7 from sys import version_info as python_version
9 logger = logging.getLogger(__name__)
12 'BASEURL' : 'http://localhost/nominatim',
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 'TEST_SETTINGS_FILE' : '/tmp/nominatim_settings.php'
21 use_step_matcher("re")
23 class NominatimEnvironment(object):
24 """ Collects all functions for the execution of Nominatim functions.
27 def __init__(self, config):
28 self.build_dir = os.path.abspath(config['BUILDDIR'])
29 self.template_db = config['TEMPLATE_DB']
30 self.test_db = config['TEST_DB']
31 self.local_settings_file = config['TEST_SETTINGS_FILE']
32 self.reuse_template = not config['REMOVE_TEMPLATE']
33 self.keep_scenario_db = config['KEEP_TEST_DB']
34 os.environ['NOMINATIM_SETTINGS'] = self.local_settings_file
36 self.template_db_done = False
38 def write_nominatim_config(self, dbname):
39 f = open(self.local_settings_file, 'w')
40 f.write("<?php\n @define('CONST_Database_DSN', 'pgsql://@/%s');\n" % dbname)
45 os.remove(self.local_settings_file)
47 pass # ignore missing file
49 def db_drop_database(self, name):
50 conn = psycopg2.connect(database='postgres')
51 conn.set_isolation_level(0)
53 cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
56 def setup_template_db(self):
57 if self.template_db_done:
60 self.template_db_done = True
62 if self.reuse_template:
63 # check that the template is there
64 conn = psycopg2.connect(database='postgres')
66 cur.execute('select count(*) from pg_database where datname = %s',
68 if cur.fetchone()[0] == 1:
72 # just in case... make sure a previous table has been dropped
73 self.db_drop_database(self.template_db)
75 # call the first part of database setup
76 self.write_nominatim_config(self.template_db)
77 self.run_setup_script('create-db', 'setup-db')
78 # remove external data to speed up indexing for tests
79 conn = psycopg2.connect(database=self.template_db)
81 cur.execute("""select tablename from pg_tables
82 where tablename in ('gb_postcode', 'us_postcode')""")
84 conn.cursor().execute('TRUNCATE TABLE %s' % (t[0],))
88 # execute osm2pgsql on an empty file to get the right tables
89 osm2pgsql = os.path.join(self.build_dir, 'osm2pgsql', 'osm2pgsql')
90 proc = subprocess.Popen([osm2pgsql, '-lsc', '-r', 'xml',
91 '-O', 'gazetteer', '-d', self.template_db, '-'],
92 cwd=self.build_dir, stdin=subprocess.PIPE,
93 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
94 [outstr, errstr] = proc.communicate(input=b'<osm version="0.6"></osm>')
95 logger.debug("running osm2pgsql for template: %s\n%s\n%s" % (osm2pgsql, outstr, errstr))
96 self.run_setup_script('create-functions', 'create-tables',
97 'create-partition-tables', 'create-partition-functions',
98 'load-data', 'create-search-indices')
102 def setup_db(self, context):
103 self.setup_template_db()
104 self.write_nominatim_config(self.test_db)
105 conn = psycopg2.connect(database=self.template_db)
106 conn.set_isolation_level(0)
108 cur.execute('DROP DATABASE IF EXISTS %s' % (self.test_db, ))
109 cur.execute('CREATE DATABASE %s TEMPLATE = %s' % (self.test_db, self.template_db))
111 context.db = psycopg2.connect(database=self.test_db)
112 if python_version[0] < 3:
113 psycopg2.extras.register_hstore(context.db, globally=False, unicode=True)
115 psycopg2.extras.register_hstore(context.db, globally=False)
117 def teardown_db(self, context):
121 if not self.keep_scenario_db:
122 self.db_drop_database(self.test_db)
124 def run_setup_script(self, *args):
125 self.run_nominatim_script('setup', *args)
127 def run_nominatim_script(self, script, *args):
128 cmd = [os.path.join(self.build_dir, 'utils', '%s.php' % script)]
129 cmd.extend(['--%s' % x for x in args])
130 proc = subprocess.Popen(cmd, cwd=self.build_dir,
131 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
132 (outp, outerr) = proc.communicate()
133 logger.debug("run_nominatim_script: %s\n%s\n%s" % (cmd, outp, outerr))
134 assert (proc.returncode == 0), "Script '%s' failed:\n%s\n%s\n" % (script, outp, outerr)
137 class OSMDataFactory(object):
140 scriptpath = os.path.dirname(os.path.abspath(__file__))
141 self.scene_path = os.environ.get('SCENE_PATH',
142 os.path.join(scriptpath, '..', 'scenes', 'data'))
143 self.scene_cache = {}
145 def parse_geometry(self, geom, scene):
146 if geom[0].find(':') >= 0:
147 out = self.get_scene_geometry(scene, geom[1:])
148 if geom.find(',') < 0:
149 out = 'POINT(%s)' % geom
150 elif geom.find('(') < 0:
151 out = 'LINESTRING(%s)' % geom
153 out = 'POLYGON(%s)' % geom
155 # TODO parse precision
158 def get_scene_geometry(self, default_scene, name):
160 defscene = self.load_scene(default_scene)
161 for obj in name.split('+'):
163 if oname.startswith(':'):
164 wkt = defscene[oname[1:]]
166 scene, obj = oname.split(':', 2)
167 scene_geoms = world.load_scene(scene)
168 wkt = scene_geoms[obj]
170 geoms.append("'%s'::geometry" % wkt)
175 return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
177 def load_scene(self, name):
178 if name in self.scene_cache:
179 return self.scene_cache[name]
182 with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
185 obj, wkt = line.split('|', 2)
186 scene[obj.strip()] = wkt.strip()
187 self.scene_cache[name] = scene
192 def before_all(context):
194 context.config.setup_logging()
196 for k,v in userconfig.items():
197 context.config.userdata.setdefault(k, v)
198 logging.debug('User config: %s' %(str(context.config.userdata)))
199 # Nominatim test setup
200 context.nominatim = NominatimEnvironment(context.config.userdata)
201 context.osm = OSMDataFactory()
203 def after_all(context):
204 context.nominatim.cleanup()
207 def before_scenario(context, scenario):
208 if 'DB' in context.tags:
209 context.nominatim.setup_db(context)
212 def after_scenario(context, scenario):
213 if 'DB' in context.tags:
214 context.nominatim.teardown_db(context)