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,
17 'TEMPLATE_DB' : 'test_template_nominatim',
18 'TEST_DB' : 'test_nominatim',
19 'API_TEST_DB' : 'test_api_nominatim',
20 'TEST_SETTINGS_FILE' : '/tmp/nominatim_settings.php',
21 'PHPCOV' : False, # set to output directory to enable code coverage
24 use_step_matcher("re")
26 class NominatimEnvironment(object):
27 """ Collects all functions for the execution of Nominatim functions.
30 def __init__(self, config):
31 self.build_dir = os.path.abspath(config['BUILDDIR'])
32 self.src_dir = os.path.abspath(os.path.join(os.path.split(__file__)[0], "../.."))
33 self.template_db = config['TEMPLATE_DB']
34 self.test_db = config['TEST_DB']
35 self.api_test_db = config['API_TEST_DB']
36 self.local_settings_file = config['TEST_SETTINGS_FILE']
37 self.reuse_template = not config['REMOVE_TEMPLATE']
38 self.keep_scenario_db = config['KEEP_TEST_DB']
39 self.code_coverage_path = config['PHPCOV']
40 self.code_coverage_id = 1
41 os.environ['NOMINATIM_SETTINGS'] = self.local_settings_file
43 self.template_db_done = False
45 def next_code_coverage_file(self):
46 fn = os.path.join(self.code_coverage_path, "%06d.cov" % self.code_coverage_id)
47 self.code_coverage_id += 1
51 def write_nominatim_config(self, dbname):
52 f = open(self.local_settings_file, 'w')
53 f.write("<?php\n @define('CONST_Database_DSN', 'pgsql://@/%s');\n" % dbname)
54 f.write("@define('CONST_Osm2pgsql_Flatnode_File', null);\n")
59 os.remove(self.local_settings_file)
61 pass # ignore missing file
63 def db_drop_database(self, name):
64 conn = psycopg2.connect(database='postgres')
65 conn.set_isolation_level(0)
67 cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
70 def setup_template_db(self):
71 if self.template_db_done:
74 self.template_db_done = True
76 if self.reuse_template:
77 # check that the template is there
78 conn = psycopg2.connect(database='postgres')
80 cur.execute('select count(*) from pg_database where datname = %s',
82 if cur.fetchone()[0] == 1:
86 # just in case... make sure a previous table has been dropped
87 self.db_drop_database(self.template_db)
89 # call the first part of database setup
90 self.write_nominatim_config(self.template_db)
91 self.run_setup_script('create-db', 'setup-db')
92 # remove external data to speed up indexing for tests
93 conn = psycopg2.connect(database=self.template_db)
95 cur.execute("""select tablename from pg_tables
96 where tablename in ('gb_postcode', 'us_postcode')""")
98 conn.cursor().execute('TRUNCATE TABLE %s' % (t[0],))
102 # execute osm2pgsql import on an empty file to get the right tables
103 with tempfile.NamedTemporaryFile(dir='/tmp', suffix='.xml') as fd:
104 fd.write(b'<osm version="0.6"></osm>')
106 self.run_setup_script('import-data',
110 'create-partition-tables',
111 'create-partition-functions',
113 'create-search-indices',
115 osm2pgsql_cache='200')
117 def setup_api_db(self, context):
118 self.write_nominatim_config(self.api_test_db)
120 def setup_db(self, context):
121 self.setup_template_db()
122 self.write_nominatim_config(self.test_db)
123 conn = psycopg2.connect(database=self.template_db)
124 conn.set_isolation_level(0)
126 cur.execute('DROP DATABASE IF EXISTS %s' % (self.test_db, ))
127 cur.execute('CREATE DATABASE %s TEMPLATE = %s' % (self.test_db, self.template_db))
129 context.db = psycopg2.connect(database=self.test_db)
130 if python_version[0] < 3:
131 psycopg2.extras.register_hstore(context.db, globally=False, unicode=True)
133 psycopg2.extras.register_hstore(context.db, globally=False)
135 def teardown_db(self, context):
139 if not self.keep_scenario_db:
140 self.db_drop_database(self.test_db)
142 def run_setup_script(self, *args, **kwargs):
143 self.run_nominatim_script('setup', *args, **kwargs)
145 def run_update_script(self, *args, **kwargs):
146 self.run_nominatim_script('update', *args, **kwargs)
148 def run_nominatim_script(self, script, *args, **kwargs):
149 cmd = [os.path.join(self.build_dir, 'utils', '%s.php' % script)]
150 cmd.extend(['--%s' % x for x in args])
151 for k, v in kwargs.items():
152 cmd.extend(('--' + k.replace('_', '-'), str(v)))
153 proc = subprocess.Popen(cmd, cwd=self.build_dir,
154 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
155 (outp, outerr) = proc.communicate()
156 logger.debug("run_nominatim_script: %s\n%s\n%s" % (cmd, outp, outerr))
157 assert (proc.returncode == 0), "Script '%s' failed:\n%s\n%s\n" % (script, outp, outerr)
160 class OSMDataFactory(object):
163 scriptpath = os.path.dirname(os.path.abspath(__file__))
164 self.scene_path = os.environ.get('SCENE_PATH',
165 os.path.join(scriptpath, '..', 'scenes', 'data'))
166 self.scene_cache = {}
169 def parse_geometry(self, geom, scene):
170 if geom.find(':') >= 0:
171 return "ST_SetSRID(%s, 4326)" % self.get_scene_geometry(scene, geom)
173 if geom.find(',') < 0:
174 out = "POINT(%s)" % self.mk_wkt_point(geom)
175 elif geom.find('(') < 0:
176 line = ','.join([self.mk_wkt_point(x) for x in geom.split(',')])
177 out = "LINESTRING(%s)" % line
179 inner = geom.strip('() ')
180 line = ','.join([self.mk_wkt_point(x) for x in inner.split(',')])
181 out = "POLYGON((%s))" % line
183 return "ST_SetSRID('%s'::geometry, 4326)" % out
185 def mk_wkt_point(self, point):
187 if geom.find(' ') >= 0:
190 pt = self.grid_node(int(geom))
191 assert_is_not_none(pt, "Point not found in grid")
194 def get_scene_geometry(self, default_scene, name):
196 for obj in name.split('+'):
198 if oname.startswith(':'):
199 assert_is_not_none(default_scene, "You need to set a scene")
200 defscene = self.load_scene(default_scene)
201 wkt = defscene[oname[1:]]
203 scene, obj = oname.split(':', 2)
204 scene_geoms = self.load_scene(scene)
205 wkt = scene_geoms[obj]
207 geoms.append("'%s'::geometry" % wkt)
212 return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
214 def load_scene(self, name):
215 if name in self.scene_cache:
216 return self.scene_cache[name]
219 with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
222 obj, wkt = line.split('|', 2)
223 scene[obj.strip()] = wkt.strip()
224 self.scene_cache[name] = scene
228 def clear_grid(self):
231 def add_grid_node(self, nodeid, x, y):
232 self.grid[nodeid] = (x, y)
234 def grid_node(self, nodeid):
235 return self.grid.get(nodeid)
238 def before_all(context):
240 context.config.setup_logging()
242 for k,v in userconfig.items():
243 context.config.userdata.setdefault(k, v)
244 logging.debug('User config: %s' %(str(context.config.userdata)))
245 # Nominatim test setup
246 context.nominatim = NominatimEnvironment(context.config.userdata)
247 context.osm = OSMDataFactory()
249 def after_all(context):
250 context.nominatim.cleanup()
253 def before_scenario(context, scenario):
254 if 'DB' in context.tags:
255 context.nominatim.setup_db(context)
256 elif 'APIDB' in context.tags:
257 context.nominatim.setup_api_db(context)
260 def after_scenario(context, scenario):
261 if 'DB' in context.tags:
262 context.nominatim.teardown_db(context)