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