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)
43 f.write("@define('CONST_Osm2pgsql_Flatnode_File', null);\n")
48 os.remove(self.local_settings_file)
50 pass # ignore missing file
52 def db_drop_database(self, name):
53 conn = psycopg2.connect(database='postgres')
54 conn.set_isolation_level(0)
56 cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
59 def setup_template_db(self):
60 if self.template_db_done:
63 self.template_db_done = True
65 if self.reuse_template:
66 # check that the template is there
67 conn = psycopg2.connect(database='postgres')
69 cur.execute('select count(*) from pg_database where datname = %s',
71 if cur.fetchone()[0] == 1:
75 # just in case... make sure a previous table has been dropped
76 self.db_drop_database(self.template_db)
78 # call the first part of database setup
79 self.write_nominatim_config(self.template_db)
80 self.run_setup_script('create-db', 'setup-db')
81 # remove external data to speed up indexing for tests
82 conn = psycopg2.connect(database=self.template_db)
84 cur.execute("""select tablename from pg_tables
85 where tablename in ('gb_postcode', 'us_postcode')""")
87 conn.cursor().execute('TRUNCATE TABLE %s' % (t[0],))
91 # execute osm2pgsql on an empty file to get the right tables
92 osm2pgsql = os.path.join(self.build_dir, 'osm2pgsql', 'osm2pgsql')
93 proc = subprocess.Popen([osm2pgsql, '-lsc', '-r', 'xml',
94 '-O', 'gazetteer', '-d', self.template_db, '-'],
95 cwd=self.build_dir, stdin=subprocess.PIPE,
96 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
97 [outstr, errstr] = proc.communicate(input=b'<osm version="0.6"></osm>')
98 logger.debug("running osm2pgsql for template: %s\n%s\n%s" % (osm2pgsql, outstr, errstr))
99 self.run_setup_script('create-functions', 'create-tables',
100 'create-partition-tables', 'create-partition-functions',
101 'load-data', 'create-search-indices')
103 def setup_api_db(self, context):
104 self.write_nominatim_config(self.api_test_db)
106 def setup_db(self, context):
107 self.setup_template_db()
108 self.write_nominatim_config(self.test_db)
109 conn = psycopg2.connect(database=self.template_db)
110 conn.set_isolation_level(0)
112 cur.execute('DROP DATABASE IF EXISTS %s' % (self.test_db, ))
113 cur.execute('CREATE DATABASE %s TEMPLATE = %s' % (self.test_db, self.template_db))
115 context.db = psycopg2.connect(database=self.test_db)
116 if python_version[0] < 3:
117 psycopg2.extras.register_hstore(context.db, globally=False, unicode=True)
119 psycopg2.extras.register_hstore(context.db, globally=False)
121 def teardown_db(self, context):
125 if not self.keep_scenario_db:
126 self.db_drop_database(self.test_db)
128 def run_setup_script(self, *args, **kwargs):
129 self.run_nominatim_script('setup', *args, **kwargs)
131 def run_update_script(self, *args, **kwargs):
132 self.run_nominatim_script('update', *args, **kwargs)
134 def run_nominatim_script(self, script, *args, **kwargs):
135 cmd = [os.path.join(self.build_dir, 'utils', '%s.php' % script)]
136 cmd.extend(['--%s' % x for x in args])
137 for k, v in kwargs.items():
138 cmd.extend(('--' + k.replace('_', '-'), str(v)))
139 proc = subprocess.Popen(cmd, cwd=self.build_dir,
140 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
141 (outp, outerr) = proc.communicate()
142 logger.debug("run_nominatim_script: %s\n%s\n%s" % (cmd, outp, outerr))
143 assert (proc.returncode == 0), "Script '%s' failed:\n%s\n%s\n" % (script, outp, outerr)
146 class OSMDataFactory(object):
149 scriptpath = os.path.dirname(os.path.abspath(__file__))
150 self.scene_path = os.environ.get('SCENE_PATH',
151 os.path.join(scriptpath, '..', 'scenes', 'data'))
152 self.scene_cache = {}
155 def parse_geometry(self, geom, scene):
156 if geom.find(':') >= 0:
157 return "ST_SetSRID(%s, 4326)" % self.get_scene_geometry(scene, geom)
159 if geom.find(',') < 0:
160 out = "POINT(%s)" % self.mk_wkt_point(geom)
161 elif geom.find('(') < 0:
162 line = ','.join([self.mk_wkt_point(x) for x in geom.split(',')])
163 out = "LINESTRING(%s)" % line
165 inner = geom.strip('() ')
166 line = ','.join([self.mk_wkt_point(x) for x in inner.split(',')])
167 out = "POLYGON((%s))" % line
169 return "ST_SetSRID('%s'::geometry, 4326)" % out
171 def mk_wkt_point(self, point):
173 if geom.find(' ') >= 0:
176 pt = self.grid_node(int(geom))
177 assert_is_not_none(pt, "Point not found in grid")
180 def get_scene_geometry(self, default_scene, name):
182 for obj in name.split('+'):
184 if oname.startswith(':'):
185 assert_is_not_none(default_scene, "You need to set a scene")
186 defscene = self.load_scene(default_scene)
187 wkt = defscene[oname[1:]]
189 scene, obj = oname.split(':', 2)
190 scene_geoms = self.load_scene(scene)
191 wkt = scene_geoms[obj]
193 geoms.append("'%s'::geometry" % wkt)
198 return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
200 def load_scene(self, name):
201 if name in self.scene_cache:
202 return self.scene_cache[name]
205 with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
208 obj, wkt = line.split('|', 2)
209 scene[obj.strip()] = wkt.strip()
210 self.scene_cache[name] = scene
214 def clear_grid(self):
217 def add_grid_node(self, nodeid, x, y):
218 self.grid[nodeid] = (x, y)
220 def grid_node(self, nodeid):
221 return self.grid.get(nodeid)
224 def before_all(context):
226 context.config.setup_logging()
228 for k,v in userconfig.items():
229 context.config.userdata.setdefault(k, v)
230 logging.debug('User config: %s' %(str(context.config.userdata)))
231 # Nominatim test setup
232 context.nominatim = NominatimEnvironment(context.config.userdata)
233 context.osm = OSMDataFactory()
235 def after_all(context):
236 context.nominatim.cleanup()
239 def before_scenario(context, scenario):
240 if 'DB' in context.tags:
241 context.nominatim.setup_db(context)
242 elif 'APIDB' in context.tags:
243 context.nominatim.setup_api_db(context)
246 def after_scenario(context, scenario):
247 if 'DB' in context.tags:
248 context.nominatim.teardown_db(context)