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