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)
209 context.nominatim.run_update_script('index')
211 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
212 if cur.rowcount == 0:
215 check_database_integrity(context)
217 @when("updating postcodes")
218 def update_postcodes(context):
219 context.nominatim.run_update_script('calculate-postcodes')
221 @when("marking for delete (?P<oids>.*)")
222 def delete_places(context, oids):
223 context.nominatim.run_setup_script(
224 'create-functions', 'create-partition-functions', 'enable-diff-updates')
225 with context.db.cursor() as cur:
226 for oid in oids.split(','):
227 where, params = NominatimID(oid).table_select()
228 cur.execute("DELETE FROM place WHERE " + where, params)
231 context.nominatim.run_update_script('index')
233 with context.db.cursor() as cur:
234 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
235 if cur.rowcount == 0:
238 ################################ THEN ##################################
240 @then("placex contains(?P<exact> exactly)?")
241 def check_placex_contents(context, exact):
242 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
243 expected_content = set()
244 for row in context.table:
245 nid = NominatimID(row['object'])
246 where, params = nid.table_select()
247 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
248 ST_X(centroid) as cx, ST_Y(centroid) as cy
249 FROM placex where %s""" % where,
251 assert cur.rowcount > 0, "No rows found for " + row['object']
255 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
256 for h in row.headings:
257 if h in ('extratags', 'address'):
259 assert res[h] is None
261 vdict = eval('{' + row[h] + '}')
262 assert vdict == res[h]
263 elif h.startswith('name'):
264 name = h[5:] if h.startswith('name+') else 'name'
265 assert name in res['name']
266 assert res['name'][name] == row[h]
267 elif h.startswith('extratags+'):
268 assert res['extratags'][h[10:]] == row[h]
269 elif h.startswith('addr+'):
271 if res['address'] is not None:
272 assert h[5:] not in res['address']
274 assert h[5:] in res['address'], "column " + h
275 assert res['address'][h[5:]] == row[h], "column %s" % h
276 elif h in ('linked_place_id', 'parent_place_id'):
277 compare_place_id(row[h], res[h], h, context)
279 assert_db_column(res, h, row[h], context)
282 cur.execute('SELECT osm_type, osm_id, class from placex')
283 assert expected_content == set([(r[0], r[1], r[2]) for r in cur])
285 @then("place contains(?P<exact> exactly)?")
286 def check_placex_contents(context, exact):
287 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
288 expected_content = set()
289 for row in context.table:
290 nid = NominatimID(row['object'])
291 where, params = nid.table_select()
292 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
293 ST_GeometryType(geometry) as geometrytype
294 FROM place where %s""" % where,
296 assert cur.rowcount > 0, "No rows found for " + row['object']
300 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
301 for h in row.headings:
302 msg = "%s: %s" % (row['object'], h)
303 if h in ('name', 'extratags', 'address'):
305 assert res[h] is None, msg
307 vdict = eval('{' + row[h] + '}')
308 assert vdict == res[h], msg
309 elif h.startswith('name+'):
310 assert res['name'][h[5:]] == row[h], msg
311 elif h.startswith('extratags+'):
312 assert res['extratags'][h[10:]] == row[h], msg
313 elif h.startswith('addr+'):
315 if res['address'] is not None:
316 assert h[5:] not in res['address']
318 assert res['address'][h[5:]] == row[h], msg
319 elif h in ('linked_place_id', 'parent_place_id'):
320 compare_place_id(row[h], res[h], h, context)
322 assert_db_column(res, h, row[h], context)
325 cur.execute('SELECT osm_type, osm_id, class from place')
326 assert expected_content, set([(r[0], r[1], r[2]) for r in cur])
328 @then("search_name contains(?P<exclude> not)?")
329 def check_search_name_contents(context, exclude):
330 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
331 for row in context.table:
332 pid = NominatimID(row['object']).get_place_id(cur)
333 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
334 FROM search_name WHERE place_id = %s""", (pid, ))
335 assert cur.rowcount > 0, "No rows found for " + row['object']
338 for h in row.headings:
339 if h in ('name_vector', 'nameaddress_vector'):
340 terms = [x.strip() for x in row[h].split(',') if not x.strip().startswith('#')]
341 words = [x.strip()[1:] for x in row[h].split(',') if x.strip().startswith('#')]
342 with context.db.cursor() as subcur:
343 subcur.execute(""" SELECT word_id, word_token
344 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
345 WHERE word_token = make_standard_name(t.term)
346 and class is null and country_code is null
349 SELECT word_id, word_token
350 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
351 WHERE word_token = ' ' || make_standard_name(t.term)
352 and class is null and country_code is null
357 assert subcur.rowcount >= len(terms) + len(words), \
358 "No word entry found for " + row[h] + ". Entries found: " + str(subcur.rowcount)
361 assert wid[0] not in res[h], "Found term for %s/%s: %s" % (pid, h, wid[1])
363 assert wid[0] in res[h], "Missing term for %s/%s: %s" % (pid, h, wid[1])
365 assert_db_column(res, h, row[h], context)
367 @then("location_postcode contains exactly")
368 def check_location_postcode(context):
369 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
370 cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
371 assert cur.rowcount == len(list(context.table)), \
372 "Postcode table has %d rows, expected %d rows." % (cur.rowcount, len(list(context.table)))
375 for row in context.table:
376 for i in range(len(table)):
377 if table[i]['country_code'] != row['country'] \
378 or table[i]['postcode'] != row['postcode']:
380 for h in row.headings:
381 if h not in ('country', 'postcode'):
382 assert_db_column(table[i], h, row[h], context)
384 @then("word contains(?P<exclude> not)?")
385 def check_word_table(context, exclude):
386 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
387 for row in context.table:
390 for h in row.headings:
391 wheres.append("%s = %%s" % h)
392 values.append(row[h])
393 cur.execute("SELECT * from word WHERE %s" % ' AND '.join(wheres), values)
395 assert cur.rowcount == 0, "Row still in word table: %s" % '/'.join(values)
397 assert cur.rowcount > 0, "Row not in word table: %s" % '/'.join(values)
399 @then("place_addressline contains")
400 def check_place_addressline(context):
401 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
402 for row in context.table:
403 pid = NominatimID(row['object']).get_place_id(cur)
404 apid = NominatimID(row['address']).get_place_id(cur)
405 cur.execute(""" SELECT * FROM place_addressline
406 WHERE place_id = %s AND address_place_id = %s""",
408 assert cur.rowcount > 0, \
409 "No rows found for place %s and address %s" % (row['object'], row['address'])
412 for h in row.headings:
413 if h not in ('address', 'object'):
414 assert_db_column(res, h, row[h], context)
416 @then("place_addressline doesn't contain")
417 def check_place_addressline_exclude(context):
418 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
419 for row in context.table:
420 pid = NominatimID(row['object']).get_place_id(cur)
421 apid = NominatimID(row['address']).get_place_id(cur)
422 cur.execute(""" SELECT * FROM place_addressline
423 WHERE place_id = %s AND address_place_id = %s""",
425 assert cur.rowcount == 0, \
426 "Row found for place %s and address %s" % (row['object'], row['address'])
428 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
429 def check_location_property_osmline(context, oid, neg):
430 nid = NominatimID(oid)
432 assert 'W' == nid.typ, "interpolation must be a way"
434 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
435 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
436 FROM location_property_osmline
437 WHERE osm_id = %s AND startnumber IS NOT NULL""",
441 assert cur.rowcount == 0
444 todo = list(range(len(list(context.table))))
447 row = context.table[i]
448 if (int(row['start']) == res['startnumber']
449 and int(row['end']) == res['endnumber']):
453 assert False, "Unexpected row %s" % (str(res))
455 for h in row.headings:
456 if h in ('start', 'end'):
458 elif h == 'parent_place_id':
459 compare_place_id(row[h], res[h], h, context)
461 assert_db_column(res, h, row[h], context)
466 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
467 def check_placex_has_entry(context, table, oid):
468 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
469 nid = NominatimID(oid)
470 where, params = nid.table_select()
471 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
472 assert cur.rowcount == 0
474 @then("search_name has no entry for (?P<oid>.*)")
475 def check_search_name_has_entry(context, oid):
476 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
477 pid = NominatimID(oid).get_place_id(cur)
478 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))
479 assert cur.rowcount == 0