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()))
95 class LazyFmt(object):
97 def __init__(self, fmtstr, *args):
102 return self.fmt % self.args
104 class PlaceObjName(object):
106 def __init__(self, placeid, conn):
117 cur = self.conn.cursor()
118 cur.execute("""SELECT osm_type, osm_id, class
119 FROM placex WHERE place_id = %s""",
121 assert cur.rowcount == 1, "No entry found for place id %s" % self.pid
123 return "%s%s:%s" % cur.fetchone()
125 def compare_place_id(expected, result, column, context):
127 assert result == 0, \
128 LazyFmt("Bad place id in column %s. Expected: 0, got: %s.",
129 column, PlaceObjName(result, context.db))
130 elif expected == '-':
131 assert result is None, \
132 LazyFmt("bad place id in column %s: %s.",
133 column, PlaceObjName(result, context.db))
135 assert NominatimID(expected).get_place_id(context.db.cursor()) == result, \
136 LazyFmt("Bad place id in column %s. Expected: %s, got: %s.",
137 column, expected, PlaceObjName(result, context.db))
139 def check_database_integrity(context):
140 """ Check some generic constraints on the tables.
142 # place_addressline should not have duplicate (place_id, address_place_id)
143 cur = context.db.cursor()
144 cur.execute("""SELECT count(*) FROM
145 (SELECT place_id, address_place_id, count(*) as c
146 FROM place_addressline GROUP BY place_id, address_place_id) x
148 assert cur.fetchone()[0] == 0, "Duplicates found in place_addressline"
152 """ Splits a unique identifier for places into its components.
153 As place_ids cannot be used for testing, we use a unique
154 identifier instead that is of the form <osmtype><osmid>[:<class>].
157 id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
159 def __init__(self, oid):
160 self.typ = self.oid = self.cls = None
163 m = self.id_regex.fullmatch(oid)
164 assert m is not None, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid
166 self.typ = m.group('tp')
167 self.oid = m.group('id')
168 self.cls = m.group('cls')
172 return self.typ + self.oid
174 return '%s%d:%s' % (self.typ, self.oid, self.cls)
176 def table_select(self):
177 """ Return where clause and parameter list to select the object
178 from a Nominatim table.
180 where = 'osm_type = %s and osm_id = %s'
181 params = [self.typ, self. oid]
183 if self.cls is not None:
184 where += ' and class = %s'
185 params.append(self.cls)
189 def get_place_id(self, cur):
190 where, params = self.table_select()
191 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
192 assert cur.rowcount == 1, \
193 "Expected exactly 1 entry in placex for %s found %s" % (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 assert cur.fetchone()[0], "(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(float(x) * fac) == row['cx'], "Bad x coordinate"
214 assert Almost(float(y) * fac) == row['cy'], "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 assert cur.fetchone()[0], "(Row %s failed: %s)" % (column, query)
223 assert row[column] is None, "Row %s" % column
225 assert value == str(row[column]), \
226 "Row '%s': expected: %s, got: %s" % (column, value, str(row[column]))
229 ################################ STEPS ##################################
231 @given(u'the scene (?P<scene>.+)')
232 def set_default_scene(context, scene):
233 context.scene = scene
235 @given("the (?P<named>named )?places")
236 def add_data_to_place_table(context, named):
237 cur = context.db.cursor()
238 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
239 for r in context.table:
240 col = PlaceColumn(context, named is not None)
246 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
250 @given("the relations")
251 def add_data_to_planet_relations(context):
252 cur = context.db.cursor()
253 for r in context.table:
259 for m in r['members'].split(','):
262 parts.insert(last_node, int(mid.oid))
266 parts.insert(last_way, int(mid.oid))
269 parts.append(int(mid.oid))
271 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
277 if h.startswith("tags+"):
278 tags.extend((h[5:], r[h]))
280 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
281 VALUES (%s, %s, %s, %s, %s, %s)""",
282 (r['id'], last_node, last_way, parts, members, tags))
286 def add_data_to_planet_ways(context):
287 cur = context.db.cursor()
288 for r in context.table:
291 if h.startswith("tags+"):
292 tags.extend((h[5:], r[h]))
294 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
296 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
297 (r['id'], nodes, tags))
301 def import_and_index_data_from_place_table(context):
302 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
303 cur = context.db.cursor()
305 """insert into placex (osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry)
306 select osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry
307 from place where not (class='place' and type='houses' and osm_type='W')""")
309 """insert into location_property_osmline (osm_id, address, linegeo)
310 SELECT osm_id, address, geometry from place
311 WHERE class='place' and type='houses' and osm_type='W'
312 and ST_GeometryType(geometry) = 'ST_LineString'""")
314 context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
315 check_database_integrity(context)
317 @when("updating places")
318 def update_place_table(context):
319 context.nominatim.run_setup_script(
320 'create-functions', 'create-partition-functions', 'enable-diff-updates')
321 cur = context.db.cursor()
322 for r in context.table:
323 col = PlaceColumn(context, False)
333 context.nominatim.run_update_script('index')
335 cur = context.db.cursor()
336 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
337 if cur.rowcount == 0:
340 check_database_integrity(context)
342 @when("updating postcodes")
343 def update_postcodes(context):
344 context.nominatim.run_update_script('calculate-postcodes')
346 @when("marking for delete (?P<oids>.*)")
347 def delete_places(context, oids):
348 context.nominatim.run_setup_script(
349 'create-functions', 'create-partition-functions', 'enable-diff-updates')
350 cur = context.db.cursor()
351 for oid in oids.split(','):
352 where, params = NominatimID(oid).table_select()
353 cur.execute("DELETE FROM place WHERE " + where, params)
357 context.nominatim.run_update_script('index')
359 cur = context.db.cursor()
360 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
361 if cur.rowcount == 0:
364 @then("placex contains(?P<exact> exactly)?")
365 def check_placex_contents(context, exact):
366 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
368 expected_content = set()
369 for row in context.table:
370 nid = NominatimID(row['object'])
371 where, params = nid.table_select()
372 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
373 ST_X(centroid) as cx, ST_Y(centroid) as cy
374 FROM placex where %s""" % where,
376 assert cur.rowcount > 0, "No rows found for " + row['object']
380 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
381 for h in row.headings:
382 if h in ('extratags', 'address'):
384 assert res[h] is None
386 vdict = eval('{' + row[h] + '}')
387 assert vdict == res[h]
388 elif h.startswith('name'):
389 name = h[5:] if h.startswith('name+') else 'name'
390 assert name in res['name']
391 assert res['name'][name] == row[h]
392 elif h.startswith('extratags+'):
393 assert res['extratags'][h[10:]] == row[h]
394 elif h.startswith('addr+'):
396 if res['address'] is not None:
397 assert h[5:] not in res['address']
399 assert h[5:] in res['address'], "column " + h
400 assert res['address'][h[5:]] == row[h], "column %s" % h
401 elif h in ('linked_place_id', 'parent_place_id'):
402 compare_place_id(row[h], res[h], h, context)
404 assert_db_column(res, h, row[h], context)
407 cur.execute('SELECT osm_type, osm_id, class from placex')
408 assert expected_content == set([(r[0], r[1], r[2]) for r in cur])
412 @then("place contains(?P<exact> exactly)?")
413 def check_placex_contents(context, exact):
414 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
416 expected_content = set()
417 for row in context.table:
418 nid = NominatimID(row['object'])
419 where, params = nid.table_select()
420 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
421 ST_GeometryType(geometry) as geometrytype
422 FROM place where %s""" % where,
424 assert cur.rowcount > 0, "No rows found for " + row['object']
428 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
429 for h in row.headings:
430 msg = "%s: %s" % (row['object'], h)
431 if h in ('name', 'extratags', 'address'):
433 assert res[h] is None, msg
435 vdict = eval('{' + row[h] + '}')
436 assert vdict == res[h], msg
437 elif h.startswith('name+'):
438 assert res['name'][h[5:]] == row[h], msg
439 elif h.startswith('extratags+'):
440 assert res['extratags'][h[10:]] == row[h], msg
441 elif h.startswith('addr+'):
443 if res['address'] is not None:
444 assert h[5:] not in res['address']
446 assert res['address'][h[5:]] == row[h], msg
447 elif h in ('linked_place_id', 'parent_place_id'):
448 compare_place_id(row[h], res[h], h, context)
450 assert_db_column(res, h, row[h], context)
453 cur.execute('SELECT osm_type, osm_id, class from place')
454 assert expected_content, set([(r[0], r[1], r[2]) for r in cur])
458 @then("search_name contains(?P<exclude> not)?")
459 def check_search_name_contents(context, exclude):
460 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
462 for row in context.table:
463 pid = NominatimID(row['object']).get_place_id(cur)
464 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
465 FROM search_name WHERE place_id = %s""", (pid, ))
466 assert cur.rowcount > 0, "No rows found for " + row['object']
469 for h in row.headings:
470 if h in ('name_vector', 'nameaddress_vector'):
471 terms = [x.strip() for x in row[h].split(',') if not x.strip().startswith('#')]
472 words = [x.strip()[1:] for x in row[h].split(',') if x.strip().startswith('#')]
473 subcur = context.db.cursor()
474 subcur.execute(""" SELECT word_id, word_token
475 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
476 WHERE word_token = make_standard_name(t.term)
477 and class is null and country_code is null
480 SELECT word_id, word_token
481 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
482 WHERE word_token = ' ' || make_standard_name(t.term)
483 and class is null and country_code is null
488 assert subcur.rowcount >= len(terms) + len(words), \
489 "No word entry found for " + row[h] + ". Entries found: " + str(subcur.rowcount)
492 assert wid[0] not in res[h], "Found term for %s/%s: %s" % (pid, h, wid[1])
494 assert wid[0] in res[h], "Missing term for %s/%s: %s" % (pid, h, wid[1])
496 assert_db_column(res, h, row[h], context)
501 @then("location_postcode contains exactly")
502 def check_location_postcode(context):
503 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
505 cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
506 assert cur.rowcount == len(list(context.table)), \
507 "Postcode table has %d rows, expected %d rows." % (cur.rowcount, len(list(context.table)))
510 for row in context.table:
511 for i in range(len(table)):
512 if table[i]['country_code'] != row['country'] \
513 or table[i]['postcode'] != row['postcode']:
515 for h in row.headings:
516 if h not in ('country', 'postcode'):
517 assert_db_column(table[i], h, row[h], context)
519 @then("word contains(?P<exclude> not)?")
520 def check_word_table(context, exclude):
521 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
523 for row in context.table:
526 for h in row.headings:
527 wheres.append("%s = %%s" % h)
528 values.append(row[h])
529 cur.execute("SELECT * from word WHERE %s" % ' AND '.join(wheres), values)
531 assert cur.rowcount == 0, "Row still in word table: %s" % '/'.join(values)
533 assert cur.rowcount > 0, "Row not in word table: %s" % '/'.join(values)
535 @then("place_addressline contains")
536 def check_place_addressline(context):
537 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
539 for row in context.table:
540 pid = NominatimID(row['object']).get_place_id(cur)
541 apid = NominatimID(row['address']).get_place_id(cur)
542 cur.execute(""" SELECT * FROM place_addressline
543 WHERE place_id = %s AND address_place_id = %s""",
545 assert cur.rowcount > 0, \
546 "No rows found for place %s and address %s" % (row['object'], row['address'])
549 for h in row.headings:
550 if h not in ('address', 'object'):
551 assert_db_column(res, h, row[h], context)
555 @then("place_addressline doesn't contain")
556 def check_place_addressline_exclude(context):
557 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
559 for row in context.table:
560 pid = NominatimID(row['object']).get_place_id(cur)
561 apid = NominatimID(row['address']).get_place_id(cur)
562 cur.execute(""" SELECT * FROM place_addressline
563 WHERE place_id = %s AND address_place_id = %s""",
565 assert cur.rowcount == 0, \
566 "Row found for place %s and address %s" % (row['object'], row['address'])
570 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
571 def check_location_property_osmline(context, oid, neg):
572 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
573 nid = NominatimID(oid)
575 assert 'W' == nid.typ, "interpolation must be a way"
577 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
578 FROM location_property_osmline
579 WHERE osm_id = %s AND startnumber IS NOT NULL""",
583 assert cur.rowcount == 0
586 todo = list(range(len(list(context.table))))
589 row = context.table[i]
590 if (int(row['start']) == res['startnumber']
591 and int(row['end']) == res['endnumber']):
595 assert False, "Unexpected row %s" % (str(res))
597 for h in row.headings:
598 if h in ('start', 'end'):
600 elif h == 'parent_place_id':
601 compare_place_id(row[h], res[h], h, context)
603 assert_db_column(res, h, row[h], context)
608 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
609 def check_placex_has_entry(context, table, oid):
610 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
611 nid = NominatimID(oid)
612 where, params = nid.table_select()
613 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
614 assert cur.rowcount == 0
617 @then("search_name has no entry for (?P<oid>.*)")
618 def check_search_name_has_entry(context, oid):
619 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
620 pid = NominatimID(oid).get_place_id(cur)
621 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))
622 assert cur.rowcount == 0