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