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