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