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'
23 use_step_matcher("re")
25 class NominatimEnvironment(object):
26 """ Collects all functions for the execution of Nominatim functions.
29 def __init__(self, config):
30 self.build_dir = os.path.abspath(config['BUILDDIR'])
31 self.template_db = config['TEMPLATE_DB']
32 self.test_db = config['TEST_DB']
33 self.api_test_db = config['API_TEST_DB']
34 self.local_settings_file = config['TEST_SETTINGS_FILE']
35 self.reuse_template = not config['REMOVE_TEMPLATE']
36 self.keep_scenario_db = config['KEEP_TEST_DB']
37 os.environ['NOMINATIM_SETTINGS'] = self.local_settings_file
39 self.template_db_done = False
41 def write_nominatim_config(self, dbname):
42 f = open(self.local_settings_file, 'w')
43 f.write("<?php\n @define('CONST_Database_DSN', 'pgsql://@/%s');\n" % dbname)
44 f.write("@define('CONST_Osm2pgsql_Flatnode_File', null);\n")
49 os.remove(self.local_settings_file)
51 pass # ignore missing file
53 def db_drop_database(self, name):
54 conn = psycopg2.connect(database='postgres')
55 conn.set_isolation_level(0)
57 cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
60 def setup_template_db(self):
61 if self.template_db_done:
64 self.template_db_done = True
66 if self.reuse_template:
67 # check that the template is there
68 conn = psycopg2.connect(database='postgres')
70 cur.execute('select count(*) from pg_database where datname = %s',
72 if cur.fetchone()[0] == 1:
76 # just in case... make sure a previous table has been dropped
77 self.db_drop_database(self.template_db)
79 # call the first part of database setup
80 self.write_nominatim_config(self.template_db)
81 self.run_setup_script('create-db', 'setup-db')
82 # remove external data to speed up indexing for tests
83 conn = psycopg2.connect(database=self.template_db)
85 cur.execute("""select tablename from pg_tables
86 where tablename in ('gb_postcode', 'us_postcode')""")
88 conn.cursor().execute('TRUNCATE TABLE %s' % (t[0],))
92 # execute osm2pgsql import on an empty file to get the right tables
93 with tempfile.NamedTemporaryFile(dir='/tmp', suffix='.xml') as fd:
94 fd.write(b'<osm version="0.6"></osm>')
96 self.run_setup_script('import-data',
100 'create-partition-tables',
101 'create-partition-functions',
103 'create-search-indices',
105 osm2pgsql_cache='200')
107 def setup_api_db(self, context):
108 self.write_nominatim_config(self.api_test_db)
110 def setup_db(self, context):
111 self.setup_template_db()
112 self.write_nominatim_config(self.test_db)
113 conn = psycopg2.connect(database=self.template_db)
114 conn.set_isolation_level(0)
116 cur.execute('DROP DATABASE IF EXISTS %s' % (self.test_db, ))
117 cur.execute('CREATE DATABASE %s TEMPLATE = %s' % (self.test_db, self.template_db))
119 context.db = psycopg2.connect(database=self.test_db)
120 if python_version[0] < 3:
121 psycopg2.extras.register_hstore(context.db, globally=False, unicode=True)
123 psycopg2.extras.register_hstore(context.db, globally=False)
125 def teardown_db(self, context):
129 if not self.keep_scenario_db:
130 self.db_drop_database(self.test_db)
132 def run_setup_script(self, *args, **kwargs):
133 self.run_nominatim_script('setup', *args, **kwargs)
135 def run_update_script(self, *args, **kwargs):
136 self.run_nominatim_script('update', *args, **kwargs)
138 def run_nominatim_script(self, script, *args, **kwargs):
139 cmd = [os.path.join(self.build_dir, 'utils', '%s.php' % script)]
140 cmd.extend(['--%s' % x for x in args])
141 for k, v in kwargs.items():
142 cmd.extend(('--' + k.replace('_', '-'), str(v)))
143 proc = subprocess.Popen(cmd, cwd=self.build_dir,
144 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
145 (outp, outerr) = proc.communicate()
146 logger.debug("run_nominatim_script: %s\n%s\n%s" % (cmd, outp, outerr))
147 assert (proc.returncode == 0), "Script '%s' failed:\n%s\n%s\n" % (script, outp, outerr)
150 class OSMDataFactory(object):
153 scriptpath = os.path.dirname(os.path.abspath(__file__))
154 self.scene_path = os.environ.get('SCENE_PATH',
155 os.path.join(scriptpath, '..', 'scenes', 'data'))
156 self.scene_cache = {}
159 def parse_geometry(self, geom, scene):
160 if geom.find(':') >= 0:
161 return "ST_SetSRID(%s, 4326)" % self.get_scene_geometry(scene, geom)
163 if geom.find(',') < 0:
164 out = "POINT(%s)" % self.mk_wkt_point(geom)
165 elif geom.find('(') < 0:
166 line = ','.join([self.mk_wkt_point(x) for x in geom.split(',')])
167 out = "LINESTRING(%s)" % line
169 inner = geom.strip('() ')
170 line = ','.join([self.mk_wkt_point(x) for x in inner.split(',')])
171 out = "POLYGON((%s))" % line
173 return "ST_SetSRID('%s'::geometry, 4326)" % out
175 def mk_wkt_point(self, point):
177 if geom.find(' ') >= 0:
180 pt = self.grid_node(int(geom))
181 assert_is_not_none(pt, "Point not found in grid")
184 def get_scene_geometry(self, default_scene, name):
186 for obj in name.split('+'):
188 if oname.startswith(':'):
189 assert_is_not_none(default_scene, "You need to set a scene")
190 defscene = self.load_scene(default_scene)
191 wkt = defscene[oname[1:]]
193 scene, obj = oname.split(':', 2)
194 scene_geoms = self.load_scene(scene)
195 wkt = scene_geoms[obj]
197 geoms.append("'%s'::geometry" % wkt)
202 return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
204 def load_scene(self, name):
205 if name in self.scene_cache:
206 return self.scene_cache[name]
209 with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
212 obj, wkt = line.split('|', 2)
213 scene[obj.strip()] = wkt.strip()
214 self.scene_cache[name] = scene
218 def clear_grid(self):
221 def add_grid_node(self, nodeid, x, y):
222 self.grid[nodeid] = (x, y)
224 def grid_node(self, nodeid):
225 return self.grid.get(nodeid)
228 def before_all(context):
230 context.config.setup_logging()
232 for k,v in userconfig.items():
233 context.config.userdata.setdefault(k, v)
234 logging.debug('User config: %s' %(str(context.config.userdata)))
235 # Nominatim test setup
236 context.nominatim = NominatimEnvironment(context.config.userdata)
237 context.osm = OSMDataFactory()
239 def after_all(context):
240 context.nominatim.cleanup()
243 def before_scenario(context, scenario):
244 if 'DB' in context.tags:
245 context.nominatim.setup_db(context)
246 elif 'APIDB' in context.tags:
247 context.nominatim.setup_api_db(context)
250 def after_scenario(context, scenario):
251 if 'DB' in context.tags:
252 context.nominatim.teardown_db(context)