]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/environment.py
3ce3c83a36e83856228aa765aa44a976207e0b36
[nominatim.git] / test / bdd / environment.py
1 from behave import *
2 import logging
3 import os
4 import psycopg2
5 import psycopg2.extras
6 import subprocess
7 from sys import version_info as python_version
8
9 logger = logging.getLogger(__name__)
10
11 userconfig = {
12     'BASEURL' : 'http://localhost/nominatim',
13     'BUILDDIR' : '../build',
14     'REMOVE_TEMPLATE' : False,
15     'KEEP_TEST_DB' : False,
16     'TEMPLATE_DB' : 'test_template_nominatim',
17     'TEST_DB' : 'test_nominatim',
18     'TEST_SETTINGS_FILE' : '/tmp/nominatim_settings.php'
19 }
20
21 use_step_matcher("re")
22
23 class NominatimEnvironment(object):
24     """ Collects all functions for the execution of Nominatim functions.
25     """
26
27     def __init__(self, config):
28         self.build_dir = os.path.abspath(config['BUILDDIR'])
29         self.template_db = config['TEMPLATE_DB']
30         self.test_db = config['TEST_DB']
31         self.local_settings_file = config['TEST_SETTINGS_FILE']
32         self.reuse_template = not config['REMOVE_TEMPLATE']
33         self.keep_scenario_db = config['KEEP_TEST_DB']
34         os.environ['NOMINATIM_SETTINGS'] = self.local_settings_file
35
36         self.template_db_done = False
37
38     def write_nominatim_config(self, dbname):
39         f = open(self.local_settings_file, 'w')
40         f.write("<?php\n  @define('CONST_Database_DSN', 'pgsql://@/%s');\n" % dbname)
41         f.close()
42
43     def cleanup(self):
44         try:
45             os.remove(self.local_settings_file)
46         except OSError:
47             pass # ignore missing file
48
49     def db_drop_database(self, name):
50         conn = psycopg2.connect(database='postgres')
51         conn.set_isolation_level(0)
52         cur = conn.cursor()
53         cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
54         conn.close()
55
56     def setup_template_db(self):
57         if self.template_db_done:
58             return
59
60         self.template_db_done = True
61
62         if self.reuse_template:
63             # check that the template is there
64             conn = psycopg2.connect(database='postgres')
65             cur = conn.cursor()
66             cur.execute('select count(*) from pg_database where datname = %s',
67                         (self.template_db,))
68             if cur.fetchone()[0] == 1:
69                 return
70             conn.close()
71         else:
72             # just in case... make sure a previous table has been dropped
73             self.db_drop_database(self.template_db)
74
75         # call the first part of database setup
76         self.write_nominatim_config(self.template_db)
77         self.run_setup_script('create-db', 'setup-db')
78         # remove external data to speed up indexing for tests
79         conn = psycopg2.connect(database=self.template_db)
80         cur = conn.cursor()
81         cur.execute("""select tablename from pg_tables
82                        where tablename in ('gb_postcode', 'us_postcode')""")
83         for t in cur:
84             conn.cursor().execute('TRUNCATE TABLE %s' % (t[0],))
85         conn.commit()
86         conn.close()
87
88         # execute osm2pgsql on an empty file to get the right tables
89         osm2pgsql = os.path.join(self.build_dir, 'osm2pgsql', 'osm2pgsql')
90         proc = subprocess.Popen([osm2pgsql, '-lsc', '-r', 'xml',
91                                  '-O', 'gazetteer', '-d', self.template_db, '-'],
92                                 cwd=self.build_dir, stdin=subprocess.PIPE,
93                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
94         [outstr, errstr] = proc.communicate(input=b'<osm version="0.6"></osm>')
95         logger.debug("running osm2pgsql for template: %s\n%s\n%s" % (osm2pgsql, outstr, errstr))
96         self.run_setup_script('create-functions', 'create-tables',
97                               'create-partition-tables', 'create-partition-functions',
98                               'load-data', 'create-search-indices')
99
100
101
102     def setup_db(self, context):
103         self.setup_template_db()
104         self.write_nominatim_config(self.test_db)
105         conn = psycopg2.connect(database=self.template_db)
106         conn.set_isolation_level(0)
107         cur = conn.cursor()
108         cur.execute('DROP DATABASE IF EXISTS %s' % (self.test_db, ))
109         cur.execute('CREATE DATABASE %s TEMPLATE = %s' % (self.test_db, self.template_db))
110         conn.close()
111         context.db = psycopg2.connect(database=self.test_db)
112         if python_version[0] < 3:
113             psycopg2.extras.register_hstore(context.db, globally=False, unicode=True)
114         else:
115             psycopg2.extras.register_hstore(context.db, globally=False)
116
117     def teardown_db(self, context):
118         if 'db' in context:
119             context.db.close()
120
121         if not self.keep_scenario_db:
122             self.db_drop_database(self.test_db)
123
124     def run_setup_script(self, *args):
125         self.run_nominatim_script('setup', *args)
126
127     def run_nominatim_script(self, script, *args):
128         cmd = [os.path.join(self.build_dir, 'utils', '%s.php' % script)]
129         cmd.extend(['--%s' % x for x in args])
130         proc = subprocess.Popen(cmd, cwd=self.build_dir,
131                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
132         (outp, outerr) = proc.communicate()
133         logger.debug("run_nominatim_script: %s\n%s\n%s" % (cmd, outp, outerr))
134         assert (proc.returncode == 0), "Script '%s' failed:\n%s\n%s\n" % (script, outp, outerr)
135
136
137 class OSMDataFactory(object):
138
139     def __init__(self):
140         scriptpath = os.path.dirname(os.path.abspath(__file__))
141         self.scene_path = os.environ.get('SCENE_PATH',
142                            os.path.join(scriptpath, '..', 'scenes', 'data'))
143
144     def make_geometry(self, geom):
145         if geom.find(',') < 0:
146             return 'POINT(%s)' % geom
147
148         if geom.find('(') < 0:
149             return 'LINESTRING(%s)' % geom
150
151         return 'POLYGON(%s)' % geom
152
153
154 def before_all(context):
155     # logging setup
156     context.config.setup_logging()
157     # set up -D options
158     for k,v in userconfig.items():
159         context.config.userdata.setdefault(k, v)
160     logging.debug('User config: %s' %(str(context.config.userdata)))
161     # Nominatim test setup
162     context.nominatim = NominatimEnvironment(context.config.userdata)
163     context.osm = OSMDataFactory()
164
165 def after_all(context):
166     context.nominatim.cleanup()
167
168
169 def before_scenario(context, scenario):
170     if 'DB' in context.tags:
171         context.nominatim.setup_db(context)
172
173 def after_scenario(context, scenario):
174     if 'DB' in context.tags:
175         context.nominatim.teardown_db(context)
176