]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/db_ops.py
Merge pull request #661 from mtmail/travis-ci-badge
[nominatim.git] / test / bdd / steps / db_ops.py
1 import base64
2 import random
3 import string
4 import re
5 from nose.tools import * # for assert functions
6 import psycopg2.extras
7
8 class PlaceColumn:
9
10     def __init__(self, context, force_name):
11         self.columns = { 'admin_level' : 100}
12         self.force_name = force_name
13         self.context = context
14         self.geometry = None
15
16     def add(self, key, value):
17         if hasattr(self, 'set_key_' + key):
18             getattr(self, 'set_key_' + key)(value)
19         elif key.startswith('name+'):
20             self.add_hstore('name', key[5:], value)
21         elif key.startswith('extra+'):
22             self.add_hstore('extratags', key[6:], value)
23         else:
24             assert_in(key, ('class', 'type', 'street', 'addr_place',
25                             'isin', 'postcode'))
26             self.columns[key] = None if value == '' else value
27
28     def set_key_name(self, value):
29         self.add_hstore('name', 'name', value)
30
31     def set_key_osm(self, value):
32         assert_in(value[0], 'NRW')
33         ok_(value[1:].isdigit())
34
35         self.columns['osm_type'] = value[0]
36         self.columns['osm_id'] = int(value[1:])
37
38     def set_key_admin(self, value):
39         self.columns['admin_level'] = int(value)
40
41     def set_key_housenr(self, value):
42         self.columns['housenumber'] = None if value == '' else value
43
44     def set_key_country(self, value):
45         self.columns['country_code'] = None if value == '' else value
46
47     def set_key_geometry(self, value):
48         self.geometry = self.context.osm.parse_geometry(value, self.context.scene)
49         assert_is_not_none(self.geometry)
50
51     def add_hstore(self, column, key, value):
52         if column in self.columns:
53             self.columns[column][key] = value
54         else:
55             self.columns[column] = { key : value }
56
57     def db_insert(self, cursor):
58         assert_in('osm_type', self.columns)
59         if self.force_name and 'name' not in self.columns:
60             self.add_hstore('name', 'name', ''.join(random.choice(string.printable)
61                                            for _ in range(int(random.random()*30))))
62
63         if self.columns['osm_type'] == 'N' and self.geometry is None:
64             pt = self.context.osm.grid_node(self.columns['osm_id'])
65             if pt is None:
66                 pt = (random.random()*360 - 180, random.random()*180 - 90)
67
68             self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % pt
69         else:
70             assert_is_not_none(self.geometry, "Geometry missing")
71         query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
72                      ','.join(self.columns.keys()),
73                      ','.join(['%s' for x in range(len(self.columns))]),
74                      self.geometry)
75         cursor.execute(query, list(self.columns.values()))
76
77 class NominatimID:
78     """ Splits a unique identifier for places into its components.
79         As place_ids cannot be used for testing, we use a unique
80         identifier instead that is of the form <osmtype><osmid>[:<class>].
81     """
82
83     id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
84
85     def __init__(self, oid):
86         self.typ = self.oid = self.cls = None
87
88         if oid is not None:
89             m = self.id_regex.fullmatch(oid)
90             assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
91
92             self.typ = m.group('tp')
93             self.oid = m.group('id')
94             self.cls = m.group('cls')
95
96     def table_select(self):
97         """ Return where clause and parameter list to select the object
98             from a Nominatim table.
99         """
100         where = 'osm_type = %s and osm_id = %s'
101         params = [self.typ, self. oid]
102
103         if self.cls is not None:
104             where += ' and class = %s'
105             params.append(self.cls)
106
107         return where, params
108
109     def get_place_id(self, cur):
110         where, params = self.table_select()
111         cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
112         eq_(1, cur.rowcount, "Expected exactly 1 entry in placex found %s" % cur.rowcount)
113
114         return cur.fetchone()[0]
115
116
117 def assert_db_column(row, column, value, context):
118     if column == 'object':
119         return
120
121     if column.startswith('centroid'):
122         fac = float(column[9:]) if column.startswith('centroid*') else 1.0
123         x, y = value.split(' ')
124         assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
125         assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
126     elif column == 'geometry':
127         geom = context.osm.parse_geometry(value, context.scene)
128         cur = context.db.cursor()
129         query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
130                  geom, row['geomtxt'],)
131         cur.execute(query)
132         eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
133     elif value == '-':
134         assert_is_none(row[column], "Row %s" % column)
135     else:
136         eq_(value, str(row[column]),
137             "Row '%s': expected: %s, got: %s"
138             % (column, value, str(row[column])))
139
140
141 ################################ STEPS ##################################
142
143 @given(u'the scene (?P<scene>.+)')
144 def set_default_scene(context, scene):
145     context.scene = scene
146
147 @given("the (?P<named>named )?places")
148 def add_data_to_place_table(context, named):
149     cur = context.db.cursor()
150     cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
151     for r in context.table:
152         col = PlaceColumn(context, named is not None)
153
154         for h in r.headings:
155             col.add(h, r[h])
156
157         col.db_insert(cur)
158     cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
159     cur.close()
160     context.db.commit()
161
162 @given("the relations")
163 def add_data_to_planet_relations(context):
164     cur = context.db.cursor()
165     for r in context.table:
166         last_node = 0
167         last_way = 0
168         parts = []
169         if r['members']:
170             members = []
171             for m in r['members'].split(','):
172                 mid = NominatimID(m)
173                 if mid.typ == 'N':
174                     parts.insert(last_node, int(mid.oid))
175                     last_node += 1
176                     last_way += 1
177                 elif mid.typ == 'W':
178                     parts.insert(last_way, int(mid.oid))
179                     last_way += 1
180                 else:
181                     parts.append(int(mid.oid))
182
183                 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
184         else:
185             members = None
186
187         tags = []
188         for h in r.headings:
189             if h.startswith("tags+"):
190                 tags.extend((h[5:], r[h]))
191
192         cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
193                        VALUES (%s, %s, %s, %s, %s, %s)""",
194                     (r['id'], last_node, last_way, parts, members, tags))
195     context.db.commit()
196
197 @given("the ways")
198 def add_data_to_planet_ways(context):
199     cur = context.db.cursor()
200     for r in context.table:
201         tags = []
202         for h in r.headings:
203             if h.startswith("tags+"):
204                 tags.extend((h[5:], r[h]))
205
206         nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
207
208         cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
209                     (r['id'], nodes, tags))
210     context.db.commit()
211
212 @when("importing")
213 def import_and_index_data_from_place_table(context):
214     context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
215     cur = context.db.cursor()
216     cur.execute(
217         """insert into placex (osm_type, osm_id, class, type, name, admin_level,
218            housenumber, street, addr_place, isin, postcode, country_code, extratags,
219            geometry)
220            select * from place where not (class='place' and type='houses' and osm_type='W')""")
221     cur.execute(
222             """insert into location_property_osmline
223                (osm_id, interpolationtype, street, addr_place,
224                 postcode, calculated_country_code, linegeo)
225              SELECT osm_id, housenumber, street, addr_place,
226                     postcode, country_code, geometry from place
227               WHERE class='place' and type='houses' and osm_type='W'
228                     and ST_GeometryType(geometry) = 'ST_LineString'""")
229     context.db.commit()
230     context.nominatim.run_setup_script('index', 'index-noanalyse')
231
232 @when("updating places")
233 def update_place_table(context):
234     context.nominatim.run_setup_script(
235         'create-functions', 'create-partition-functions', 'enable-diff-updates')
236     cur = context.db.cursor()
237     for r in context.table:
238         col = PlaceColumn(context, False)
239
240         for h in r.headings:
241             col.add(h, r[h])
242
243         col.db_insert(cur)
244
245     context.db.commit()
246
247     while True:
248         context.nominatim.run_update_script('index')
249
250         cur = context.db.cursor()
251         cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
252         if cur.rowcount == 0:
253             break
254
255 @when("marking for delete (?P<oids>.*)")
256 def delete_places(context, oids):
257     context.nominatim.run_setup_script(
258         'create-functions', 'create-partition-functions', 'enable-diff-updates')
259     cur = context.db.cursor()
260     for oid in oids.split(','):
261         where, params = NominatimID(oid).table_select()
262         cur.execute("DELETE FROM place WHERE " + where, params)
263     context.db.commit()
264
265     while True:
266         context.nominatim.run_update_script('index')
267
268         cur = context.db.cursor()
269         cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
270         if cur.rowcount == 0:
271             break
272
273 @then("placex contains(?P<exact> exactly)?")
274 def check_placex_contents(context, exact):
275     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
276
277     expected_content = set()
278     for row in context.table:
279         nid = NominatimID(row['object'])
280         where, params = nid.table_select()
281         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
282                        ST_X(centroid) as cx, ST_Y(centroid) as cy
283                        FROM placex where %s""" % where,
284                     params)
285         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
286
287         for res in cur:
288             if exact:
289                 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
290             for h in row.headings:
291                 if h.startswith('name'):
292                     name = h[5:] if h.startswith('name+') else 'name'
293                     assert_in(name, res['name'])
294                     eq_(res['name'][name], row[h])
295                 elif h.startswith('extratags+'):
296                     eq_(res['extratags'][h[10:]], row[h])
297                 elif h in ('linked_place_id', 'parent_place_id'):
298                     if row[h] == '0':
299                         eq_(0, res[h])
300                     elif row[h] == '-':
301                         assert_is_none(res[h])
302                     else:
303                         eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
304                             res[h])
305                 else:
306                     assert_db_column(res, h, row[h], context)
307
308     if exact:
309         cur.execute('SELECT osm_type, osm_id, class from placex')
310         eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
311
312     context.db.commit()
313
314 @then("place contains(?P<exact> exactly)?")
315 def check_placex_contents(context, exact):
316     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
317
318     expected_content = set()
319     for row in context.table:
320         nid = NominatimID(row['object'])
321         where, params = nid.table_select()
322         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
323                        ST_GeometryType(geometry) as geometrytype
324                        FROM place where %s""" % where,
325                     params)
326         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
327
328         for res in cur:
329             if exact:
330                 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
331             for h in row.headings:
332                 msg = "%s: %s" % (row['object'], h)
333                 if h in ('name', 'extratags'):
334                     if row[h] == '-':
335                         assert_is_none(res[h], msg)
336                     else:
337                         vdict = eval('{' + row[h] + '}')
338                         assert_equals(vdict, res[h], msg)
339                 elif h.startswith('name+'):
340                     assert_equals(res['name'][h[5:]], row[h], msg)
341                 elif h.startswith('extratags+'):
342                     assert_equals(res['extratags'][h[10:]], row[h], msg)
343                 elif h in ('linked_place_id', 'parent_place_id'):
344                     if row[h] == '0':
345                         assert_equals(0, res[h], msg)
346                     elif row[h] == '-':
347                         assert_is_none(res[h], msg)
348                     else:
349                         assert_equals(NominatimID(row[h]).get_place_id(context.db.cursor()),
350                                       res[h], msg)
351                 else:
352                     assert_db_column(res, h, row[h], context)
353
354     if exact:
355         cur.execute('SELECT osm_type, osm_id, class from place')
356         eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
357
358     context.db.commit()
359
360 @then("search_name contains")
361 def check_search_name_contents(context):
362     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
363
364     for row in context.table:
365         pid = NominatimID(row['object']).get_place_id(cur)
366         cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
367                        FROM search_name WHERE place_id = %s""", (pid, ))
368         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
369
370         for res in cur:
371             for h in row.headings:
372                 if h in ('name_vector', 'nameaddress_vector'):
373                     terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
374                     subcur = context.db.cursor()
375                     subcur.execute("""SELECT word_id, word_token
376                                       FROM word, (SELECT unnest(%s) as term) t
377                                       WHERE word_token = make_standard_name(t.term)""",
378                                    (terms,))
379                     ok_(subcur.rowcount >= len(terms))
380                     for wid in subcur:
381                         assert_in(wid[0], res[h],
382                                   "Missing term for %s/%s: %s" % (pid, h, wid[1]))
383                 else:
384                     assert_db_column(res, h, row[h], context)
385
386
387     context.db.commit()
388
389 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
390 def check_location_property_osmline(context, oid, neg):
391     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
392     nid = NominatimID(oid)
393
394     eq_('W', nid.typ, "interpolation must be a way")
395
396     cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
397                    FROM location_property_osmline
398                    WHERE osm_id = %s AND startnumber IS NOT NULL""",
399                 (nid.oid, ))
400
401     if neg:
402         eq_(0, cur.rowcount)
403         return
404
405     todo = list(range(len(list(context.table))))
406     for res in cur:
407         for i in todo:
408             row = context.table[i]
409             if (int(row['start']) == res['startnumber']
410                 and int(row['end']) == res['endnumber']):
411                 todo.remove(i)
412                 break
413         else:
414             assert False, "Unexpected row %s" % (str(res))
415
416         for h in row.headings:
417             if h in ('start', 'end'):
418                 continue
419             elif h == 'parent_place_id':
420                 if row[h] == '0':
421                     eq_(0, res[h])
422                 elif row[h] == '-':
423                     assert_is_none(res[h])
424                 else:
425                     eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
426                         res[h])
427             else:
428                 assert_db_column(res, h, row[h], context)
429
430     eq_(todo, [])
431
432
433 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
434 def check_placex_has_entry(context, table, oid):
435     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
436     nid = NominatimID(oid)
437     where, params = nid.table_select()
438     cur.execute("SELECT * FROM %s where %s" % (table, where), params)
439     eq_(0, cur.rowcount)
440     context.db.commit()
441
442 @then("search_name has no entry for (?P<oid>.*)")
443 def check_search_name_has_entry(context, oid):
444     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
445     pid = NominatimID(oid).get_place_id(cur)
446     cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))
447     eq_(0, cur.rowcount)
448     context.db.commit()