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