]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/environment.py
create a temporary project dir for tests
[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 import tempfile
8 from sys import version_info as python_version
9
10 logger = logging.getLogger(__name__)
11
12 userconfig = {
13     'BUILDDIR' : os.path.join(os.path.split(__file__)[0], "../../build"),
14     'REMOVE_TEMPLATE' : False,
15     'KEEP_TEST_DB' : False,
16     'DB_HOST' : None,
17     'DB_PORT' : None,
18     'DB_USER' : None,
19     'DB_PASS' : None,
20     'TEMPLATE_DB' : 'test_template_nominatim',
21     'TEST_DB' : 'test_nominatim',
22     'API_TEST_DB' : 'test_api_nominatim',
23     'SERVER_MODULE_PATH' : None,
24     'PHPCOV' : False, # set to output directory to enable code coverage
25 }
26
27 use_step_matcher("re")
28
29
30 class NominatimEnvironment(object):
31     """ Collects all functions for the execution of Nominatim functions.
32     """
33
34     def __init__(self, config):
35         self.build_dir = os.path.abspath(config['BUILDDIR'])
36         self.src_dir = os.path.abspath(os.path.join(os.path.split(__file__)[0], "../.."))
37         self.db_host = config['DB_HOST']
38         self.db_port = config['DB_PORT']
39         self.db_user = config['DB_USER']
40         self.db_pass = config['DB_PASS']
41         self.template_db = config['TEMPLATE_DB']
42         self.test_db = config['TEST_DB']
43         self.api_test_db = config['API_TEST_DB']
44         self.server_module_path = config['SERVER_MODULE_PATH']
45         self.reuse_template = not config['REMOVE_TEMPLATE']
46         self.keep_scenario_db = config['KEEP_TEST_DB']
47         self.code_coverage_path = config['PHPCOV']
48         self.code_coverage_id = 1
49         self.test_env = None
50
51         self.template_db_done = False
52         self.website_dir = None
53
54     def connect_database(self, dbname):
55         dbargs = {'database': dbname}
56         if self.db_host:
57             dbargs['host'] = self.db_host
58         if self.db_port:
59             dbargs['port'] = self.db_port
60         if self.db_user:
61             dbargs['user'] = self.db_user
62         if self.db_pass:
63             dbargs['password'] = self.db_pass
64         conn = psycopg2.connect(**dbargs)
65         return conn
66
67     def next_code_coverage_file(self):
68         fn = os.path.join(self.code_coverage_path, "%06d.cov" % self.code_coverage_id)
69         self.code_coverage_id += 1
70
71         return fn
72
73     def write_nominatim_config(self, dbname):
74         dsn = 'pgsql:dbname={}{}{}{}{}'.format(
75                 dbname,
76                  (';host=' + self.db_host) if self.db_host else '',
77                  (';port=' + self.db_port) if self.db_port else '',
78                  (';user=' + self.db_user) if self.db_user else '',
79                  (';password=' + self.db_pass) if self.db_pass else ''
80                  )
81
82         if self.website_dir is not None \
83            and self.test_env is not None \
84            and dsn == self.test_env['NOMINATIM_DATABASE_DSN']:
85             return # environment already set uo
86
87         self.test_env = os.environ
88         self.test_env['NOMINATIM_DATABASE_DSN'] = dsn
89         self.test_env['NOMINATIM_FLATNODE_FILE'] = ''
90         self.test_env['NOMINATIM_IMPORT_STYLE'] = 'full'
91         self.test_env['NOMINATIM_USE_US_TIGER_DATA'] = 'yes'
92
93         if self.website_dir is not None:
94             self.website_dir.cleanup()
95
96         self.website_dir = tempfile.TemporaryDirectory()
97         self.run_setup_script('setup-website')
98
99
100     def db_drop_database(self, name):
101         conn = self.connect_database('postgres')
102         conn.set_isolation_level(0)
103         cur = conn.cursor()
104         cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
105         conn.close()
106
107     def setup_template_db(self):
108         if self.template_db_done:
109             return
110
111         self.template_db_done = True
112
113         if self.reuse_template:
114             # check that the template is there
115             conn = self.connect_database('postgres')
116             cur = conn.cursor()
117             cur.execute('select count(*) from pg_database where datname = %s',
118                         (self.template_db,))
119             if cur.fetchone()[0] == 1:
120                 return
121             conn.close()
122         else:
123             # just in case... make sure a previous table has been dropped
124             self.db_drop_database(self.template_db)
125
126         try:
127             # call the first part of database setup
128             self.write_nominatim_config(self.template_db)
129             self.run_setup_script('create-db', 'setup-db')
130             # remove external data to speed up indexing for tests
131             conn = self.connect_database(self.template_db)
132             cur = conn.cursor()
133             cur.execute("""select tablename from pg_tables
134                            where tablename in ('gb_postcode', 'us_postcode')""")
135             for t in cur:
136                 conn.cursor().execute('TRUNCATE TABLE %s' % (t[0],))
137             conn.commit()
138             conn.close()
139
140             # execute osm2pgsql import on an empty file to get the right tables
141             with tempfile.NamedTemporaryFile(dir='/tmp', suffix='.xml') as fd:
142                 fd.write(b'<osm version="0.6"></osm>')
143                 fd.flush()
144                 self.run_setup_script('import-data',
145                                       'ignore-errors',
146                                       'create-functions',
147                                       'create-tables',
148                                       'create-partition-tables',
149                                       'create-partition-functions',
150                                       'load-data',
151                                       'create-search-indices',
152                                       osm_file=fd.name,
153                                       osm2pgsql_cache='200')
154         except:
155             self.db_drop_database(self.template_db)
156             raise
157
158
159     def setup_api_db(self, context):
160         self.write_nominatim_config(self.api_test_db)
161
162     def setup_unknown_db(self, context):
163         self.write_nominatim_config('UNKNOWN_DATABASE_NAME')
164
165     def setup_db(self, context):
166         self.setup_template_db()
167         self.write_nominatim_config(self.test_db)
168         conn = self.connect_database(self.template_db)
169         conn.set_isolation_level(0)
170         cur = conn.cursor()
171         cur.execute('DROP DATABASE IF EXISTS %s' % (self.test_db, ))
172         cur.execute('CREATE DATABASE %s TEMPLATE = %s' % (self.test_db, self.template_db))
173         conn.close()
174         context.db = self.connect_database(self.test_db)
175         if python_version[0] < 3:
176             psycopg2.extras.register_hstore(context.db, globally=False, unicode=True)
177         else:
178             psycopg2.extras.register_hstore(context.db, globally=False)
179
180     def teardown_db(self, context):
181         if 'db' in context:
182             context.db.close()
183
184         if not self.keep_scenario_db:
185             self.db_drop_database(self.test_db)
186
187     def run_setup_script(self, *args, **kwargs):
188         if self.server_module_path:
189             kwargs = dict(kwargs)
190             kwargs['module_path'] = self.server_module_path
191         self.run_nominatim_script('setup', *args, **kwargs)
192
193     def run_update_script(self, *args, **kwargs):
194         self.run_nominatim_script('update', *args, **kwargs)
195
196     def run_nominatim_script(self, script, *args, **kwargs):
197         cmd = ['/usr/bin/env', 'php', '-Cq']
198         cmd.append(os.path.join(self.build_dir, 'utils', '%s.php' % script))
199         cmd.extend(['--%s' % x for x in args])
200         for k, v in kwargs.items():
201             cmd.extend(('--' + k.replace('_', '-'), str(v)))
202
203         if self.website_dir is not None:
204             cwd = self.website_dir.name
205         else:
206             cwd = self.build_dir
207
208         proc = subprocess.Popen(cmd, cwd=cwd, env=self.test_env,
209                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
210         (outp, outerr) = proc.communicate()
211         outerr = outerr.decode('utf-8').replace('\\n', '\n')
212         logger.debug("run_nominatim_script: %s\n%s\n%s" % (cmd, outp, outerr))
213         assert (proc.returncode == 0), "Script '%s' failed:\n%s\n%s\n" % (script, outp, outerr)
214
215
216 class OSMDataFactory(object):
217
218     def __init__(self):
219         scriptpath = os.path.dirname(os.path.abspath(__file__))
220         self.scene_path = os.environ.get('SCENE_PATH',
221                            os.path.join(scriptpath, '..', 'scenes', 'data'))
222         self.scene_cache = {}
223         self.clear_grid()
224
225     def parse_geometry(self, geom, scene):
226         if geom.find(':') >= 0:
227             return "ST_SetSRID(%s, 4326)" % self.get_scene_geometry(scene, geom)
228
229         if geom.find(',') < 0:
230             out = "POINT(%s)" % self.mk_wkt_point(geom)
231         elif geom.find('(') < 0:
232             line = ','.join([self.mk_wkt_point(x) for x in geom.split(',')])
233             out = "LINESTRING(%s)" % line
234         else:
235             inner = geom.strip('() ')
236             line = ','.join([self.mk_wkt_point(x) for x in inner.split(',')])
237             out = "POLYGON((%s))" % line
238
239         return "ST_SetSRID('%s'::geometry, 4326)" % out
240
241     def mk_wkt_point(self, point):
242         geom = point.strip()
243         if geom.find(' ') >= 0:
244             return geom
245         else:
246             pt = self.grid_node(int(geom))
247             assert pt is not None, "Bad scenario: Point '{}' not found in grid".format(geom)
248             return "%f %f" % pt
249
250     def get_scene_geometry(self, default_scene, name):
251         geoms = []
252         for obj in name.split('+'):
253             oname = obj.strip()
254             if oname.startswith(':'):
255                 assert default_scene is not None, "Bad scenario: You need to set a scene"
256                 defscene = self.load_scene(default_scene)
257                 wkt = defscene[oname[1:]]
258             else:
259                 scene, obj = oname.split(':', 2)
260                 scene_geoms = self.load_scene(scene)
261                 wkt = scene_geoms[obj]
262
263             geoms.append("'%s'::geometry" % wkt)
264
265         if len(geoms) == 1:
266             return geoms[0]
267         else:
268             return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
269
270     def load_scene(self, name):
271         if name in self.scene_cache:
272             return self.scene_cache[name]
273
274         scene = {}
275         with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
276             for line in fd:
277                 if line.strip():
278                     obj, wkt = line.split('|', 2)
279                     scene[obj.strip()] = wkt.strip()
280             self.scene_cache[name] = scene
281
282         return scene
283
284     def clear_grid(self):
285         self.grid = {}
286
287     def add_grid_node(self, nodeid, x, y):
288         self.grid[nodeid] = (x, y)
289
290     def grid_node(self, nodeid):
291         return self.grid.get(nodeid)
292
293
294 def before_all(context):
295     # logging setup
296     context.config.setup_logging()
297     # set up -D options
298     for k,v in userconfig.items():
299         context.config.userdata.setdefault(k, v)
300     logging.debug('User config: %s' %(str(context.config.userdata)))
301     # Nominatim test setup
302     context.nominatim = NominatimEnvironment(context.config.userdata)
303     context.osm = OSMDataFactory()
304
305
306 def before_scenario(context, scenario):
307     if 'DB' in context.tags:
308         context.nominatim.setup_db(context)
309     elif 'APIDB' in context.tags:
310         context.nominatim.setup_api_db(context)
311     elif 'UNKNOWNDB' in context.tags:
312         context.nominatim.setup_unknown_db(context)
313     context.scene = None
314
315 def after_scenario(context, scenario):
316     if 'DB' in context.tags:
317         context.nominatim.teardown_db(context)