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