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