]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/environment.py
add vagrant and installation instructions for ubuntu 18
[nominatim.git] / test / bdd / environment.py
1 from behave import *
2 import logging
3 import os
4 import psycopg2
5 import psycopg2.extras
6 import subprocess
7 import tempfile
8 from nose.tools import * # for assert functions
9 from sys import version_info as python_version
10
11 logger = logging.getLogger(__name__)
12
13 userconfig = {
14     'BUILDDIR' : os.path.join(os.path.split(__file__)[0], "../../build"),
15     'REMOVE_TEMPLATE' : False,
16     'KEEP_TEST_DB' : False,
17     'DB_HOST' : None,
18     'DB_USER' : None,
19     'DB_PASS' : None,
20     'TEMPLATE_DB' : 'test_template_nominatim',
21     'TEST_DB' : 'test_nominatim',
22     'API_TEST_DB' : 'test_api_nominatim',
23     'TEST_SETTINGS_FILE' : '/tmp/nominatim_settings.php',
24     'SERVER_MODULE_PATH' : None,
25     'PHPCOV' : False, # set to output directory to enable code coverage
26 }
27
28 use_step_matcher("re")
29
30 class NominatimEnvironment(object):
31     """ Collects all functions for the execution of Nominatim functions.
32     """
33
34     def __init__(self, config):
35         self.build_dir = os.path.abspath(config['BUILDDIR'])
36         self.src_dir = os.path.abspath(os.path.join(os.path.split(__file__)[0], "../.."))
37         self.db_host = config['DB_HOST']
38         self.db_user = config['DB_USER']
39         self.db_pass = config['DB_PASS']
40         self.template_db = config['TEMPLATE_DB']
41         self.test_db = config['TEST_DB']
42         self.api_test_db = config['API_TEST_DB']
43         self.server_module_path = config['SERVER_MODULE_PATH']
44         self.local_settings_file = config['TEST_SETTINGS_FILE']
45         self.reuse_template = not config['REMOVE_TEMPLATE']
46         self.keep_scenario_db = config['KEEP_TEST_DB']
47         self.code_coverage_path = config['PHPCOV']
48         self.code_coverage_id = 1
49         os.environ['NOMINATIM_SETTINGS'] = self.local_settings_file
50
51         self.template_db_done = False
52
53     def connect_database(self, dbname):
54         dbargs = {'database': dbname}
55         if self.db_host:
56             dbargs['host'] = self.db_host
57         if self.db_user:
58             dbargs['user'] = self.db_user
59         if self.db_pass:
60             dbargs['password'] = self.db_pass
61         conn = psycopg2.connect(**dbargs)
62         return conn
63
64     def next_code_coverage_file(self):
65         fn = os.path.join(self.code_coverage_path, "%06d.cov" % self.code_coverage_id)
66         self.code_coverage_id += 1
67
68         return fn
69
70     def write_nominatim_config(self, dbname):
71         f = open(self.local_settings_file, 'w')
72         f.write("<?php\n  @define('CONST_Database_DSN', 'pgsql://%s:%s@%s/%s');\n" %
73                 (self.db_user if self.db_user else '',
74                  self.db_pass if self.db_pass else '',
75                  self.db_host if self.db_host else '',
76                  dbname))
77         f.write("@define('CONST_Osm2pgsql_Flatnode_File', null);\n")
78         f.close()
79
80     def cleanup(self):
81         try:
82             os.remove(self.local_settings_file)
83         except OSError:
84             pass # ignore missing file
85
86     def db_drop_database(self, name):
87         conn = self.connect_database('postgres')
88         conn.set_isolation_level(0)
89         cur = conn.cursor()
90         cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
91         conn.close()
92
93     def setup_template_db(self):
94         if self.template_db_done:
95             return
96
97         self.template_db_done = True
98
99         if self.reuse_template:
100             # check that the template is there
101             conn = self.connect_database('postgres')
102             cur = conn.cursor()
103             cur.execute('select count(*) from pg_database where datname = %s',
104                         (self.template_db,))
105             if cur.fetchone()[0] == 1:
106                 return
107             conn.close()
108         else:
109             # just in case... make sure a previous table has been dropped
110             self.db_drop_database(self.template_db)
111
112         try:
113             # call the first part of database setup
114             self.write_nominatim_config(self.template_db)
115             self.run_setup_script('create-db', 'setup-db')
116             # remove external data to speed up indexing for tests
117             conn = self.connect_database(self.template_db)
118             cur = conn.cursor()
119             cur.execute("""select tablename from pg_tables
120                            where tablename in ('gb_postcode', 'us_postcode')""")
121             for t in cur:
122                 conn.cursor().execute('TRUNCATE TABLE %s' % (t[0],))
123             conn.commit()
124             conn.close()
125
126             # execute osm2pgsql import on an empty file to get the right tables
127             with tempfile.NamedTemporaryFile(dir='/tmp', suffix='.xml') as fd:
128                 fd.write(b'<osm version="0.6"></osm>')
129                 fd.flush()
130                 self.run_setup_script('import-data',
131                                       'ignore-errors',
132                                       'create-functions',
133                                       'create-tables',
134                                       'create-partition-tables',
135                                       'create-partition-functions',
136                                       'load-data',
137                                       'create-search-indices',
138                                       osm_file=fd.name,
139                                       osm2pgsql_cache='200')
140         except:
141             self.db_drop_database(self.template_db)
142             raise
143
144
145     def setup_api_db(self, context):
146         self.write_nominatim_config(self.api_test_db)
147
148     def setup_unknown_db(self, context):
149         self.write_nominatim_config('UNKNOWN_DATABASE_NAME')
150
151     def setup_db(self, context):
152         self.setup_template_db()
153         self.write_nominatim_config(self.test_db)
154         conn = self.connect_database(self.template_db)
155         conn.set_isolation_level(0)
156         cur = conn.cursor()
157         cur.execute('DROP DATABASE IF EXISTS %s' % (self.test_db, ))
158         cur.execute('CREATE DATABASE %s TEMPLATE = %s' % (self.test_db, self.template_db))
159         conn.close()
160         context.db = self.connect_database(self.test_db)
161         if python_version[0] < 3:
162             psycopg2.extras.register_hstore(context.db, globally=False, unicode=True)
163         else:
164             psycopg2.extras.register_hstore(context.db, globally=False)
165
166     def teardown_db(self, context):
167         if 'db' in context:
168             context.db.close()
169
170         if not self.keep_scenario_db:
171             self.db_drop_database(self.test_db)
172
173     def run_setup_script(self, *args, **kwargs):
174         if self.server_module_path:
175             kwargs = dict(kwargs)
176             kwargs['module_path'] = self.server_module_path
177         self.run_nominatim_script('setup', *args, **kwargs)
178
179     def run_update_script(self, *args, **kwargs):
180         self.run_nominatim_script('update', *args, **kwargs)
181
182     def run_nominatim_script(self, script, *args, **kwargs):
183         cmd = ['/usr/bin/env', 'php', '-Cq']
184         cmd.append(os.path.join(self.build_dir, 'utils', '%s.php' % script))
185         cmd.extend(['--%s' % x for x in args])
186         for k, v in kwargs.items():
187             cmd.extend(('--' + k.replace('_', '-'), str(v)))
188         proc = subprocess.Popen(cmd, cwd=self.build_dir,
189                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
190         (outp, outerr) = proc.communicate()
191         logger.debug("run_nominatim_script: %s\n%s\n%s" % (cmd, outp, outerr))
192         assert (proc.returncode == 0), "Script '%s' failed:\n%s\n%s\n" % (script, outp, outerr)
193
194
195 class OSMDataFactory(object):
196
197     def __init__(self):
198         scriptpath = os.path.dirname(os.path.abspath(__file__))
199         self.scene_path = os.environ.get('SCENE_PATH',
200                            os.path.join(scriptpath, '..', 'scenes', 'data'))
201         self.scene_cache = {}
202         self.clear_grid()
203
204     def parse_geometry(self, geom, scene):
205         if geom.find(':') >= 0:
206             return "ST_SetSRID(%s, 4326)" % self.get_scene_geometry(scene, geom)
207
208         if geom.find(',') < 0:
209             out = "POINT(%s)" % self.mk_wkt_point(geom)
210         elif geom.find('(') < 0:
211             line = ','.join([self.mk_wkt_point(x) for x in geom.split(',')])
212             out = "LINESTRING(%s)" % line
213         else:
214             inner = geom.strip('() ')
215             line = ','.join([self.mk_wkt_point(x) for x in inner.split(',')])
216             out = "POLYGON((%s))" % line
217
218         return "ST_SetSRID('%s'::geometry, 4326)" % out
219
220     def mk_wkt_point(self, point):
221         geom = point.strip()
222         if geom.find(' ') >= 0:
223             return geom
224         else:
225             pt = self.grid_node(int(geom))
226             assert_is_not_none(pt, "Point not found in grid")
227             return "%f %f" % pt
228
229     def get_scene_geometry(self, default_scene, name):
230         geoms = []
231         for obj in name.split('+'):
232             oname = obj.strip()
233             if oname.startswith(':'):
234                 assert_is_not_none(default_scene, "You need to set a scene")
235                 defscene = self.load_scene(default_scene)
236                 wkt = defscene[oname[1:]]
237             else:
238                 scene, obj = oname.split(':', 2)
239                 scene_geoms = self.load_scene(scene)
240                 wkt = scene_geoms[obj]
241
242             geoms.append("'%s'::geometry" % wkt)
243
244         if len(geoms) == 1:
245             return geoms[0]
246         else:
247             return 'ST_LineMerge(ST_Collect(ARRAY[%s]))' % ','.join(geoms)
248
249     def load_scene(self, name):
250         if name in self.scene_cache:
251             return self.scene_cache[name]
252
253         scene = {}
254         with open(os.path.join(self.scene_path, "%s.wkt" % name), 'r') as fd:
255             for line in fd:
256                 if line.strip():
257                     obj, wkt = line.split('|', 2)
258                     scene[obj.strip()] = wkt.strip()
259             self.scene_cache[name] = scene
260
261         return scene
262
263     def clear_grid(self):
264         self.grid = {}
265
266     def add_grid_node(self, nodeid, x, y):
267         self.grid[nodeid] = (x, y)
268
269     def grid_node(self, nodeid):
270         return self.grid.get(nodeid)
271
272
273 def before_all(context):
274     # logging setup
275     context.config.setup_logging()
276     # set up -D options
277     for k,v in userconfig.items():
278         context.config.userdata.setdefault(k, v)
279     logging.debug('User config: %s' %(str(context.config.userdata)))
280     # Nominatim test setup
281     context.nominatim = NominatimEnvironment(context.config.userdata)
282     context.osm = OSMDataFactory()
283
284 def after_all(context):
285     context.nominatim.cleanup()
286
287
288 def before_scenario(context, scenario):
289     if 'DB' in context.tags:
290         context.nominatim.setup_db(context)
291     elif 'APIDB' in context.tags:
292         context.nominatim.setup_api_db(context)
293     elif 'UNKNOWNDB' in context.tags:
294         context.nominatim.setup_unknown_db(context)
295     context.scene = None
296
297 def after_scenario(context, scenario):
298     if 'DB' in context.tags:
299         context.nominatim.teardown_db(context)