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 = {}
153 def parse_geometry(self, geom, scene):
154 if geom.find(':') >= 0:
155 out = self.get_scene_geometry(scene, geom)
156 elif geom.find(',') < 0:
157 out = "'POINT(%s)'::geometry" % geom
158 elif geom.find('(') < 0:
159 out = "'LINESTRING(%s)'::geometry" % geom
161 out = "'POLYGON(%s)'::geometry" % geom
163 return "ST_SetSRID(%s, 4326)" % out
165 def get_scene_geometry(self, default_scene, name):
167 for obj in name.split('+'):
169 if oname.startswith(':'):
170 assert_is_not_none(default_scene, "You need to set a scene")
171 defscene = self.load_scene(default_scene)
172 wkt = defscene[oname[1:]]
174 scene, obj = oname.split(':', 2)
175 scene_geoms = self.load_scene(scene)
176 wkt = scene_geoms[obj]
178 geoms.append("'%s'::geometry" % wkt)
183 return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
185 def load_scene(self, name):
186 if name in self.scene_cache:
187 return self.scene_cache[name]
190 with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
193 obj, wkt = line.split('|', 2)
194 scene[obj.strip()] = wkt.strip()
195 self.scene_cache[name] = scene
200 def before_all(context):
202 context.config.setup_logging()
204 for k,v in userconfig.items():
205 context.config.userdata.setdefault(k, v)
206 logging.debug('User config: %s' %(str(context.config.userdata)))
207 # Nominatim test setup
208 context.nominatim = NominatimEnvironment(context.config.userdata)
209 context.osm = OSMDataFactory()
211 def after_all(context):
212 context.nominatim.cleanup()
215 def before_scenario(context, scenario):
216 if 'DB' in context.tags:
217 context.nominatim.setup_db(context)
218 elif 'APIDB' in context.tags:
219 context.nominatim.setup_api_db(context)
222 def after_scenario(context, scenario):
223 if 'DB' in context.tags:
224 context.nominatim.teardown_db(context)