8 from nose.tools import * # for assert functions
9 from sys import version_info as python_version
11 logger = logging.getLogger(__name__)
14 'BUILDDIR' : os.path.join(os.path.split(__file__)[0], "../../build"),
15 'REMOVE_TEMPLATE' : False,
16 'KEEP_TEST_DB' : False,
21 'TEMPLATE_DB' : 'test_template_nominatim',
22 'TEST_DB' : 'test_nominatim',
23 'API_TEST_DB' : 'test_api_nominatim',
24 'TEST_SETTINGS_FILE' : '/tmp/nominatim_settings.php',
25 'SERVER_MODULE_PATH' : None,
26 'PHPCOV' : False, # set to output directory to enable code coverage
29 use_step_matcher("re")
31 class NominatimEnvironment(object):
32 """ Collects all functions for the execution of Nominatim functions.
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 os.environ['NOMINATIM_SETTINGS'] = self.local_settings_file
53 self.template_db_done = False
55 def connect_database(self, dbname):
56 dbargs = {'database': dbname}
58 dbargs['host'] = self.db_host
60 dbargs['port'] = self.db_port
62 dbargs['user'] = self.db_user
64 dbargs['password'] = self.db_pass
65 conn = psycopg2.connect(**dbargs)
68 def next_code_coverage_file(self):
69 fn = os.path.join(self.code_coverage_path, "%06d.cov" % self.code_coverage_id)
70 self.code_coverage_id += 1
74 def write_nominatim_config(self, dbname):
75 f = open(self.local_settings_file, 'w')
76 # https://secure.php.net/manual/en/ref.pdo-pgsql.connection.php
77 f.write("<?php\n @define('CONST_Database_DSN', 'pgsql:dbname=%s%s%s%s%s');\n" %
79 (';host=' + self.db_host) if self.db_host else '',
80 (';port=' + self.db_port) if self.db_port else '',
81 (';user=' + self.db_user) if self.db_user else '',
82 (';password=' + self.db_pass) if self.db_pass else ''
84 f.write("@define('CONST_Osm2pgsql_Flatnode_File', null);\n")
85 f.write("@define('CONST_Import_Style', CONST_DataDir.'/settings/import-full.style');\n")
86 f.write("@define('CONST_Use_US_Tiger_Data', true);\n")
91 os.remove(self.local_settings_file)
93 pass # ignore missing file
95 def db_drop_database(self, name):
96 conn = self.connect_database('postgres')
97 conn.set_isolation_level(0)
99 cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
102 def setup_template_db(self):
103 if self.template_db_done:
106 self.template_db_done = True
108 if self.reuse_template:
109 # check that the template is there
110 conn = self.connect_database('postgres')
112 cur.execute('select count(*) from pg_database where datname = %s',
114 if cur.fetchone()[0] == 1:
118 # just in case... make sure a previous table has been dropped
119 self.db_drop_database(self.template_db)
122 # call the first part of database setup
123 self.write_nominatim_config(self.template_db)
124 self.run_setup_script('create-db', 'setup-db')
125 # remove external data to speed up indexing for tests
126 conn = self.connect_database(self.template_db)
128 cur.execute("""select tablename from pg_tables
129 where tablename in ('gb_postcode', 'us_postcode')""")
131 conn.cursor().execute('TRUNCATE TABLE %s' % (t[0],))
135 # execute osm2pgsql import on an empty file to get the right tables
136 with tempfile.NamedTemporaryFile(dir='/tmp', suffix='.xml') as fd:
137 fd.write(b'<osm version="0.6"></osm>')
139 self.run_setup_script('import-data',
143 'create-partition-tables',
144 'create-partition-functions',
146 'create-search-indices',
148 osm2pgsql_cache='200')
150 self.db_drop_database(self.template_db)
154 def setup_api_db(self, context):
155 self.write_nominatim_config(self.api_test_db)
157 def setup_unknown_db(self, context):
158 self.write_nominatim_config('UNKNOWN_DATABASE_NAME')
160 def setup_db(self, context):
161 self.setup_template_db()
162 self.write_nominatim_config(self.test_db)
163 conn = self.connect_database(self.template_db)
164 conn.set_isolation_level(0)
166 cur.execute('DROP DATABASE IF EXISTS %s' % (self.test_db, ))
167 cur.execute('CREATE DATABASE %s TEMPLATE = %s' % (self.test_db, self.template_db))
169 context.db = self.connect_database(self.test_db)
170 if python_version[0] < 3:
171 psycopg2.extras.register_hstore(context.db, globally=False, unicode=True)
173 psycopg2.extras.register_hstore(context.db, globally=False)
175 def teardown_db(self, context):
179 if not self.keep_scenario_db:
180 self.db_drop_database(self.test_db)
182 def run_setup_script(self, *args, **kwargs):
183 if self.server_module_path:
184 kwargs = dict(kwargs)
185 kwargs['module_path'] = self.server_module_path
186 self.run_nominatim_script('setup', *args, **kwargs)
188 def run_update_script(self, *args, **kwargs):
189 self.run_nominatim_script('update', *args, **kwargs)
191 def run_nominatim_script(self, script, *args, **kwargs):
192 cmd = ['/usr/bin/env', 'php', '-Cq']
193 cmd.append(os.path.join(self.build_dir, 'utils', '%s.php' % script))
194 cmd.extend(['--%s' % x for x in args])
195 for k, v in kwargs.items():
196 cmd.extend(('--' + k.replace('_', '-'), str(v)))
197 proc = subprocess.Popen(cmd, cwd=self.build_dir,
198 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
199 (outp, outerr) = proc.communicate()
200 outerr = outerr.decode('utf-8').replace('\\n', '\n')
201 logger.debug("run_nominatim_script: %s\n%s\n%s" % (cmd, outp, outerr))
202 assert (proc.returncode == 0), "Script '%s' failed:\n%s\n%s\n" % (script, outp, outerr)
205 class OSMDataFactory(object):
208 scriptpath = os.path.dirname(os.path.abspath(__file__))
209 self.scene_path = os.environ.get('SCENE_PATH',
210 os.path.join(scriptpath, '..', 'scenes', 'data'))
211 self.scene_cache = {}
214 def parse_geometry(self, geom, scene):
215 if geom.find(':') >= 0:
216 return "ST_SetSRID(%s, 4326)" % self.get_scene_geometry(scene, geom)
218 if geom.find(',') < 0:
219 out = "POINT(%s)" % self.mk_wkt_point(geom)
220 elif geom.find('(') < 0:
221 line = ','.join([self.mk_wkt_point(x) for x in geom.split(',')])
222 out = "LINESTRING(%s)" % line
224 inner = geom.strip('() ')
225 line = ','.join([self.mk_wkt_point(x) for x in inner.split(',')])
226 out = "POLYGON((%s))" % line
228 return "ST_SetSRID('%s'::geometry, 4326)" % out
230 def mk_wkt_point(self, point):
232 if geom.find(' ') >= 0:
235 pt = self.grid_node(int(geom))
236 assert_is_not_none(pt, "Point not found in grid")
239 def get_scene_geometry(self, default_scene, name):
241 for obj in name.split('+'):
243 if oname.startswith(':'):
244 assert_is_not_none(default_scene, "You need to set a scene")
245 defscene = self.load_scene(default_scene)
246 wkt = defscene[oname[1:]]
248 scene, obj = oname.split(':', 2)
249 scene_geoms = self.load_scene(scene)
250 wkt = scene_geoms[obj]
252 geoms.append("'%s'::geometry" % wkt)
257 return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
259 def load_scene(self, name):
260 if name in self.scene_cache:
261 return self.scene_cache[name]
264 with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
267 obj, wkt = line.split('|', 2)
268 scene[obj.strip()] = wkt.strip()
269 self.scene_cache[name] = scene
273 def clear_grid(self):
276 def add_grid_node(self, nodeid, x, y):
277 self.grid[nodeid] = (x, y)
279 def grid_node(self, nodeid):
280 return self.grid.get(nodeid)
283 def before_all(context):
285 context.config.setup_logging()
287 for k,v in userconfig.items():
288 context.config.userdata.setdefault(k, v)
289 logging.debug('User config: %s' %(str(context.config.userdata)))
290 # Nominatim test setup
291 context.nominatim = NominatimEnvironment(context.config.userdata)
292 context.osm = OSMDataFactory()
294 def after_all(context):
295 context.nominatim.cleanup()
298 def before_scenario(context, scenario):
299 if 'DB' in context.tags:
300 context.nominatim.setup_db(context)
301 elif 'APIDB' in context.tags:
302 context.nominatim.setup_api_db(context)
303 elif 'UNKNOWNDB' in context.tags:
304 context.nominatim.setup_unknown_db(context)
307 def after_scenario(context, scenario):
308 if 'DB' in context.tags:
309 context.nominatim.teardown_db(context)