7 from nose.tools import * # for assert functions
8 from sys import version_info as python_version
10 logger = logging.getLogger(__name__)
13 'BASEURL' : 'http://localhost/nominatim',
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 '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.local_settings_file = config['TEST_SETTINGS_FILE']
33 self.reuse_template = not config['REMOVE_TEMPLATE']
34 self.keep_scenario_db = config['KEEP_TEST_DB']
35 os.environ['NOMINATIM_SETTINGS'] = self.local_settings_file
37 self.template_db_done = False
39 def write_nominatim_config(self, dbname):
40 f = open(self.local_settings_file, 'w')
41 f.write("<?php\n @define('CONST_Database_DSN', 'pgsql://@/%s');\n" % dbname)
46 os.remove(self.local_settings_file)
48 pass # ignore missing file
50 def db_drop_database(self, name):
51 conn = psycopg2.connect(database='postgres')
52 conn.set_isolation_level(0)
54 cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
57 def setup_template_db(self):
58 if self.template_db_done:
61 self.template_db_done = True
63 if self.reuse_template:
64 # check that the template is there
65 conn = psycopg2.connect(database='postgres')
67 cur.execute('select count(*) from pg_database where datname = %s',
69 if cur.fetchone()[0] == 1:
73 # just in case... make sure a previous table has been dropped
74 self.db_drop_database(self.template_db)
76 # call the first part of database setup
77 self.write_nominatim_config(self.template_db)
78 self.run_setup_script('create-db', 'setup-db')
79 # remove external data to speed up indexing for tests
80 conn = psycopg2.connect(database=self.template_db)
82 cur.execute("""select tablename from pg_tables
83 where tablename in ('gb_postcode', 'us_postcode')""")
85 conn.cursor().execute('TRUNCATE TABLE %s' % (t[0],))
89 # execute osm2pgsql on an empty file to get the right tables
90 osm2pgsql = os.path.join(self.build_dir, 'osm2pgsql', 'osm2pgsql')
91 proc = subprocess.Popen([osm2pgsql, '-lsc', '-r', 'xml',
92 '-O', 'gazetteer', '-d', self.template_db, '-'],
93 cwd=self.build_dir, stdin=subprocess.PIPE,
94 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
95 [outstr, errstr] = proc.communicate(input=b'<osm version="0.6"></osm>')
96 logger.debug("running osm2pgsql for template: %s\n%s\n%s" % (osm2pgsql, outstr, errstr))
97 self.run_setup_script('create-functions', 'create-tables',
98 'create-partition-tables', 'create-partition-functions',
99 'load-data', 'create-search-indices')
103 def setup_db(self, context):
104 self.setup_template_db()
105 self.write_nominatim_config(self.test_db)
106 conn = psycopg2.connect(database=self.template_db)
107 conn.set_isolation_level(0)
109 cur.execute('DROP DATABASE IF EXISTS %s' % (self.test_db, ))
110 cur.execute('CREATE DATABASE %s TEMPLATE = %s' % (self.test_db, self.template_db))
112 context.db = psycopg2.connect(database=self.test_db)
113 if python_version[0] < 3:
114 psycopg2.extras.register_hstore(context.db, globally=False, unicode=True)
116 psycopg2.extras.register_hstore(context.db, globally=False)
118 def teardown_db(self, context):
122 if not self.keep_scenario_db:
123 self.db_drop_database(self.test_db)
125 def run_setup_script(self, *args, **kwargs):
126 self.run_nominatim_script('setup', *args, **kwargs)
128 def run_update_script(self, *args, **kwargs):
129 self.run_nominatim_script('update', *args, **kwargs)
131 def run_nominatim_script(self, script, *args, **kwargs):
132 cmd = [os.path.join(self.build_dir, 'utils', '%s.php' % script)]
133 cmd.extend(['--%s' % x for x in args])
134 for k, v in kwargs.items():
135 cmd.extend(('--' + k.replace('_', '-'), str(v)))
136 proc = subprocess.Popen(cmd, cwd=self.build_dir,
137 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
138 (outp, outerr) = proc.communicate()
139 logger.debug("run_nominatim_script: %s\n%s\n%s" % (cmd, outp, outerr))
140 assert (proc.returncode == 0), "Script '%s' failed:\n%s\n%s\n" % (script, outp, outerr)
143 class OSMDataFactory(object):
146 scriptpath = os.path.dirname(os.path.abspath(__file__))
147 self.scene_path = os.environ.get('SCENE_PATH',
148 os.path.join(scriptpath, '..', 'scenes', 'data'))
149 self.scene_cache = {}
151 def parse_geometry(self, geom, scene):
152 if geom.find(':') >= 0:
153 out = self.get_scene_geometry(scene, geom)
154 elif geom.find(',') < 0:
155 out = "'POINT(%s)'::geometry" % geom
156 elif geom.find('(') < 0:
157 out = "'LINESTRING(%s)'::geometry" % geom
159 out = "'POLYGON(%s)'::geometry" % geom
161 return "ST_SetSRID(%s, 4326)" % out
163 def get_scene_geometry(self, default_scene, name):
165 for obj in name.split('+'):
167 if oname.startswith(':'):
168 assert_is_not_none(default_scene, "You need to set a scene")
169 defscene = self.load_scene(default_scene)
170 wkt = defscene[oname[1:]]
172 scene, obj = oname.split(':', 2)
173 scene_geoms = self.load_scene(scene)
174 wkt = scene_geoms[obj]
176 geoms.append("'%s'::geometry" % wkt)
181 return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
183 def load_scene(self, name):
184 if name in self.scene_cache:
185 return self.scene_cache[name]
188 with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
191 obj, wkt = line.split('|', 2)
192 scene[obj.strip()] = wkt.strip()
193 self.scene_cache[name] = scene
198 def before_all(context):
200 context.config.setup_logging()
202 for k,v in userconfig.items():
203 context.config.userdata.setdefault(k, v)
204 logging.debug('User config: %s' %(str(context.config.userdata)))
205 # Nominatim test setup
206 context.nominatim = NominatimEnvironment(context.config.userdata)
207 context.osm = OSMDataFactory()
209 def after_all(context):
210 context.nominatim.cleanup()
213 def before_scenario(context, scenario):
214 if 'DB' in context.tags:
215 context.nominatim.setup_db(context)
218 def after_scenario(context, scenario):
219 if 'DB' in context.tags:
220 context.nominatim.teardown_db(context)