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