7 from check_functions import Almost
11 def __init__(self, context, force_name):
12 self.columns = { 'admin_level' : 15}
13 self.force_name = force_name
14 self.context = context
17 def add(self, key, value):
18 if hasattr(self, 'set_key_' + key):
19 getattr(self, 'set_key_' + key)(value)
20 elif key.startswith('name+'):
21 self.add_hstore('name', key[5:], value)
22 elif key.startswith('extra+'):
23 self.add_hstore('extratags', key[6:], value)
24 elif key.startswith('addr+'):
25 self.add_hstore('address', key[5:], value)
26 elif key in ('name', 'address', 'extratags'):
27 self.columns[key] = eval('{' + value + '}')
29 assert key in ('class', 'type')
30 self.columns[key] = None if value == '' else value
32 def set_key_name(self, value):
33 self.add_hstore('name', 'name', value)
35 def set_key_osm(self, value):
36 assert value[0] in 'NRW'
37 assert value[1:].isdigit()
39 self.columns['osm_type'] = value[0]
40 self.columns['osm_id'] = int(value[1:])
42 def set_key_admin(self, value):
43 self.columns['admin_level'] = int(value)
45 def set_key_housenr(self, value):
47 self.add_hstore('address', 'housenumber', value)
49 def set_key_postcode(self, value):
51 self.add_hstore('address', 'postcode', value)
53 def set_key_street(self, value):
55 self.add_hstore('address', 'street', value)
57 def set_key_addr_place(self, value):
59 self.add_hstore('address', 'place', value)
61 def set_key_country(self, value):
63 self.add_hstore('address', 'country', value)
65 def set_key_geometry(self, value):
66 self.geometry = self.context.osm.parse_geometry(value, self.context.scene)
67 assert self.geometry is not None
69 def add_hstore(self, column, key, value):
70 if column in self.columns:
71 self.columns[column][key] = value
73 self.columns[column] = { key : value }
75 def db_insert(self, cursor):
76 assert 'osm_type' in self.columns
77 if self.force_name and 'name' not in self.columns:
78 self.add_hstore('name', 'name', ''.join(random.choice(string.printable)
79 for _ in range(int(random.random()*30))))
81 if self.columns['osm_type'] == 'N' and self.geometry is None:
82 pt = self.context.osm.grid_node(self.columns['osm_id'])
84 pt = (random.random()*360 - 180, random.random()*180 - 90)
86 self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % pt
88 assert self.geometry is not None, "Geometry missing"
89 query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
90 ','.join(self.columns.keys()),
91 ','.join(['%s' for x in range(len(self.columns))]),
93 cursor.execute(query, list(self.columns.values()))
96 class PlaceObjName(object):
98 def __init__(self, placeid, conn):
109 cur = self.conn.cursor()
110 cur.execute("""SELECT osm_type, osm_id, class
111 FROM placex WHERE place_id = %s""",
113 assert cur.rowcount == 1, "No entry found for place id %s" % self.pid
115 return "%s%s:%s" % cur.fetchone()
117 def compare_place_id(expected, result, column, context):
119 assert result == 0, \
120 "Bad place id in column {}. Expected: 0, got: {!s}.".format(
121 column, PlaceObjName(result, context.db))
122 elif expected == '-':
123 assert result is None, \
124 "Bad place id in column {}: {!s}.".format(
125 column, PlaceObjName(result, context.db))
127 assert NominatimID(expected).get_place_id(context.db.cursor()) == result, \
128 "Bad place id in column {}. Expected: {}, got: {!s}.".format(
129 column, expected, PlaceObjName(result, context.db))
131 def check_database_integrity(context):
132 """ Check some generic constraints on the tables.
134 # place_addressline should not have duplicate (place_id, address_place_id)
135 cur = context.db.cursor()
136 cur.execute("""SELECT count(*) FROM
137 (SELECT place_id, address_place_id, count(*) as c
138 FROM place_addressline GROUP BY place_id, address_place_id) x
140 assert cur.fetchone()[0] == 0, "Duplicates found in place_addressline"
144 """ Splits a unique identifier for places into its components.
145 As place_ids cannot be used for testing, we use a unique
146 identifier instead that is of the form <osmtype><osmid>[:<class>].
149 id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
151 def __init__(self, oid):
152 self.typ = self.oid = self.cls = None
155 m = self.id_regex.fullmatch(oid)
156 assert m is not None, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid
158 self.typ = m.group('tp')
159 self.oid = m.group('id')
160 self.cls = m.group('cls')
164 return self.typ + self.oid
166 return '%s%d:%s' % (self.typ, self.oid, self.cls)
168 def table_select(self):
169 """ Return where clause and parameter list to select the object
170 from a Nominatim table.
172 where = 'osm_type = %s and osm_id = %s'
173 params = [self.typ, self. oid]
175 if self.cls is not None:
176 where += ' and class = %s'
177 params.append(self.cls)
181 def get_place_id(self, cur):
182 where, params = self.table_select()
183 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
184 assert cur.rowcount == 1, \
185 "Expected exactly 1 entry in placex for %s found %s" % (str(self), cur.rowcount)
187 return cur.fetchone()[0]
190 def assert_db_column(row, column, value, context):
191 if column == 'object':
194 if column.startswith('centroid'):
195 if value == 'in geometry':
196 query = """SELECT ST_Within(ST_SetSRID(ST_Point({}, {}), 4326),
197 ST_SetSRID('{}'::geometry, 4326))""".format(
198 row['cx'], row['cy'], row['geomtxt'])
199 cur = context.db.cursor()
201 assert cur.fetchone()[0], "(Row %s failed: %s)" % (column, query)
203 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
204 x, y = value.split(' ')
205 assert Almost(float(x) * fac) == row['cx'], "Bad x coordinate"
206 assert Almost(float(y) * fac) == row['cy'], "Bad y coordinate"
207 elif column == 'geometry':
208 geom = context.osm.parse_geometry(value, context.scene)
209 cur = context.db.cursor()
210 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
211 geom, row['geomtxt'],)
213 assert cur.fetchone()[0], "(Row %s failed: %s)" % (column, query)
215 assert row[column] is None, "Row %s" % column
217 assert value == str(row[column]), \
218 "Row '%s': expected: %s, got: %s" % (column, value, str(row[column]))
221 ################################ STEPS ##################################
223 @given(u'the scene (?P<scene>.+)')
224 def set_default_scene(context, scene):
225 context.scene = scene
227 @given("the (?P<named>named )?places")
228 def add_data_to_place_table(context, named):
229 cur = context.db.cursor()
230 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
231 for r in context.table:
232 col = PlaceColumn(context, named is not None)
238 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
242 @given("the relations")
243 def add_data_to_planet_relations(context):
244 cur = context.db.cursor()
245 for r in context.table:
251 for m in r['members'].split(','):
254 parts.insert(last_node, int(mid.oid))
258 parts.insert(last_way, int(mid.oid))
261 parts.append(int(mid.oid))
263 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
269 if h.startswith("tags+"):
270 tags.extend((h[5:], r[h]))
272 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
273 VALUES (%s, %s, %s, %s, %s, %s)""",
274 (r['id'], last_node, last_way, parts, members, tags))
278 def add_data_to_planet_ways(context):
279 cur = context.db.cursor()
280 for r in context.table:
283 if h.startswith("tags+"):
284 tags.extend((h[5:], r[h]))
286 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
288 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
289 (r['id'], nodes, tags))
293 def import_and_index_data_from_place_table(context):
294 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
295 cur = context.db.cursor()
297 """insert into placex (osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry)
298 select osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry
299 from place where not (class='place' and type='houses' and osm_type='W')""")
301 """insert into location_property_osmline (osm_id, address, linegeo)
302 SELECT osm_id, address, geometry from place
303 WHERE class='place' and type='houses' and osm_type='W'
304 and ST_GeometryType(geometry) = 'ST_LineString'""")
306 context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
307 check_database_integrity(context)
309 @when("updating places")
310 def update_place_table(context):
311 context.nominatim.run_setup_script(
312 'create-functions', 'create-partition-functions', 'enable-diff-updates')
313 cur = context.db.cursor()
314 for r in context.table:
315 col = PlaceColumn(context, False)
325 context.nominatim.run_update_script('index')
327 cur = context.db.cursor()
328 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
329 if cur.rowcount == 0:
332 check_database_integrity(context)
334 @when("updating postcodes")
335 def update_postcodes(context):
336 context.nominatim.run_update_script('calculate-postcodes')
338 @when("marking for delete (?P<oids>.*)")
339 def delete_places(context, oids):
340 context.nominatim.run_setup_script(
341 'create-functions', 'create-partition-functions', 'enable-diff-updates')
342 cur = context.db.cursor()
343 for oid in oids.split(','):
344 where, params = NominatimID(oid).table_select()
345 cur.execute("DELETE FROM place WHERE " + where, params)
349 context.nominatim.run_update_script('index')
351 cur = context.db.cursor()
352 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
353 if cur.rowcount == 0:
356 @then("placex contains(?P<exact> exactly)?")
357 def check_placex_contents(context, exact):
358 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
360 expected_content = set()
361 for row in context.table:
362 nid = NominatimID(row['object'])
363 where, params = nid.table_select()
364 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
365 ST_X(centroid) as cx, ST_Y(centroid) as cy
366 FROM placex where %s""" % where,
368 assert cur.rowcount > 0, "No rows found for " + row['object']
372 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
373 for h in row.headings:
374 if h in ('extratags', 'address'):
376 assert res[h] is None
378 vdict = eval('{' + row[h] + '}')
379 assert vdict == res[h]
380 elif h.startswith('name'):
381 name = h[5:] if h.startswith('name+') else 'name'
382 assert name in res['name']
383 assert res['name'][name] == row[h]
384 elif h.startswith('extratags+'):
385 assert res['extratags'][h[10:]] == row[h]
386 elif h.startswith('addr+'):
388 if res['address'] is not None:
389 assert h[5:] not in res['address']
391 assert h[5:] in res['address'], "column " + h
392 assert res['address'][h[5:]] == row[h], "column %s" % h
393 elif h in ('linked_place_id', 'parent_place_id'):
394 compare_place_id(row[h], res[h], h, context)
396 assert_db_column(res, h, row[h], context)
399 cur.execute('SELECT osm_type, osm_id, class from placex')
400 assert expected_content == set([(r[0], r[1], r[2]) for r in cur])
404 @then("place contains(?P<exact> exactly)?")
405 def check_placex_contents(context, exact):
406 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
408 expected_content = set()
409 for row in context.table:
410 nid = NominatimID(row['object'])
411 where, params = nid.table_select()
412 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
413 ST_GeometryType(geometry) as geometrytype
414 FROM place where %s""" % where,
416 assert cur.rowcount > 0, "No rows found for " + row['object']
420 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
421 for h in row.headings:
422 msg = "%s: %s" % (row['object'], h)
423 if h in ('name', 'extratags', 'address'):
425 assert res[h] is None, msg
427 vdict = eval('{' + row[h] + '}')
428 assert vdict == res[h], msg
429 elif h.startswith('name+'):
430 assert res['name'][h[5:]] == row[h], msg
431 elif h.startswith('extratags+'):
432 assert res['extratags'][h[10:]] == row[h], msg
433 elif h.startswith('addr+'):
435 if res['address'] is not None:
436 assert h[5:] not in res['address']
438 assert res['address'][h[5:]] == row[h], msg
439 elif h in ('linked_place_id', 'parent_place_id'):
440 compare_place_id(row[h], res[h], h, context)
442 assert_db_column(res, h, row[h], context)
445 cur.execute('SELECT osm_type, osm_id, class from place')
446 assert expected_content, set([(r[0], r[1], r[2]) for r in cur])
450 @then("search_name contains(?P<exclude> not)?")
451 def check_search_name_contents(context, exclude):
452 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
454 for row in context.table:
455 pid = NominatimID(row['object']).get_place_id(cur)
456 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
457 FROM search_name WHERE place_id = %s""", (pid, ))
458 assert cur.rowcount > 0, "No rows found for " + row['object']
461 for h in row.headings:
462 if h in ('name_vector', 'nameaddress_vector'):
463 terms = [x.strip() for x in row[h].split(',') if not x.strip().startswith('#')]
464 words = [x.strip()[1:] for x in row[h].split(',') if x.strip().startswith('#')]
465 subcur = context.db.cursor()
466 subcur.execute(""" SELECT word_id, word_token
467 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
468 WHERE word_token = make_standard_name(t.term)
469 and class is null and country_code is null
472 SELECT word_id, word_token
473 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
474 WHERE word_token = ' ' || make_standard_name(t.term)
475 and class is null and country_code is null
480 assert subcur.rowcount >= len(terms) + len(words), \
481 "No word entry found for " + row[h] + ". Entries found: " + str(subcur.rowcount)
484 assert wid[0] not in res[h], "Found term for %s/%s: %s" % (pid, h, wid[1])
486 assert wid[0] in res[h], "Missing term for %s/%s: %s" % (pid, h, wid[1])
488 assert_db_column(res, h, row[h], context)
493 @then("location_postcode contains exactly")
494 def check_location_postcode(context):
495 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
497 cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
498 assert cur.rowcount == len(list(context.table)), \
499 "Postcode table has %d rows, expected %d rows." % (cur.rowcount, len(list(context.table)))
502 for row in context.table:
503 for i in range(len(table)):
504 if table[i]['country_code'] != row['country'] \
505 or table[i]['postcode'] != row['postcode']:
507 for h in row.headings:
508 if h not in ('country', 'postcode'):
509 assert_db_column(table[i], h, row[h], context)
511 @then("word contains(?P<exclude> not)?")
512 def check_word_table(context, exclude):
513 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
515 for row in context.table:
518 for h in row.headings:
519 wheres.append("%s = %%s" % h)
520 values.append(row[h])
521 cur.execute("SELECT * from word WHERE %s" % ' AND '.join(wheres), values)
523 assert cur.rowcount == 0, "Row still in word table: %s" % '/'.join(values)
525 assert cur.rowcount > 0, "Row not in word table: %s" % '/'.join(values)
527 @then("place_addressline contains")
528 def check_place_addressline(context):
529 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
531 for row in context.table:
532 pid = NominatimID(row['object']).get_place_id(cur)
533 apid = NominatimID(row['address']).get_place_id(cur)
534 cur.execute(""" SELECT * FROM place_addressline
535 WHERE place_id = %s AND address_place_id = %s""",
537 assert cur.rowcount > 0, \
538 "No rows found for place %s and address %s" % (row['object'], row['address'])
541 for h in row.headings:
542 if h not in ('address', 'object'):
543 assert_db_column(res, h, row[h], context)
547 @then("place_addressline doesn't contain")
548 def check_place_addressline_exclude(context):
549 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
551 for row in context.table:
552 pid = NominatimID(row['object']).get_place_id(cur)
553 apid = NominatimID(row['address']).get_place_id(cur)
554 cur.execute(""" SELECT * FROM place_addressline
555 WHERE place_id = %s AND address_place_id = %s""",
557 assert cur.rowcount == 0, \
558 "Row found for place %s and address %s" % (row['object'], row['address'])
562 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
563 def check_location_property_osmline(context, oid, neg):
564 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
565 nid = NominatimID(oid)
567 assert 'W' == nid.typ, "interpolation must be a way"
569 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
570 FROM location_property_osmline
571 WHERE osm_id = %s AND startnumber IS NOT NULL""",
575 assert cur.rowcount == 0
578 todo = list(range(len(list(context.table))))
581 row = context.table[i]
582 if (int(row['start']) == res['startnumber']
583 and int(row['end']) == res['endnumber']):
587 assert False, "Unexpected row %s" % (str(res))
589 for h in row.headings:
590 if h in ('start', 'end'):
592 elif h == 'parent_place_id':
593 compare_place_id(row[h], res[h], h, context)
595 assert_db_column(res, h, row[h], context)
600 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
601 def check_placex_has_entry(context, table, oid):
602 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
603 nid = NominatimID(oid)
604 where, params = nid.table_select()
605 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
606 assert cur.rowcount == 0
609 @then("search_name has no entry for (?P<oid>.*)")
610 def check_search_name_has_entry(context, oid):
611 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
612 pid = NominatimID(oid).get_place_id(cur)
613 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))
614 assert cur.rowcount == 0