8 from sys import version_info as python_version
10 logger = logging.getLogger(__name__)
13 'BUILDDIR' : os.path.join(os.path.split(__file__)[0], "../../build"),
14 'REMOVE_TEMPLATE' : False,
15 'KEEP_TEST_DB' : False,
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
27 use_step_matcher("re")
30 class NominatimEnvironment(object):
31 """ Collects all functions for the execution of Nominatim functions.
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
51 self.template_db_done = False
52 self.website_dir = None
54 def connect_database(self, dbname):
55 dbargs = {'database': dbname}
57 dbargs['host'] = self.db_host
59 dbargs['port'] = self.db_port
61 dbargs['user'] = self.db_user
63 dbargs['password'] = self.db_pass
64 conn = psycopg2.connect(**dbargs)
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
73 def write_nominatim_config(self, dbname):
74 dsn = 'pgsql:dbname={}{}{}{}{}'.format(
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 ''
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
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'
93 if self.website_dir is not None:
94 self.website_dir.cleanup()
96 self.website_dir = tempfile.TemporaryDirectory()
97 self.run_setup_script('setup-website')
100 def db_drop_database(self, name):
101 conn = self.connect_database('postgres')
102 conn.set_isolation_level(0)
104 cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
107 def setup_template_db(self):
108 if self.template_db_done:
111 self.template_db_done = True
113 if self.reuse_template:
114 # check that the template is there
115 conn = self.connect_database('postgres')
117 cur.execute('select count(*) from pg_database where datname = %s',
119 if cur.fetchone()[0] == 1:
123 # just in case... make sure a previous table has been dropped
124 self.db_drop_database(self.template_db)
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)
133 cur.execute("""select tablename from pg_tables
134 where tablename in ('gb_postcode', 'us_postcode')""")
136 conn.cursor().execute('TRUNCATE TABLE %s' % (t[0],))
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>')
144 self.run_setup_script('import-data',
148 'create-partition-tables',
149 'create-partition-functions',
151 'create-search-indices',
153 osm2pgsql_cache='200')
155 self.db_drop_database(self.template_db)
159 def setup_api_db(self, context):
160 self.write_nominatim_config(self.api_test_db)
162 def setup_unknown_db(self, context):
163 self.write_nominatim_config('UNKNOWN_DATABASE_NAME')
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)
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))
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)
178 psycopg2.extras.register_hstore(context.db, globally=False)
180 def teardown_db(self, context):
184 if not self.keep_scenario_db:
185 self.db_drop_database(self.test_db)
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)
193 def run_update_script(self, *args, **kwargs):
194 self.run_nominatim_script('update', *args, **kwargs)
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)))
203 if self.website_dir is not None:
204 cwd = self.website_dir.name
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)
216 class OSMDataFactory(object):
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 = {}
225 def parse_geometry(self, geom, scene):
226 if geom.find(':') >= 0:
227 return "ST_SetSRID(%s, 4326)" % self.get_scene_geometry(scene, geom)
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
235 inner = geom.strip('() ')
236 line = ','.join([self.mk_wkt_point(x) for x in inner.split(',')])
237 out = "POLYGON((%s))" % line
239 return "ST_SetSRID('%s'::geometry, 4326)" % out
241 def mk_wkt_point(self, point):
243 if geom.find(' ') >= 0:
246 pt = self.grid_node(int(geom))
247 assert pt is not None, "Bad scenario: Point '{}' not found in grid".format(geom)
250 def get_scene_geometry(self, default_scene, name):
252 for obj in name.split('+'):
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:]]
259 scene, obj = oname.split(':', 2)
260 scene_geoms = self.load_scene(scene)
261 wkt = scene_geoms[obj]
263 geoms.append("'%s'::geometry" % wkt)
268 return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
270 def load_scene(self, name):
271 if name in self.scene_cache:
272 return self.scene_cache[name]
275 with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
278 obj, wkt = line.split('|', 2)
279 scene[obj.strip()] = wkt.strip()
280 self.scene_cache[name] = scene
284 def clear_grid(self):
287 def add_grid_node(self, nodeid, x, y):
288 self.grid[nodeid] = (x, y)
290 def grid_node(self, nodeid):
291 return self.grid.get(nodeid)
294 def before_all(context):
296 context.config.setup_logging()
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()
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)
315 def after_scenario(context, scenario):
316 if 'DB' in context.tags:
317 context.nominatim.teardown_db(context)