4 from check_functions import Almost
5 from place_inserter import PlaceColumn
7 class PlaceObjName(object):
9 def __init__(self, placeid, conn):
20 cur = self.conn.cursor()
21 cur.execute("""SELECT osm_type, osm_id, class
22 FROM placex WHERE place_id = %s""",
24 assert cur.rowcount == 1, "No entry found for place id %s" % self.pid
26 return "%s%s:%s" % cur.fetchone()
28 def compare_place_id(expected, result, column, context):
31 "Bad place id in column {}. Expected: 0, got: {!s}.".format(
32 column, PlaceObjName(result, context.db))
34 assert result is None, \
35 "Bad place id in column {}: {!s}.".format(
36 column, PlaceObjName(result, context.db))
38 assert NominatimID(expected).get_place_id(context.db.cursor()) == result, \
39 "Bad place id in column {}. Expected: {}, got: {!s}.".format(
40 column, expected, PlaceObjName(result, context.db))
42 def check_database_integrity(context):
43 """ Check some generic constraints on the tables.
45 # place_addressline should not have duplicate (place_id, address_place_id)
46 cur = context.db.cursor()
47 cur.execute("""SELECT count(*) FROM
48 (SELECT place_id, address_place_id, count(*) as c
49 FROM place_addressline GROUP BY place_id, address_place_id) x
51 assert cur.fetchone()[0] == 0, "Duplicates found in place_addressline"
55 """ Splits a unique identifier for places into its components.
56 As place_ids cannot be used for testing, we use a unique
57 identifier instead that is of the form <osmtype><osmid>[:<class>].
60 id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
62 def __init__(self, oid):
63 self.typ = self.oid = self.cls = None
66 m = self.id_regex.fullmatch(oid)
67 assert m is not None, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid
69 self.typ = m.group('tp')
70 self.oid = m.group('id')
71 self.cls = m.group('cls')
75 return self.typ + self.oid
77 return '%s%d:%s' % (self.typ, self.oid, self.cls)
79 def table_select(self):
80 """ Return where clause and parameter list to select the object
81 from a Nominatim table.
83 where = 'osm_type = %s and osm_id = %s'
84 params = [self.typ, self. oid]
86 if self.cls is not None:
87 where += ' and class = %s'
88 params.append(self.cls)
92 def get_place_id(self, cur):
93 where, params = self.table_select()
94 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
95 assert cur.rowcount == 1, \
96 "Expected exactly 1 entry in placex for %s found %s" % (str(self), cur.rowcount)
98 return cur.fetchone()[0]
101 def assert_db_column(row, column, value, context):
102 if column == 'object':
105 if column.startswith('centroid'):
106 if value == 'in geometry':
107 query = """SELECT ST_Within(ST_SetSRID(ST_Point({}, {}), 4326),
108 ST_SetSRID('{}'::geometry, 4326))""".format(
109 row['cx'], row['cy'], row['geomtxt'])
110 cur = context.db.cursor()
112 assert cur.fetchone()[0], "(Row %s failed: %s)" % (column, query)
114 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
115 x, y = value.split(' ')
116 assert Almost(float(x) * fac) == row['cx'], "Bad x coordinate"
117 assert Almost(float(y) * fac) == row['cy'], "Bad y coordinate"
118 elif column == 'geometry':
119 geom = context.osm.parse_geometry(value, context.scene)
120 cur = context.db.cursor()
121 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
122 geom, row['geomtxt'],)
124 assert cur.fetchone()[0], "(Row %s failed: %s)" % (column, query)
126 assert row[column] is None, "Row %s" % column
128 assert value == str(row[column]), \
129 "Row '%s': expected: %s, got: %s" % (column, value, str(row[column]))
132 ################################ GIVEN ##################################
134 @given("the (?P<named>named )?places")
135 def add_data_to_place_table(context, named):
136 with context.db.cursor() as cur:
137 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
138 for row in context.table:
139 PlaceColumn(context).add_row(row, named is not None).db_insert(cur)
140 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
142 @given("the relations")
143 def add_data_to_planet_relations(context):
144 with context.db.cursor() as cur:
145 for r in context.table:
151 for m in r['members'].split(','):
154 parts.insert(last_node, int(mid.oid))
158 parts.insert(last_way, int(mid.oid))
161 parts.append(int(mid.oid))
163 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
169 if h.startswith("tags+"):
170 tags.extend((h[5:], r[h]))
172 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
173 VALUES (%s, %s, %s, %s, %s, %s)""",
174 (r['id'], last_node, last_way, parts, members, tags))
177 def add_data_to_planet_ways(context):
178 with context.db.cursor() as cur:
179 for r in context.table:
182 if h.startswith("tags+"):
183 tags.extend((h[5:], r[h]))
185 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
187 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
188 (r['id'], nodes, tags))
190 ################################ WHEN ##################################
193 def import_and_index_data_from_place_table(context):
194 """ Import data previously set up in the place table.
196 context.nominatim.copy_from_place(context.db)
197 context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
198 check_database_integrity(context)
200 @when("updating places")
201 def update_place_table(context):
202 context.nominatim.run_setup_script(
203 'create-functions', 'create-partition-functions', 'enable-diff-updates')
204 with context.db.cursor() as cur:
205 for row in context.table:
206 PlaceColumn(context).add_row(row, False).db_insert(cur)
208 context.nominatim.reindex_placex(context.db)
209 check_database_integrity(context)
211 @when("updating postcodes")
212 def update_postcodes(context):
213 context.nominatim.run_update_script('calculate-postcodes')
215 @when("marking for delete (?P<oids>.*)")
216 def delete_places(context, oids):
217 context.nominatim.run_setup_script(
218 'create-functions', 'create-partition-functions', 'enable-diff-updates')
219 with context.db.cursor() as cur:
220 for oid in oids.split(','):
221 where, params = NominatimID(oid).table_select()
222 cur.execute("DELETE FROM place WHERE " + where, params)
224 context.nominatim.reindex_placex(context.db)
226 ################################ THEN ##################################
228 @then("placex contains(?P<exact> exactly)?")
229 def check_placex_contents(context, exact):
230 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
231 expected_content = set()
232 for row in context.table:
233 nid = NominatimID(row['object'])
234 where, params = nid.table_select()
235 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
236 ST_X(centroid) as cx, ST_Y(centroid) as cy
237 FROM placex where %s""" % where,
239 assert cur.rowcount > 0, "No rows found for " + row['object']
243 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
244 for h in row.headings:
245 if h in ('extratags', 'address'):
247 assert res[h] is None
249 vdict = eval('{' + row[h] + '}')
250 assert vdict == res[h]
251 elif h.startswith('name'):
252 name = h[5:] if h.startswith('name+') else 'name'
253 assert name in res['name']
254 assert res['name'][name] == row[h]
255 elif h.startswith('extratags+'):
256 assert res['extratags'][h[10:]] == row[h]
257 elif h.startswith('addr+'):
259 if res['address'] is not None:
260 assert h[5:] not in res['address']
262 assert h[5:] in res['address'], "column " + h
263 assert res['address'][h[5:]] == row[h], "column %s" % h
264 elif h in ('linked_place_id', 'parent_place_id'):
265 compare_place_id(row[h], res[h], h, context)
267 assert_db_column(res, h, row[h], context)
270 cur.execute('SELECT osm_type, osm_id, class from placex')
271 assert expected_content == set([(r[0], r[1], r[2]) for r in cur])
273 @then("place contains(?P<exact> exactly)?")
274 def check_placex_contents(context, exact):
275 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
276 expected_content = set()
277 for row in context.table:
278 nid = NominatimID(row['object'])
279 where, params = nid.table_select()
280 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
281 ST_GeometryType(geometry) as geometrytype
282 FROM place where %s""" % where,
284 assert cur.rowcount > 0, "No rows found for " + row['object']
288 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
289 for h in row.headings:
290 msg = "%s: %s" % (row['object'], h)
291 if h in ('name', 'extratags', 'address'):
293 assert res[h] is None, msg
295 vdict = eval('{' + row[h] + '}')
296 assert vdict == res[h], msg
297 elif h.startswith('name+'):
298 assert res['name'][h[5:]] == row[h], msg
299 elif h.startswith('extratags+'):
300 assert res['extratags'][h[10:]] == row[h], msg
301 elif h.startswith('addr+'):
303 if res['address'] is not None:
304 assert h[5:] not in res['address']
306 assert res['address'][h[5:]] == row[h], msg
307 elif h in ('linked_place_id', 'parent_place_id'):
308 compare_place_id(row[h], res[h], h, context)
310 assert_db_column(res, h, row[h], context)
313 cur.execute('SELECT osm_type, osm_id, class from place')
314 assert expected_content, set([(r[0], r[1], r[2]) for r in cur])
316 @then("search_name contains(?P<exclude> not)?")
317 def check_search_name_contents(context, exclude):
318 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
319 for row in context.table:
320 pid = NominatimID(row['object']).get_place_id(cur)
321 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
322 FROM search_name WHERE place_id = %s""", (pid, ))
323 assert cur.rowcount > 0, "No rows found for " + row['object']
326 for h in row.headings:
327 if h in ('name_vector', 'nameaddress_vector'):
328 terms = [x.strip() for x in row[h].split(',') if not x.strip().startswith('#')]
329 words = [x.strip()[1:] for x in row[h].split(',') if x.strip().startswith('#')]
330 with context.db.cursor() as subcur:
331 subcur.execute(""" SELECT word_id, word_token
332 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
333 WHERE word_token = make_standard_name(t.term)
334 and class is null and country_code is null
337 SELECT word_id, word_token
338 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
339 WHERE word_token = ' ' || make_standard_name(t.term)
340 and class is null and country_code is null
345 assert subcur.rowcount >= len(terms) + len(words), \
346 "No word entry found for " + row[h] + ". Entries found: " + str(subcur.rowcount)
349 assert wid[0] not in res[h], "Found term for %s/%s: %s" % (pid, h, wid[1])
351 assert wid[0] in res[h], "Missing term for %s/%s: %s" % (pid, h, wid[1])
353 assert_db_column(res, h, row[h], context)
355 @then("location_postcode contains exactly")
356 def check_location_postcode(context):
357 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
358 cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
359 assert cur.rowcount == len(list(context.table)), \
360 "Postcode table has %d rows, expected %d rows." % (cur.rowcount, len(list(context.table)))
363 for row in context.table:
364 for i in range(len(table)):
365 if table[i]['country_code'] != row['country'] \
366 or table[i]['postcode'] != row['postcode']:
368 for h in row.headings:
369 if h not in ('country', 'postcode'):
370 assert_db_column(table[i], h, row[h], context)
372 @then("word contains(?P<exclude> not)?")
373 def check_word_table(context, exclude):
374 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
375 for row in context.table:
378 for h in row.headings:
379 wheres.append("%s = %%s" % h)
380 values.append(row[h])
381 cur.execute("SELECT * from word WHERE %s" % ' AND '.join(wheres), values)
383 assert cur.rowcount == 0, "Row still in word table: %s" % '/'.join(values)
385 assert cur.rowcount > 0, "Row not in word table: %s" % '/'.join(values)
387 @then("place_addressline contains")
388 def check_place_addressline(context):
389 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
390 for row in context.table:
391 pid = NominatimID(row['object']).get_place_id(cur)
392 apid = NominatimID(row['address']).get_place_id(cur)
393 cur.execute(""" SELECT * FROM place_addressline
394 WHERE place_id = %s AND address_place_id = %s""",
396 assert cur.rowcount > 0, \
397 "No rows found for place %s and address %s" % (row['object'], row['address'])
400 for h in row.headings:
401 if h not in ('address', 'object'):
402 assert_db_column(res, h, row[h], context)
404 @then("place_addressline doesn't contain")
405 def check_place_addressline_exclude(context):
406 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
407 for row in context.table:
408 pid = NominatimID(row['object']).get_place_id(cur)
409 apid = NominatimID(row['address']).get_place_id(cur)
410 cur.execute(""" SELECT * FROM place_addressline
411 WHERE place_id = %s AND address_place_id = %s""",
413 assert cur.rowcount == 0, \
414 "Row found for place %s and address %s" % (row['object'], row['address'])
416 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
417 def check_location_property_osmline(context, oid, neg):
418 nid = NominatimID(oid)
420 assert 'W' == nid.typ, "interpolation must be a way"
422 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
423 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
424 FROM location_property_osmline
425 WHERE osm_id = %s AND startnumber IS NOT NULL""",
429 assert cur.rowcount == 0
432 todo = list(range(len(list(context.table))))
435 row = context.table[i]
436 if (int(row['start']) == res['startnumber']
437 and int(row['end']) == res['endnumber']):
441 assert False, "Unexpected row %s" % (str(res))
443 for h in row.headings:
444 if h in ('start', 'end'):
446 elif h == 'parent_place_id':
447 compare_place_id(row[h], res[h], h, context)
449 assert_db_column(res, h, row[h], context)
454 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
455 def check_placex_has_entry(context, table, oid):
456 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
457 nid = NominatimID(oid)
458 where, params = nid.table_select()
459 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
460 assert cur.rowcount == 0
462 @then("search_name has no entry for (?P<oid>.*)")
463 def check_search_name_has_entry(context, oid):
464 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
465 pid = NominatimID(oid).get_place_id(cur)
466 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))
467 assert cur.rowcount == 0