]> git.openstreetmap.org Git - nominatim.git/blob - tests/steps/terrain.py
e9561d1a9fd11b52653f8d383d7f5d9eb8872785
[nominatim.git] / tests / steps / terrain.py
1 from lettuce import *
2 from nose.tools import *
3 import logging
4 import os
5 import subprocess
6 import psycopg2
7 import re
8 from haversine import haversine
9 from shapely.wkt import loads as wkt_load
10 from shapely.ops import linemerge
11
12 logger = logging.getLogger(__name__)
13
14 class NominatimConfig:
15
16     def __init__(self):
17         # logging setup
18         loglevel = getattr(logging, os.environ.get('LOGLEVEL','info').upper())
19         if 'LOGFILE' in os.environ:
20             logging.basicConfig(filename=os.environ.get('LOGFILE','run.log'),
21                                 level=loglevel)
22         else:
23             logging.basicConfig(level=loglevel)
24         # Nominatim test setup
25         self.base_url = os.environ.get('NOMINATIM_SERVER', 'http://localhost/nominatim')
26         self.source_dir = os.path.abspath(os.environ.get('NOMINATIM_DIR', '..'))
27         self.template_db = os.environ.get('TEMPLATE_DB', 'test_template_nominatim')
28         self.test_db = os.environ.get('TEST_DB', 'test_nominatim')
29         self.local_settings_file = os.environ.get('NOMINATIM_SETTINGS', '/tmp/nominatim_settings.php')
30         self.reuse_template = 'NOMINATIM_REMOVE_TEMPLATE' not in os.environ
31         self.keep_scenario_db = 'NOMINATIM_KEEP_SCENARIO_DB' in os.environ
32         os.environ['NOMINATIM_SETTINGS'] = '/tmp/nominatim_settings.php'
33
34         scriptpath = os.path.dirname(os.path.abspath(__file__))
35         self.scene_path = os.environ.get('SCENE_PATH', 
36                 os.path.join(scriptpath, '..', 'scenes', 'data'))
37
38
39     def __str__(self):
40         return 'Server URL: %s\nSource dir: %s\n' % (self.base_url, self.source_dir)
41
42 world.config = NominatimConfig()
43
44 @world.absorb
45 def write_nominatim_config(dbname):
46     f = open(world.config.local_settings_file, 'w')
47     f.write("<?php\n  @define('CONST_Database_DSN', 'pgsql://@/%s');\n" % dbname)
48     f.close()
49
50
51 @world.absorb
52 def run_nominatim_script(script, *args):
53     cmd = [os.path.join(world.config.source_dir, 'utils', '%s.php' % script)]
54     cmd.extend(['--%s' % x for x in args])
55     proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
56     (outp, outerr) = proc.communicate()
57     assert (proc.returncode == 0), "Script '%s' failed:\n%s\n%s\n" % (script, outp, outerr)
58
59 @world.absorb
60 def make_hash(inp):
61     return eval('{' + inp + '}')
62
63 @world.absorb
64 def split_id(oid):
65     """ Splits a unique identifier for places into its components.
66         As place_ids cannot be used for testing, we use a unique
67         identifier instead that is of the form <osmtype><osmid>[:class].
68     """
69     oid = oid.strip()
70     if oid == 'None':
71         return None, None, None
72     osmtype = oid[0]
73     assert_in(osmtype, ('R','N','W'))
74     if ':' in oid:
75         osmid, cls = oid[1:].split(':')
76         return (osmtype, int(osmid), cls)
77     else:
78         return (osmtype, int(oid[1:]), None)
79
80 @world.absorb
81 def get_placeid(oid):
82     """ Tries to retrive the place_id for a unique identifier. """
83     if oid[0].isdigit():
84         return int(oid)
85
86     osmtype, osmid, cls = world.split_id(oid)
87     if osmtype is None:
88         return None
89     cur = world.conn.cursor()
90     if cls is None:
91         q = 'SELECT place_id FROM placex where osm_type = %s and osm_id = %s'
92         params = (osmtype, osmid)
93     else:
94         q = 'SELECT place_id FROM placex where osm_type = %s and osm_id = %s and class = %s'
95         params = (osmtype, osmid, cls)
96     cur.execute(q, params)
97     assert_equals(cur.rowcount, 1, "%d rows found for place %s" % (cur.rowcount, oid))
98     return cur.fetchone()[0]
99
100
101 @world.absorb
102 def match_geometry(coord, matchstring):
103     m = re.match(r'([-0-9.]+),\s*([-0-9.]+)\s*(?:\+-([0-9.]+)([a-z]+)?)?', matchstring)
104     assert_is_not_none(m, "Invalid match string")
105
106     logger.debug("Distmatch: %s/%s %s %s" % (m.group(1), m.group(2), m.group(3), m.group(4) ))
107     dist = haversine(coord, (float(m.group(1)), float(m.group(2))))
108
109     if m.group(3) is not None:
110         expdist = float(m.group(3))
111         if m.group(4) is not None:
112             if m.group(4) == 'm':
113                 expdist = expdist/1000
114             elif m.group(4) == 'km':
115                 pass
116             else:
117                 raise Exception("Unknown unit '%s' in geometry match" % (m.group(4), ))
118     else:
119         expdist = 0
120
121     logger.debug("Distances expected: %f, got: %f" % (expdist, dist))
122     assert dist <= expdist, "Geometry too far away, expected: %f, got: %f" % (expdist, dist)
123
124
125
126 @world.absorb
127 def db_dump_table(table):
128     cur = world.conn.cursor()
129     cur.execute('SELECT * FROM %s' % table)
130     print '<<<<<<< BEGIN OF TABLE DUMP %s' % table
131     for res in cur:
132             print res
133     print '<<<<<<< END OF TABLE DUMP %s' % table
134
135 @world.absorb
136 def db_drop_database(name):
137     conn = psycopg2.connect(database='postgres')
138     conn.set_isolation_level(0)
139     cur = conn.cursor()
140     cur.execute('DROP DATABASE IF EXISTS %s' % (name, ))
141     conn.close()
142
143
144 world.is_template_set_up = False
145
146 @world.absorb
147 def db_template_setup():
148     """ Set up a template database, containing all tables
149         but not yet any functions.
150     """
151     if world.is_template_set_up:
152         return
153
154     world.is_template_set_up = True
155     world.write_nominatim_config(world.config.template_db)
156     if world.config.reuse_template:
157         # check that the template is there
158         conn = psycopg2.connect(database='postgres')
159         cur = conn.cursor()
160         cur.execute('select count(*) from pg_database where datname = %s', 
161                      (world.config.template_db,))
162         if cur.fetchone()[0] == 1:
163             return
164     else:
165         # just in case... make sure a previous table has been dropped
166         world.db_drop_database(world.config.template_db)
167     # call the first part of database setup
168     world.run_nominatim_script('setup', 'create-db', 'setup-db')
169     # remove external data to speed up indexing for tests
170     conn = psycopg2.connect(database=world.config.template_db)
171     psycopg2.extras.register_hstore(conn, globally=False, unicode=True)
172     cur = conn.cursor()
173     for table in ('gb_postcode', 'us_postcode', 'us_state', 'us_statecounty'):
174         cur.execute('TRUNCATE TABLE %s' % (table,))
175     conn.commit()
176     conn.close()
177     # execute osm2pgsql on an empty file to get the right tables
178     osm2pgsql = os.path.join(world.config.source_dir, 'osm2pgsql', 'osm2pgsql')
179     proc = subprocess.Popen([osm2pgsql, '-lsc', '-O', 'gazetteer', '-d', world.config.template_db, '-'],
180     stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
181     [outstr, errstr] = proc.communicate(input='<osm version="0.6"></osm>')
182     world.run_nominatim_script('setup', 'create-functions', 'create-tables', 'create-partition-tables', 'create-partition-functions', 'load-data', 'create-search-indices')
183
184
185 # Leave the table around so it can be reused again after a non-reuse test round.
186 #@after.all
187 def db_template_teardown(total):
188     """ Set up a template database, containing all tables
189         but not yet any functions.
190     """
191     if world.is_template_set_up:
192         # remove template DB
193         if not world.config.reuse_template:
194             world.db_drop_database(world.config.template_db)
195         try:
196             os.remove(world.config.local_settings_file)
197         except OSError:
198             pass # ignore missing file
199
200
201 ##########################################################################
202 #
203 # Data scene handling
204 #
205
206 world.scenes = {}
207 world.current_scene = None
208
209 @world.absorb
210 def load_scene(name):
211     if name in world.scenes:
212         world.current_scene = world.scenes[name]
213     else:
214         with open(os.path.join(world.config.scene_path, "%s.wkt" % name), 'r') as fd:
215             scene = {}
216             for line in fd:
217                 if line.strip():
218                     obj, wkt = line.split('|', 2)
219                     wkt = wkt.strip()
220                     scene[obj.strip()] = wkt_load(wkt)
221             world.scenes[name] = scene
222             world.current_scene = scene
223
224 @world.absorb
225 def get_scene_geometry(name):
226     if not ':' in name:
227         # Not a scene description
228         return None
229     
230     geoms = []
231     for obj in name.split('+'):
232         oname = obj.strip()
233         if oname.startswith(':'):
234             geoms.append(world.current_scene[oname[1:]])
235         else:
236             scene, obj = oname.split(':', 2)
237             oldscene = world.current_scene
238             world.load_scene(scene)
239             wkt = world.current_scene[obj]
240             world.current_scene = oldscene
241             geoms.append(wkt)
242
243     if len(geoms) == 1:
244         return geoms[0]
245     else:
246         return linemerge(geoms)