7 from nose.tools import * # for assert functions
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,
16 'TEMPLATE_DB' : 'test_template_nominatim',
17 'TEST_DB' : 'test_nominatim',
18 'API_TEST_DB' : 'test_api_nominatim',
19 'TEST_SETTINGS_FILE' : '/tmp/nominatim_settings.php'
22 use_step_matcher("re")
24 class NominatimEnvironment(object):
25 """ Collects all functions for the execution of Nominatim functions.
28 def __init__(self, config):
29 self.build_dir = os.path.abspath(config['BUILDDIR'])
30 self.template_db = config['TEMPLATE_DB']
31 self.test_db = config['TEST_DB']
32 self.api_test_db = config['API_TEST_DB']
33 self.local_settings_file = config['TEST_SETTINGS_FILE']
34 self.reuse_template = not config['REMOVE_TEMPLATE']
35 self.keep_scenario_db = config['KEEP_TEST_DB']
36 os.environ['NOMINATIM_SETTINGS'] = self.local_settings_file
38 self.template_db_done = False
40 def write_nominatim_config(self, dbname):
41 f = open(self.local_settings_file, 'w')
42 f.write("<?php\n @define('CONST_Database_DSN', 'pgsql://@/%s');\n" % dbname)
47 os.remove(self.local_settings_file)
49 pass # ignore missing file
51 def db_drop_database(self, name):
52 conn = psycopg2.connect(database='postgres')
53 conn.set_isolation_level(0)
55 cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
58 def setup_template_db(self):
59 if self.template_db_done:
62 self.template_db_done = True
64 if self.reuse_template:
65 # check that the template is there
66 conn = psycopg2.connect(database='postgres')
68 cur.execute('select count(*) from pg_database where datname = %s',
70 if cur.fetchone()[0] == 1:
74 # just in case... make sure a previous table has been dropped
75 self.db_drop_database(self.template_db)
77 # call the first part of database setup
78 self.write_nominatim_config(self.template_db)
79 self.run_setup_script('create-db', 'setup-db')
80 # remove external data to speed up indexing for tests
81 conn = psycopg2.connect(database=self.template_db)
83 cur.execute("""select tablename from pg_tables
84 where tablename in ('gb_postcode', 'us_postcode')""")
86 conn.cursor().execute('TRUNCATE TABLE %s' % (t[0],))
90 # execute osm2pgsql on an empty file to get the right tables
91 osm2pgsql = os.path.join(self.build_dir, 'osm2pgsql', 'osm2pgsql')
92 proc = subprocess.Popen([osm2pgsql, '-lsc', '-r', 'xml',
93 '-O', 'gazetteer', '-d', self.template_db, '-'],
94 cwd=self.build_dir, stdin=subprocess.PIPE,
95 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
96 [outstr, errstr] = proc.communicate(input=b'<osm version="0.6"></osm>')
97 logger.debug("running osm2pgsql for template: %s\n%s\n%s" % (osm2pgsql, outstr, errstr))
98 self.run_setup_script('create-functions', 'create-tables',
99 'create-partition-tables', 'create-partition-functions',
100 'load-data', 'create-search-indices')
102 def setup_api_db(self, context):
103 self.write_nominatim_config(self.api_test_db)
105 def setup_db(self, context):
106 self.setup_template_db()
107 self.write_nominatim_config(self.test_db)
108 conn = psycopg2.connect(database=self.template_db)
109 conn.set_isolation_level(0)
111 cur.execute('DROP DATABASE IF EXISTS %s' % (self.test_db, ))
112 cur.execute('CREATE DATABASE %s TEMPLATE = %s' % (self.test_db, self.template_db))
114 context.db = psycopg2.connect(database=self.test_db)
115 if python_version[0] < 3:
116 psycopg2.extras.register_hstore(context.db, globally=False, unicode=True)
118 psycopg2.extras.register_hstore(context.db, globally=False)
120 def teardown_db(self, context):
124 if not self.keep_scenario_db:
125 self.db_drop_database(self.test_db)
127 def run_setup_script(self, *args, **kwargs):
128 self.run_nominatim_script('setup', *args, **kwargs)
130 def run_update_script(self, *args, **kwargs):
131 self.run_nominatim_script('update', *args, **kwargs)
133 def run_nominatim_script(self, script, *args, **kwargs):
134 cmd = [os.path.join(self.build_dir, 'utils', '%s.php' % script)]
135 cmd.extend(['--%s' % x for x in args])
136 for k, v in kwargs.items():
137 cmd.extend(('--' + k.replace('_', '-'), str(v)))
138 proc = subprocess.Popen(cmd, cwd=self.build_dir,
139 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
140 (outp, outerr) = proc.communicate()
141 logger.debug("run_nominatim_script: %s\n%s\n%s" % (cmd, outp, outerr))
142 assert (proc.returncode == 0), "Script '%s' failed:\n%s\n%s\n" % (script, outp, outerr)
145 class OSMDataFactory(object):
148 scriptpath = os.path.dirname(os.path.abspath(__file__))
149 self.scene_path = os.environ.get('SCENE_PATH',
150 os.path.join(scriptpath, '..', 'scenes', 'data'))
151 self.scene_cache = {}
154 def parse_geometry(self, geom, scene):
155 if geom.find(':') >= 0:
156 return "ST_SetSRID(%s, 4326)" % self.get_scene_geometry(scene, geom)
158 if geom.find(',') < 0:
159 out = "POINT(%s)" % self.mk_wkt_point(geom)
160 elif geom.find('(') < 0:
161 line = ','.join([self.mk_wkt_point(x) for x in geom.split(',')])
162 out = "LINESTRING(%s)" % line
164 inner = geom.strip('() ')
165 line = ','.join([self.mk_wkt_point(x) for x in inner.split(',')])
166 out = "POLYGON((%s))" % line
168 return "ST_SetSRID('%s'::geometry, 4326)" % out
170 def mk_wkt_point(self, point):
172 if geom.find(' ') >= 0:
175 pt = self.grid_node(int(geom))
176 assert_is_not_none(pt, "Point not found in grid")
179 def get_scene_geometry(self, default_scene, name):
181 for obj in name.split('+'):
183 if oname.startswith(':'):
184 assert_is_not_none(default_scene, "You need to set a scene")
185 defscene = self.load_scene(default_scene)
186 wkt = defscene[oname[1:]]
188 scene, obj = oname.split(':', 2)
189 scene_geoms = self.load_scene(scene)
190 wkt = scene_geoms[obj]
192 geoms.append("'%s'::geometry" % wkt)
197 return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
199 def load_scene(self, name):
200 if name in self.scene_cache:
201 return self.scene_cache[name]
204 with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
207 obj, wkt = line.split('|', 2)
208 scene[obj.strip()] = wkt.strip()
209 self.scene_cache[name] = scene
213 def clear_grid(self):
216 def add_grid_node(self, nodeid, x, y):
217 self.grid[nodeid] = (x, y)
219 def grid_node(self, nodeid):
220 return self.grid.get(nodeid)
223 def before_all(context):
225 context.config.setup_logging()
227 for k,v in userconfig.items():
228 context.config.userdata.setdefault(k, v)
229 logging.debug('User config: %s' %(str(context.config.userdata)))
230 # Nominatim test setup
231 context.nominatim = NominatimEnvironment(context.config.userdata)
232 context.osm = OSMDataFactory()
234 def after_all(context):
235 context.nominatim.cleanup()
238 def before_scenario(context, scenario):
239 if 'DB' in context.tags:
240 context.nominatim.setup_db(context)
241 elif 'APIDB' in context.tags:
242 context.nominatim.setup_api_db(context)
245 def after_scenario(context, scenario):
246 if 'DB' in context.tags:
247 context.nominatim.teardown_db(context)