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 'API_TEST_DB' : 'test_api_nominatim',
20 'TEST_SETTINGS_FILE' : '/tmp/nominatim_settings.php'
23 use_step_matcher("re")
25 class NominatimEnvironment(object):
26 """ Collects all functions for the execution of Nominatim functions.
29 def __init__(self, config):
30 self.build_dir = os.path.abspath(config['BUILDDIR'])
31 self.template_db = config['TEMPLATE_DB']
32 self.test_db = config['TEST_DB']
33 self.api_test_db = config['API_TEST_DB']
34 self.local_settings_file = config['TEST_SETTINGS_FILE']
35 self.reuse_template = not config['REMOVE_TEMPLATE']
36 self.keep_scenario_db = config['KEEP_TEST_DB']
37 os.environ['NOMINATIM_SETTINGS'] = self.local_settings_file
39 self.template_db_done = False
41 def write_nominatim_config(self, dbname):
42 f = open(self.local_settings_file, 'w')
43 f.write("<?php\n @define('CONST_Database_DSN', 'pgsql://@/%s');\n" % dbname)
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 = {}
154 def parse_geometry(self, geom, scene):
155 if geom.find(':') >= 0:
156 out = self.get_scene_geometry(scene, geom)
157 elif geom.find(',') < 0:
158 out = "'POINT(%s)'::geometry" % geom
159 elif geom.find('(') < 0:
160 out = "'LINESTRING(%s)'::geometry" % geom
162 out = "'POLYGON(%s)'::geometry" % geom
164 return "ST_SetSRID(%s, 4326)" % out
166 def get_scene_geometry(self, default_scene, name):
168 for obj in name.split('+'):
170 if oname.startswith(':'):
171 assert_is_not_none(default_scene, "You need to set a scene")
172 defscene = self.load_scene(default_scene)
173 wkt = defscene[oname[1:]]
175 scene, obj = oname.split(':', 2)
176 scene_geoms = self.load_scene(scene)
177 wkt = scene_geoms[obj]
179 geoms.append("'%s'::geometry" % wkt)
184 return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
186 def load_scene(self, name):
187 if name in self.scene_cache:
188 return self.scene_cache[name]
191 with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
194 obj, wkt = line.split('|', 2)
195 scene[obj.strip()] = wkt.strip()
196 self.scene_cache[name] = scene
201 def before_all(context):
203 context.config.setup_logging()
205 for k,v in userconfig.items():
206 context.config.userdata.setdefault(k, v)
207 logging.debug('User config: %s' %(str(context.config.userdata)))
208 # Nominatim test setup
209 context.nominatim = NominatimEnvironment(context.config.userdata)
210 context.osm = OSMDataFactory()
212 def after_all(context):
213 context.nominatim.cleanup()
216 def before_scenario(context, scenario):
217 if 'DB' in context.tags:
218 context.nominatim.setup_db(context)
219 elif 'APIDB' in context.tags:
220 context.nominatim.setup_api_db(context)
223 def after_scenario(context, scenario):
224 if 'DB' in context.tags:
225 context.nominatim.teardown_db(context)