5 from nose.tools import * # for assert functions
10 def __init__(self, context, force_name):
11 self.columns = { 'admin_level' : 15}
12 self.force_name = force_name
13 self.context = context
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 elif key in ('name', 'address', 'extratags'):
26 self.columns[key] = eval('{' + value + '}')
28 assert_in(key, ('class', 'type'))
29 self.columns[key] = None if value == '' else value
31 def set_key_name(self, value):
32 self.add_hstore('name', 'name', value)
34 def set_key_osm(self, value):
35 assert_in(value[0], 'NRW')
36 ok_(value[1:].isdigit())
38 self.columns['osm_type'] = value[0]
39 self.columns['osm_id'] = int(value[1:])
41 def set_key_admin(self, value):
42 self.columns['admin_level'] = int(value)
44 def set_key_housenr(self, value):
46 self.add_hstore('address', 'housenumber', value)
48 def set_key_postcode(self, value):
50 self.add_hstore('address', 'postcode', value)
52 def set_key_street(self, value):
54 self.add_hstore('address', 'street', value)
56 def set_key_addr_place(self, value):
58 self.add_hstore('address', 'place', value)
60 def set_key_country(self, value):
62 self.add_hstore('address', 'country', value)
64 def set_key_geometry(self, value):
65 self.geometry = self.context.osm.parse_geometry(value, self.context.scene)
66 assert_is_not_none(self.geometry)
68 def add_hstore(self, column, key, value):
69 if column in self.columns:
70 self.columns[column][key] = value
72 self.columns[column] = { key : value }
74 def db_insert(self, cursor):
75 assert_in('osm_type', self.columns)
76 if self.force_name and 'name' not in self.columns:
77 self.add_hstore('name', 'name', ''.join(random.choice(string.printable)
78 for _ in range(int(random.random()*30))))
80 if self.columns['osm_type'] == 'N' and self.geometry is None:
81 pt = self.context.osm.grid_node(self.columns['osm_id'])
83 pt = (random.random()*360 - 180, random.random()*180 - 90)
85 self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % pt
87 assert_is_not_none(self.geometry, "Geometry missing")
88 query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
89 ','.join(self.columns.keys()),
90 ','.join(['%s' for x in range(len(self.columns))]),
92 cursor.execute(query, list(self.columns.values()))
94 class LazyFmt(object):
96 def __init__(self, fmtstr, *args):
101 return self.fmt % self.args
103 class PlaceObjName(object):
105 def __init__(self, placeid, conn):
116 cur = self.conn.cursor()
117 cur.execute("""SELECT osm_type, osm_id, class
118 FROM placex WHERE place_id = %s""",
120 eq_(1, cur.rowcount, "No entry found for place id %s" % self.pid)
122 return "%s%s:%s" % cur.fetchone()
124 def compare_place_id(expected, result, column, context):
127 LazyFmt("Bad place id in column %s. Expected: 0, got: %s.",
128 column, PlaceObjName(result, context.db)))
129 elif expected == '-':
130 assert_is_none(result,
131 LazyFmt("bad place id in column %s: %s.",
132 column, PlaceObjName(result, context.db)))
134 eq_(NominatimID(expected).get_place_id(context.db.cursor()), result,
135 LazyFmt("Bad place id in column %s. Expected: %s, got: %s.",
136 column, expected, PlaceObjName(result, context.db)))
138 def check_database_integrity(context):
139 """ Check some generic constraints on the tables.
141 # place_addressline should not have duplicate (place_id, address_place_id)
142 cur = context.db.cursor()
143 cur.execute("""SELECT count(*) FROM
144 (SELECT place_id, address_place_id, count(*) as c
145 FROM place_addressline GROUP BY place_id, address_place_id) x
147 eq_(0, cur.fetchone()[0], "Duplicates found in place_addressline")
151 """ Splits a unique identifier for places into its components.
152 As place_ids cannot be used for testing, we use a unique
153 identifier instead that is of the form <osmtype><osmid>[:<class>].
156 id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
158 def __init__(self, oid):
159 self.typ = self.oid = self.cls = None
162 m = self.id_regex.fullmatch(oid)
163 assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
165 self.typ = m.group('tp')
166 self.oid = m.group('id')
167 self.cls = m.group('cls')
171 return self.typ + self.oid
173 return '%s%d:%s' % (self.typ, self.oid, self.cls)
175 def table_select(self):
176 """ Return where clause and parameter list to select the object
177 from a Nominatim table.
179 where = 'osm_type = %s and osm_id = %s'
180 params = [self.typ, self. oid]
182 if self.cls is not None:
183 where += ' and class = %s'
184 params.append(self.cls)
188 def get_place_id(self, cur):
189 where, params = self.table_select()
190 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
192 "Expected exactly 1 entry in placex for %s found %s"
193 % (str(self), cur.rowcount))
195 return cur.fetchone()[0]
198 def assert_db_column(row, column, value, context):
199 if column == 'object':
202 if column.startswith('centroid'):
203 if value == 'in geometry':
204 query = """SELECT ST_Within(ST_SetSRID(ST_Point({}, {}), 4326),
205 ST_SetSRID('{}'::geometry, 4326))""".format(
206 row['cx'], row['cy'], row['geomtxt'])
207 cur = context.db.cursor()
209 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
211 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
212 x, y = value.split(' ')
213 assert_almost_equal(float(x) * fac, row['cx'], msg="Bad x coordinate")
214 assert_almost_equal(float(y) * fac, row['cy'], msg="Bad y coordinate")
215 elif column == 'geometry':
216 geom = context.osm.parse_geometry(value, context.scene)
217 cur = context.db.cursor()
218 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
219 geom, row['geomtxt'],)
221 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
223 assert_is_none(row[column], "Row %s" % column)
225 eq_(value, str(row[column]),
226 "Row '%s': expected: %s, got: %s"
227 % (column, value, str(row[column])))
230 ################################ STEPS ##################################
232 @given(u'the scene (?P<scene>.+)')
233 def set_default_scene(context, scene):
234 context.scene = scene
236 @given("the (?P<named>named )?places")
237 def add_data_to_place_table(context, named):
238 cur = context.db.cursor()
239 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
240 for r in context.table:
241 col = PlaceColumn(context, named is not None)
247 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
251 @given("the relations")
252 def add_data_to_planet_relations(context):
253 cur = context.db.cursor()
254 for r in context.table:
260 for m in r['members'].split(','):
263 parts.insert(last_node, int(mid.oid))
267 parts.insert(last_way, int(mid.oid))
270 parts.append(int(mid.oid))
272 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
278 if h.startswith("tags+"):
279 tags.extend((h[5:], r[h]))
281 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
282 VALUES (%s, %s, %s, %s, %s, %s)""",
283 (r['id'], last_node, last_way, parts, members, tags))
287 def add_data_to_planet_ways(context):
288 cur = context.db.cursor()
289 for r in context.table:
292 if h.startswith("tags+"):
293 tags.extend((h[5:], r[h]))
295 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
297 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
298 (r['id'], nodes, tags))
302 def import_and_index_data_from_place_table(context):
303 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
304 cur = context.db.cursor()
306 """insert into placex (osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry)
307 select osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry
308 from place where not (class='place' and type='houses' and osm_type='W')""")
310 """insert into location_property_osmline (osm_id, address, linegeo)
311 SELECT osm_id, address, geometry from place
312 WHERE class='place' and type='houses' and osm_type='W'
313 and ST_GeometryType(geometry) = 'ST_LineString'""")
315 context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
316 check_database_integrity(context)
318 @when("updating places")
319 def update_place_table(context):
320 context.nominatim.run_setup_script(
321 'create-functions', 'create-partition-functions', 'enable-diff-updates')
322 cur = context.db.cursor()
323 for r in context.table:
324 col = PlaceColumn(context, False)
334 context.nominatim.run_update_script('index')
336 cur = context.db.cursor()
337 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
338 if cur.rowcount == 0:
341 check_database_integrity(context)
343 @when("updating postcodes")
344 def update_postcodes(context):
345 context.nominatim.run_update_script('calculate-postcodes')
347 @when("marking for delete (?P<oids>.*)")
348 def delete_places(context, oids):
349 context.nominatim.run_setup_script(
350 'create-functions', 'create-partition-functions', 'enable-diff-updates')
351 cur = context.db.cursor()
352 for oid in oids.split(','):
353 where, params = NominatimID(oid).table_select()
354 cur.execute("DELETE FROM place WHERE " + where, params)
358 context.nominatim.run_update_script('index')
360 cur = context.db.cursor()
361 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
362 if cur.rowcount == 0:
365 @then("placex contains(?P<exact> exactly)?")
366 def check_placex_contents(context, exact):
367 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
369 expected_content = set()
370 for row in context.table:
371 nid = NominatimID(row['object'])
372 where, params = nid.table_select()
373 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
374 ST_X(centroid) as cx, ST_Y(centroid) as cy
375 FROM placex where %s""" % where,
377 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
381 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
382 for h in row.headings:
383 if h in ('extratags', 'address'):
385 assert_is_none(res[h])
387 vdict = eval('{' + row[h] + '}')
388 assert_equals(vdict, res[h])
389 elif h.startswith('name'):
390 name = h[5:] if h.startswith('name+') else 'name'
391 assert_in(name, res['name'])
392 eq_(res['name'][name], row[h])
393 elif h.startswith('extratags+'):
394 eq_(res['extratags'][h[10:]], row[h])
395 elif h.startswith('addr+'):
397 if res['address'] is not None:
398 assert_not_in(h[5:], res['address'])
400 assert_in(h[5:], res['address'], "column " + h)
401 assert_equals(res['address'][h[5:]], row[h],
403 elif h in ('linked_place_id', 'parent_place_id'):
404 compare_place_id(row[h], res[h], h, context)
406 assert_db_column(res, h, row[h], context)
409 cur.execute('SELECT osm_type, osm_id, class from placex')
410 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
414 @then("place contains(?P<exact> exactly)?")
415 def check_placex_contents(context, exact):
416 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
418 expected_content = set()
419 for row in context.table:
420 nid = NominatimID(row['object'])
421 where, params = nid.table_select()
422 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
423 ST_GeometryType(geometry) as geometrytype
424 FROM place where %s""" % where,
426 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
430 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
431 for h in row.headings:
432 msg = "%s: %s" % (row['object'], h)
433 if h in ('name', 'extratags', 'address'):
435 assert_is_none(res[h], msg)
437 vdict = eval('{' + row[h] + '}')
438 assert_equals(vdict, res[h], msg)
439 elif h.startswith('name+'):
440 assert_equals(res['name'][h[5:]], row[h], msg)
441 elif h.startswith('extratags+'):
442 assert_equals(res['extratags'][h[10:]], row[h], msg)
443 elif h.startswith('addr+'):
445 if res['address'] is not None:
446 assert_not_in(h[5:], res['address'])
448 assert_equals(res['address'][h[5:]], row[h], msg)
449 elif h in ('linked_place_id', 'parent_place_id'):
450 compare_place_id(row[h], res[h], h, context)
452 assert_db_column(res, h, row[h], context)
455 cur.execute('SELECT osm_type, osm_id, class from place')
456 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
460 @then("search_name contains(?P<exclude> not)?")
461 def check_search_name_contents(context, exclude):
462 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
464 for row in context.table:
465 pid = NominatimID(row['object']).get_place_id(cur)
466 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
467 FROM search_name WHERE place_id = %s""", (pid, ))
468 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
471 for h in row.headings:
472 if h in ('name_vector', 'nameaddress_vector'):
473 terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
474 subcur = context.db.cursor()
475 subcur.execute("""SELECT word_id, word_token
476 FROM word, (SELECT unnest(%s) as term) t
477 WHERE word_token = make_standard_name(t.term)""",
480 ok_(subcur.rowcount >= len(terms),
481 "No word entry found for " + row[h])
484 assert_not_in(wid[0], res[h],
485 "Found term for %s/%s: %s" % (pid, h, wid[1]))
487 assert_in(wid[0], res[h],
488 "Missing term for %s/%s: %s" % (pid, h, wid[1]))
490 assert_db_column(res, h, row[h], context)
495 @then("location_postcode contains exactly")
496 def check_location_postcode(context):
497 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
499 cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
500 eq_(cur.rowcount, len(list(context.table)),
501 "Postcode table has %d rows, expected %d rows."
502 % (cur.rowcount, len(list(context.table))))
505 for row in context.table:
506 for i in range(len(table)):
507 if table[i]['country_code'] != row['country'] \
508 or table[i]['postcode'] != row['postcode']:
510 for h in row.headings:
511 if h not in ('country', 'postcode'):
512 assert_db_column(table[i], h, row[h], context)
514 @then("word contains(?P<exclude> not)?")
515 def check_word_table(context, exclude):
516 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
518 for row in context.table:
521 for h in row.headings:
522 wheres.append("%s = %%s" % h)
523 values.append(row[h])
524 cur.execute("SELECT * from word WHERE %s" % ' AND '.join(wheres), values)
527 "Row still in word table: %s" % '/'.join(values))
529 assert_greater(cur.rowcount, 0,
530 "Row not in word table: %s" % '/'.join(values))
532 @then("place_addressline contains")
533 def check_place_addressline(context):
534 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
536 for row in context.table:
537 pid = NominatimID(row['object']).get_place_id(cur)
538 apid = NominatimID(row['address']).get_place_id(cur)
539 cur.execute(""" SELECT * FROM place_addressline
540 WHERE place_id = %s AND address_place_id = %s""",
542 assert_less(0, cur.rowcount,
543 "No rows found for place %s and address %s"
544 % (row['object'], row['address']))
547 for h in row.headings:
548 if h not in ('address', 'object'):
549 assert_db_column(res, h, row[h], context)
553 @then("place_addressline doesn't contain")
554 def check_place_addressline_exclude(context):
555 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
557 for row in context.table:
558 pid = NominatimID(row['object']).get_place_id(cur)
559 apid = NominatimID(row['address']).get_place_id(cur)
560 cur.execute(""" SELECT * FROM place_addressline
561 WHERE place_id = %s AND address_place_id = %s""",
564 "Row found for place %s and address %s" % (row['object'], row['address']))
568 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
569 def check_location_property_osmline(context, oid, neg):
570 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
571 nid = NominatimID(oid)
573 eq_('W', nid.typ, "interpolation must be a way")
575 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
576 FROM location_property_osmline
577 WHERE osm_id = %s AND startnumber IS NOT NULL""",
584 todo = list(range(len(list(context.table))))
587 row = context.table[i]
588 if (int(row['start']) == res['startnumber']
589 and int(row['end']) == res['endnumber']):
593 assert False, "Unexpected row %s" % (str(res))
595 for h in row.headings:
596 if h in ('start', 'end'):
598 elif h == 'parent_place_id':
599 compare_place_id(row[h], res[h], h, context)
601 assert_db_column(res, h, row[h], context)
606 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
607 def check_placex_has_entry(context, table, oid):
608 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
609 nid = NominatimID(oid)
610 where, params = nid.table_select()
611 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
615 @then("search_name has no entry for (?P<oid>.*)")
616 def check_search_name_has_entry(context, oid):
617 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
618 pid = NominatimID(oid).get_place_id(cur)
619 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))