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 ################################ GIVEN ##################################
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 with context.db.cursor() as cur:
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')
240 @given("the relations")
241 def add_data_to_planet_relations(context):
242 with context.db.cursor() as cur:
243 for r in context.table:
249 for m in r['members'].split(','):
252 parts.insert(last_node, int(mid.oid))
256 parts.insert(last_way, int(mid.oid))
259 parts.append(int(mid.oid))
261 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
267 if h.startswith("tags+"):
268 tags.extend((h[5:], r[h]))
270 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
271 VALUES (%s, %s, %s, %s, %s, %s)""",
272 (r['id'], last_node, last_way, parts, members, tags))
275 def add_data_to_planet_ways(context):
276 with context.db.cursor() as cur:
277 for r in context.table:
280 if h.startswith("tags+"):
281 tags.extend((h[5:], r[h]))
283 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
285 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
286 (r['id'], nodes, tags))
288 ################################ WHEN ##################################
291 def import_and_index_data_from_place_table(context):
292 """ Import data previously set up in the place table.
294 context.nominatim.copy_from_place(context.db)
295 context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
296 check_database_integrity(context)
298 @when("updating places")
299 def update_place_table(context):
300 context.nominatim.run_setup_script(
301 'create-functions', 'create-partition-functions', 'enable-diff-updates')
302 with context.db.cursor() as cur:
303 for r in context.table:
304 col = PlaceColumn(context, False)
312 context.nominatim.run_update_script('index')
314 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
315 if cur.rowcount == 0:
318 check_database_integrity(context)
320 @when("updating postcodes")
321 def update_postcodes(context):
322 context.nominatim.run_update_script('calculate-postcodes')
324 @when("marking for delete (?P<oids>.*)")
325 def delete_places(context, oids):
326 context.nominatim.run_setup_script(
327 'create-functions', 'create-partition-functions', 'enable-diff-updates')
328 with context.db.cursor() as cur:
329 for oid in oids.split(','):
330 where, params = NominatimID(oid).table_select()
331 cur.execute("DELETE FROM place WHERE " + where, params)
334 context.nominatim.run_update_script('index')
336 with context.db.cursor() as cur:
337 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
338 if cur.rowcount == 0:
341 ################################ THEN ##################################
343 @then("placex contains(?P<exact> exactly)?")
344 def check_placex_contents(context, exact):
345 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
346 expected_content = set()
347 for row in context.table:
348 nid = NominatimID(row['object'])
349 where, params = nid.table_select()
350 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
351 ST_X(centroid) as cx, ST_Y(centroid) as cy
352 FROM placex where %s""" % where,
354 assert cur.rowcount > 0, "No rows found for " + row['object']
358 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
359 for h in row.headings:
360 if h in ('extratags', 'address'):
362 assert res[h] is None
364 vdict = eval('{' + row[h] + '}')
365 assert vdict == res[h]
366 elif h.startswith('name'):
367 name = h[5:] if h.startswith('name+') else 'name'
368 assert name in res['name']
369 assert res['name'][name] == row[h]
370 elif h.startswith('extratags+'):
371 assert res['extratags'][h[10:]] == row[h]
372 elif h.startswith('addr+'):
374 if res['address'] is not None:
375 assert h[5:] not in res['address']
377 assert h[5:] in res['address'], "column " + h
378 assert res['address'][h[5:]] == row[h], "column %s" % h
379 elif h in ('linked_place_id', 'parent_place_id'):
380 compare_place_id(row[h], res[h], h, context)
382 assert_db_column(res, h, row[h], context)
385 cur.execute('SELECT osm_type, osm_id, class from placex')
386 assert expected_content == set([(r[0], r[1], r[2]) for r in cur])
388 @then("place contains(?P<exact> exactly)?")
389 def check_placex_contents(context, exact):
390 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
391 expected_content = set()
392 for row in context.table:
393 nid = NominatimID(row['object'])
394 where, params = nid.table_select()
395 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
396 ST_GeometryType(geometry) as geometrytype
397 FROM place where %s""" % where,
399 assert cur.rowcount > 0, "No rows found for " + row['object']
403 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
404 for h in row.headings:
405 msg = "%s: %s" % (row['object'], h)
406 if h in ('name', 'extratags', 'address'):
408 assert res[h] is None, msg
410 vdict = eval('{' + row[h] + '}')
411 assert vdict == res[h], msg
412 elif h.startswith('name+'):
413 assert res['name'][h[5:]] == row[h], msg
414 elif h.startswith('extratags+'):
415 assert res['extratags'][h[10:]] == row[h], msg
416 elif h.startswith('addr+'):
418 if res['address'] is not None:
419 assert h[5:] not in res['address']
421 assert res['address'][h[5:]] == row[h], msg
422 elif h in ('linked_place_id', 'parent_place_id'):
423 compare_place_id(row[h], res[h], h, context)
425 assert_db_column(res, h, row[h], context)
428 cur.execute('SELECT osm_type, osm_id, class from place')
429 assert expected_content, set([(r[0], r[1], r[2]) for r in cur])
431 @then("search_name contains(?P<exclude> not)?")
432 def check_search_name_contents(context, exclude):
433 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
434 for row in context.table:
435 pid = NominatimID(row['object']).get_place_id(cur)
436 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
437 FROM search_name WHERE place_id = %s""", (pid, ))
438 assert cur.rowcount > 0, "No rows found for " + row['object']
441 for h in row.headings:
442 if h in ('name_vector', 'nameaddress_vector'):
443 terms = [x.strip() for x in row[h].split(',') if not x.strip().startswith('#')]
444 words = [x.strip()[1:] for x in row[h].split(',') if x.strip().startswith('#')]
445 with context.db.cursor() as subcur:
446 subcur.execute(""" SELECT word_id, word_token
447 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
448 WHERE word_token = make_standard_name(t.term)
449 and class is null and country_code is null
452 SELECT word_id, word_token
453 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
454 WHERE word_token = ' ' || make_standard_name(t.term)
455 and class is null and country_code is null
460 assert subcur.rowcount >= len(terms) + len(words), \
461 "No word entry found for " + row[h] + ". Entries found: " + str(subcur.rowcount)
464 assert wid[0] not in res[h], "Found term for %s/%s: %s" % (pid, h, wid[1])
466 assert wid[0] in res[h], "Missing term for %s/%s: %s" % (pid, h, wid[1])
468 assert_db_column(res, h, row[h], context)
470 @then("location_postcode contains exactly")
471 def check_location_postcode(context):
472 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
473 cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
474 assert cur.rowcount == len(list(context.table)), \
475 "Postcode table has %d rows, expected %d rows." % (cur.rowcount, len(list(context.table)))
478 for row in context.table:
479 for i in range(len(table)):
480 if table[i]['country_code'] != row['country'] \
481 or table[i]['postcode'] != row['postcode']:
483 for h in row.headings:
484 if h not in ('country', 'postcode'):
485 assert_db_column(table[i], h, row[h], context)
487 @then("word contains(?P<exclude> not)?")
488 def check_word_table(context, exclude):
489 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
490 for row in context.table:
493 for h in row.headings:
494 wheres.append("%s = %%s" % h)
495 values.append(row[h])
496 cur.execute("SELECT * from word WHERE %s" % ' AND '.join(wheres), values)
498 assert cur.rowcount == 0, "Row still in word table: %s" % '/'.join(values)
500 assert cur.rowcount > 0, "Row not in word table: %s" % '/'.join(values)
502 @then("place_addressline contains")
503 def check_place_addressline(context):
504 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
505 for row in context.table:
506 pid = NominatimID(row['object']).get_place_id(cur)
507 apid = NominatimID(row['address']).get_place_id(cur)
508 cur.execute(""" SELECT * FROM place_addressline
509 WHERE place_id = %s AND address_place_id = %s""",
511 assert cur.rowcount > 0, \
512 "No rows found for place %s and address %s" % (row['object'], row['address'])
515 for h in row.headings:
516 if h not in ('address', 'object'):
517 assert_db_column(res, h, row[h], context)
519 @then("place_addressline doesn't contain")
520 def check_place_addressline_exclude(context):
521 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
522 for row in context.table:
523 pid = NominatimID(row['object']).get_place_id(cur)
524 apid = NominatimID(row['address']).get_place_id(cur)
525 cur.execute(""" SELECT * FROM place_addressline
526 WHERE place_id = %s AND address_place_id = %s""",
528 assert cur.rowcount == 0, \
529 "Row found for place %s and address %s" % (row['object'], row['address'])
531 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
532 def check_location_property_osmline(context, oid, neg):
533 nid = NominatimID(oid)
535 assert 'W' == nid.typ, "interpolation must be a way"
537 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
538 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
539 FROM location_property_osmline
540 WHERE osm_id = %s AND startnumber IS NOT NULL""",
544 assert cur.rowcount == 0
547 todo = list(range(len(list(context.table))))
550 row = context.table[i]
551 if (int(row['start']) == res['startnumber']
552 and int(row['end']) == res['endnumber']):
556 assert False, "Unexpected row %s" % (str(res))
558 for h in row.headings:
559 if h in ('start', 'end'):
561 elif h == 'parent_place_id':
562 compare_place_id(row[h], res[h], h, context)
564 assert_db_column(res, h, row[h], context)
569 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
570 def check_placex_has_entry(context, table, oid):
571 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
572 nid = NominatimID(oid)
573 where, params = nid.table_select()
574 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
575 assert cur.rowcount == 0
577 @then("search_name has no entry for (?P<oid>.*)")
578 def check_search_name_has_entry(context, oid):
579 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
580 pid = NominatimID(oid).get_place_id(cur)
581 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))
582 assert cur.rowcount == 0