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("the (?P<named>named )?places")
224 def add_data_to_place_table(context, named):
225 with context.db.cursor() as cur:
226 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
227 for r in context.table:
228 col = PlaceColumn(context, named is not None)
234 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
236 @given("the relations")
237 def add_data_to_planet_relations(context):
238 with context.db.cursor() as cur:
239 for r in context.table:
245 for m in r['members'].split(','):
248 parts.insert(last_node, int(mid.oid))
252 parts.insert(last_way, int(mid.oid))
255 parts.append(int(mid.oid))
257 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
263 if h.startswith("tags+"):
264 tags.extend((h[5:], r[h]))
266 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
267 VALUES (%s, %s, %s, %s, %s, %s)""",
268 (r['id'], last_node, last_way, parts, members, tags))
271 def add_data_to_planet_ways(context):
272 with context.db.cursor() as cur:
273 for r in context.table:
276 if h.startswith("tags+"):
277 tags.extend((h[5:], r[h]))
279 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
281 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
282 (r['id'], nodes, tags))
284 ################################ WHEN ##################################
287 def import_and_index_data_from_place_table(context):
288 """ Import data previously set up in the place table.
290 context.nominatim.copy_from_place(context.db)
291 context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
292 check_database_integrity(context)
294 @when("updating places")
295 def update_place_table(context):
296 context.nominatim.run_setup_script(
297 'create-functions', 'create-partition-functions', 'enable-diff-updates')
298 with context.db.cursor() as cur:
299 for r in context.table:
300 col = PlaceColumn(context, False)
308 context.nominatim.run_update_script('index')
310 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
311 if cur.rowcount == 0:
314 check_database_integrity(context)
316 @when("updating postcodes")
317 def update_postcodes(context):
318 context.nominatim.run_update_script('calculate-postcodes')
320 @when("marking for delete (?P<oids>.*)")
321 def delete_places(context, oids):
322 context.nominatim.run_setup_script(
323 'create-functions', 'create-partition-functions', 'enable-diff-updates')
324 with context.db.cursor() as cur:
325 for oid in oids.split(','):
326 where, params = NominatimID(oid).table_select()
327 cur.execute("DELETE FROM place WHERE " + where, params)
330 context.nominatim.run_update_script('index')
332 with context.db.cursor() as cur:
333 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
334 if cur.rowcount == 0:
337 ################################ THEN ##################################
339 @then("placex contains(?P<exact> exactly)?")
340 def check_placex_contents(context, exact):
341 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
342 expected_content = set()
343 for row in context.table:
344 nid = NominatimID(row['object'])
345 where, params = nid.table_select()
346 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
347 ST_X(centroid) as cx, ST_Y(centroid) as cy
348 FROM placex where %s""" % where,
350 assert cur.rowcount > 0, "No rows found for " + row['object']
354 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
355 for h in row.headings:
356 if h in ('extratags', 'address'):
358 assert res[h] is None
360 vdict = eval('{' + row[h] + '}')
361 assert vdict == res[h]
362 elif h.startswith('name'):
363 name = h[5:] if h.startswith('name+') else 'name'
364 assert name in res['name']
365 assert res['name'][name] == row[h]
366 elif h.startswith('extratags+'):
367 assert res['extratags'][h[10:]] == row[h]
368 elif h.startswith('addr+'):
370 if res['address'] is not None:
371 assert h[5:] not in res['address']
373 assert h[5:] in res['address'], "column " + h
374 assert res['address'][h[5:]] == row[h], "column %s" % h
375 elif h in ('linked_place_id', 'parent_place_id'):
376 compare_place_id(row[h], res[h], h, context)
378 assert_db_column(res, h, row[h], context)
381 cur.execute('SELECT osm_type, osm_id, class from placex')
382 assert expected_content == set([(r[0], r[1], r[2]) for r in cur])
384 @then("place contains(?P<exact> exactly)?")
385 def check_placex_contents(context, exact):
386 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
387 expected_content = set()
388 for row in context.table:
389 nid = NominatimID(row['object'])
390 where, params = nid.table_select()
391 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
392 ST_GeometryType(geometry) as geometrytype
393 FROM place where %s""" % where,
395 assert cur.rowcount > 0, "No rows found for " + row['object']
399 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
400 for h in row.headings:
401 msg = "%s: %s" % (row['object'], h)
402 if h in ('name', 'extratags', 'address'):
404 assert res[h] is None, msg
406 vdict = eval('{' + row[h] + '}')
407 assert vdict == res[h], msg
408 elif h.startswith('name+'):
409 assert res['name'][h[5:]] == row[h], msg
410 elif h.startswith('extratags+'):
411 assert res['extratags'][h[10:]] == row[h], msg
412 elif h.startswith('addr+'):
414 if res['address'] is not None:
415 assert h[5:] not in res['address']
417 assert res['address'][h[5:]] == row[h], msg
418 elif h in ('linked_place_id', 'parent_place_id'):
419 compare_place_id(row[h], res[h], h, context)
421 assert_db_column(res, h, row[h], context)
424 cur.execute('SELECT osm_type, osm_id, class from place')
425 assert expected_content, set([(r[0], r[1], r[2]) for r in cur])
427 @then("search_name contains(?P<exclude> not)?")
428 def check_search_name_contents(context, exclude):
429 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
430 for row in context.table:
431 pid = NominatimID(row['object']).get_place_id(cur)
432 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
433 FROM search_name WHERE place_id = %s""", (pid, ))
434 assert cur.rowcount > 0, "No rows found for " + row['object']
437 for h in row.headings:
438 if h in ('name_vector', 'nameaddress_vector'):
439 terms = [x.strip() for x in row[h].split(',') if not x.strip().startswith('#')]
440 words = [x.strip()[1:] for x in row[h].split(',') if x.strip().startswith('#')]
441 with context.db.cursor() as subcur:
442 subcur.execute(""" SELECT word_id, word_token
443 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
444 WHERE word_token = make_standard_name(t.term)
445 and class is null and country_code is null
448 SELECT word_id, word_token
449 FROM word, (SELECT unnest(%s::TEXT[]) as term) t
450 WHERE word_token = ' ' || make_standard_name(t.term)
451 and class is null and country_code is null
456 assert subcur.rowcount >= len(terms) + len(words), \
457 "No word entry found for " + row[h] + ". Entries found: " + str(subcur.rowcount)
460 assert wid[0] not in res[h], "Found term for %s/%s: %s" % (pid, h, wid[1])
462 assert wid[0] in res[h], "Missing term for %s/%s: %s" % (pid, h, wid[1])
464 assert_db_column(res, h, row[h], context)
466 @then("location_postcode contains exactly")
467 def check_location_postcode(context):
468 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
469 cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
470 assert cur.rowcount == len(list(context.table)), \
471 "Postcode table has %d rows, expected %d rows." % (cur.rowcount, len(list(context.table)))
474 for row in context.table:
475 for i in range(len(table)):
476 if table[i]['country_code'] != row['country'] \
477 or table[i]['postcode'] != row['postcode']:
479 for h in row.headings:
480 if h not in ('country', 'postcode'):
481 assert_db_column(table[i], h, row[h], context)
483 @then("word contains(?P<exclude> not)?")
484 def check_word_table(context, exclude):
485 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
486 for row in context.table:
489 for h in row.headings:
490 wheres.append("%s = %%s" % h)
491 values.append(row[h])
492 cur.execute("SELECT * from word WHERE %s" % ' AND '.join(wheres), values)
494 assert cur.rowcount == 0, "Row still in word table: %s" % '/'.join(values)
496 assert cur.rowcount > 0, "Row not in word table: %s" % '/'.join(values)
498 @then("place_addressline contains")
499 def check_place_addressline(context):
500 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
501 for row in context.table:
502 pid = NominatimID(row['object']).get_place_id(cur)
503 apid = NominatimID(row['address']).get_place_id(cur)
504 cur.execute(""" SELECT * FROM place_addressline
505 WHERE place_id = %s AND address_place_id = %s""",
507 assert cur.rowcount > 0, \
508 "No rows found for place %s and address %s" % (row['object'], row['address'])
511 for h in row.headings:
512 if h not in ('address', 'object'):
513 assert_db_column(res, h, row[h], context)
515 @then("place_addressline doesn't contain")
516 def check_place_addressline_exclude(context):
517 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
518 for row in context.table:
519 pid = NominatimID(row['object']).get_place_id(cur)
520 apid = NominatimID(row['address']).get_place_id(cur)
521 cur.execute(""" SELECT * FROM place_addressline
522 WHERE place_id = %s AND address_place_id = %s""",
524 assert cur.rowcount == 0, \
525 "Row found for place %s and address %s" % (row['object'], row['address'])
527 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
528 def check_location_property_osmline(context, oid, neg):
529 nid = NominatimID(oid)
531 assert 'W' == nid.typ, "interpolation must be a way"
533 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
534 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
535 FROM location_property_osmline
536 WHERE osm_id = %s AND startnumber IS NOT NULL""",
540 assert cur.rowcount == 0
543 todo = list(range(len(list(context.table))))
546 row = context.table[i]
547 if (int(row['start']) == res['startnumber']
548 and int(row['end']) == res['endnumber']):
552 assert False, "Unexpected row %s" % (str(res))
554 for h in row.headings:
555 if h in ('start', 'end'):
557 elif h == 'parent_place_id':
558 compare_place_id(row[h], res[h], h, context)
560 assert_db_column(res, h, row[h], context)
565 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
566 def check_placex_has_entry(context, table, oid):
567 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
568 nid = NominatimID(oid)
569 where, params = nid.table_select()
570 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
571 assert cur.rowcount == 0
573 @then("search_name has no entry for (?P<oid>.*)")
574 def check_search_name_has_entry(context, oid):
575 with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
576 pid = NominatimID(oid).get_place_id(cur)
577 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))
578 assert cur.rowcount == 0