5 from nose.tools import * # for assert functions
10 def __init__(self, context, force_name):
11 self.columns = { 'admin_level' : 15}
12 self.force_name = force_name
13 self.context = context
16 def add(self, key, value):
17 if hasattr(self, 'set_key_' + key):
18 getattr(self, 'set_key_' + key)(value)
19 elif key.startswith('name+'):
20 self.add_hstore('name', key[5:], value)
21 elif key.startswith('extra+'):
22 self.add_hstore('extratags', key[6:], value)
23 elif key.startswith('addr+'):
24 self.add_hstore('address', key[5:], value)
25 elif key in ('name', 'address', 'extratags'):
26 self.columns[key] = eval('{' + value + '}')
28 assert_in(key, ('class', 'type'))
29 self.columns[key] = None if value == '' else value
31 def set_key_name(self, value):
32 self.add_hstore('name', 'name', value)
34 def set_key_osm(self, value):
35 assert_in(value[0], 'NRW')
36 ok_(value[1:].isdigit())
38 self.columns['osm_type'] = value[0]
39 self.columns['osm_id'] = int(value[1:])
41 def set_key_admin(self, value):
42 self.columns['admin_level'] = int(value)
44 def set_key_housenr(self, value):
46 self.add_hstore('address', 'housenumber', value)
48 def set_key_postcode(self, value):
50 self.add_hstore('address', 'postcode', value)
52 def set_key_street(self, value):
54 self.add_hstore('address', 'street', value)
56 def set_key_addr_place(self, value):
58 self.add_hstore('address', 'place', value)
60 def set_key_country(self, value):
62 self.add_hstore('address', 'country', value)
64 def set_key_geometry(self, value):
65 self.geometry = self.context.osm.parse_geometry(value, self.context.scene)
66 assert_is_not_none(self.geometry)
68 def add_hstore(self, column, key, value):
69 if column in self.columns:
70 self.columns[column][key] = value
72 self.columns[column] = { key : value }
74 def db_insert(self, cursor):
75 assert_in('osm_type', self.columns)
76 if self.force_name and 'name' not in self.columns:
77 self.add_hstore('name', 'name', ''.join(random.choice(string.printable)
78 for _ in range(int(random.random()*30))))
80 if self.columns['osm_type'] == 'N' and self.geometry is None:
81 pt = self.context.osm.grid_node(self.columns['osm_id'])
83 pt = (random.random()*360 - 180, random.random()*180 - 90)
85 self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % pt
87 assert_is_not_none(self.geometry, "Geometry missing")
88 query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
89 ','.join(self.columns.keys()),
90 ','.join(['%s' for x in range(len(self.columns))]),
92 cursor.execute(query, list(self.columns.values()))
94 class LazyFmt(object):
96 def __init__(self, fmtstr, *args):
101 return self.fmt % self.args
103 class PlaceObjName(object):
105 def __init__(self, placeid, conn):
113 cur = self.conn.cursor()
114 cur.execute("""SELECT osm_type, osm_id, class
115 FROM placex WHERE place_id = %s""",
117 eq_(1, cur.rowcount, "No entry found for place id %s" % self.pid)
119 return "%s%s:%s" % cur.fetchone()
121 def compare_place_id(expected, result, column, context):
124 LazyFmt("Bad place id in column %s. Expected: 0, got: %s.",
125 column, PlaceObjName(result, context.db)))
126 elif expected == '-':
127 assert_is_none(result,
128 LazyFmt("bad place id in column %s: %s.",
129 column, PlaceObjName(result, context.db)))
131 eq_(NominatimID(expected).get_place_id(context.db.cursor()), result,
132 LazyFmt("Bad place id in column %s. Expected: %s, got: %s.",
133 column, expected, PlaceObjName(result, context.db)))
135 def check_database_integrity(context):
136 """ Check some generic constraints on the tables.
138 # place_addressline should not have duplicate (place_id, address_place_id)
139 cur = context.db.cursor()
140 cur.execute("""SELECT count(*) FROM
141 (SELECT place_id, address_place_id, count(*) as c
142 FROM place_addressline GROUP BY place_id, address_place_id) x
144 eq_(0, cur.fetchone()[0], "Duplicates found in place_addressline")
148 """ Splits a unique identifier for places into its components.
149 As place_ids cannot be used for testing, we use a unique
150 identifier instead that is of the form <osmtype><osmid>[:<class>].
153 id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
155 def __init__(self, oid):
156 self.typ = self.oid = self.cls = None
159 m = self.id_regex.fullmatch(oid)
160 assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
162 self.typ = m.group('tp')
163 self.oid = m.group('id')
164 self.cls = m.group('cls')
168 return self.typ + self.oid
170 return '%s%d:%s' % (self.typ, self.oid, self.cls)
172 def table_select(self):
173 """ Return where clause and parameter list to select the object
174 from a Nominatim table.
176 where = 'osm_type = %s and osm_id = %s'
177 params = [self.typ, self. oid]
179 if self.cls is not None:
180 where += ' and class = %s'
181 params.append(self.cls)
185 def get_place_id(self, cur):
186 where, params = self.table_select()
187 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
189 "Expected exactly 1 entry in placex for %s found %s"
190 % (str(self), cur.rowcount))
192 return cur.fetchone()[0]
195 def assert_db_column(row, column, value, context):
196 if column == 'object':
199 if column.startswith('centroid'):
200 if value == 'in geometry':
201 query = """SELECT ST_Within(ST_SetSRID(ST_Point({}, {}), 4326),
202 ST_SetSRID('{}'::geometry, 4326))""".format(
203 row['cx'], row['cy'], row['geomtxt'])
204 cur = context.db.cursor()
206 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
208 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
209 x, y = value.split(' ')
210 assert_almost_equal(float(x) * fac, row['cx'], msg="Bad x coordinate")
211 assert_almost_equal(float(y) * fac, row['cy'], msg="Bad y coordinate")
212 elif column == 'geometry':
213 geom = context.osm.parse_geometry(value, context.scene)
214 cur = context.db.cursor()
215 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
216 geom, row['geomtxt'],)
218 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
220 assert_is_none(row[column], "Row %s" % column)
222 eq_(value, str(row[column]),
223 "Row '%s': expected: %s, got: %s"
224 % (column, value, str(row[column])))
227 ################################ STEPS ##################################
229 @given(u'the scene (?P<scene>.+)')
230 def set_default_scene(context, scene):
231 context.scene = scene
233 @given("the (?P<named>named )?places")
234 def add_data_to_place_table(context, named):
235 cur = context.db.cursor()
236 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
237 for r in context.table:
238 col = PlaceColumn(context, named is not None)
244 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
248 @given("the relations")
249 def add_data_to_planet_relations(context):
250 cur = context.db.cursor()
251 for r in context.table:
257 for m in r['members'].split(','):
260 parts.insert(last_node, int(mid.oid))
264 parts.insert(last_way, int(mid.oid))
267 parts.append(int(mid.oid))
269 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
275 if h.startswith("tags+"):
276 tags.extend((h[5:], r[h]))
278 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
279 VALUES (%s, %s, %s, %s, %s, %s)""",
280 (r['id'], last_node, last_way, parts, members, tags))
284 def add_data_to_planet_ways(context):
285 cur = context.db.cursor()
286 for r in context.table:
289 if h.startswith("tags+"):
290 tags.extend((h[5:], r[h]))
292 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
294 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
295 (r['id'], nodes, tags))
299 def import_and_index_data_from_place_table(context):
300 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
301 cur = context.db.cursor()
303 """insert into placex (osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry)
304 select osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry
305 from place where not (class='place' and type='houses' and osm_type='W')""")
307 """insert into location_property_osmline (osm_id, address, linegeo)
308 SELECT osm_id, address, geometry from place
309 WHERE class='place' and type='houses' and osm_type='W'
310 and ST_GeometryType(geometry) = 'ST_LineString'""")
312 context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
313 check_database_integrity(context)
315 @when("updating places")
316 def update_place_table(context):
317 context.nominatim.run_setup_script(
318 'create-functions', 'create-partition-functions', 'enable-diff-updates')
319 cur = context.db.cursor()
320 for r in context.table:
321 col = PlaceColumn(context, False)
331 context.nominatim.run_update_script('index')
333 cur = context.db.cursor()
334 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
335 if cur.rowcount == 0:
338 check_database_integrity(context)
340 @when("updating postcodes")
341 def update_postcodes(context):
342 context.nominatim.run_update_script('calculate-postcodes')
344 @when("marking for delete (?P<oids>.*)")
345 def delete_places(context, oids):
346 context.nominatim.run_setup_script(
347 'create-functions', 'create-partition-functions', 'enable-diff-updates')
348 cur = context.db.cursor()
349 for oid in oids.split(','):
350 where, params = NominatimID(oid).table_select()
351 cur.execute("DELETE FROM place WHERE " + where, params)
355 context.nominatim.run_update_script('index')
357 cur = context.db.cursor()
358 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
359 if cur.rowcount == 0:
362 @then("placex contains(?P<exact> exactly)?")
363 def check_placex_contents(context, exact):
364 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
366 expected_content = set()
367 for row in context.table:
368 nid = NominatimID(row['object'])
369 where, params = nid.table_select()
370 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
371 ST_X(centroid) as cx, ST_Y(centroid) as cy
372 FROM placex where %s""" % where,
374 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
378 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
379 for h in row.headings:
380 if h in ('extratags', 'address'):
382 assert_is_none(res[h])
384 vdict = eval('{' + row[h] + '}')
385 assert_equals(vdict, res[h])
386 elif h.startswith('name'):
387 name = h[5:] if h.startswith('name+') else 'name'
388 assert_in(name, res['name'])
389 eq_(res['name'][name], row[h])
390 elif h.startswith('extratags+'):
391 eq_(res['extratags'][h[10:]], row[h])
392 elif h.startswith('addr+'):
394 if res['address'] is not None:
395 assert_not_in(h[5:], res['address'])
397 assert_in(h[5:], res['address'], "column " + h)
398 assert_equals(res['address'][h[5:]], row[h],
400 elif h in ('linked_place_id', 'parent_place_id'):
401 compare_place_id(row[h], res[h], h, context)
403 assert_db_column(res, h, row[h], context)
406 cur.execute('SELECT osm_type, osm_id, class from placex')
407 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
411 @then("place contains(?P<exact> exactly)?")
412 def check_placex_contents(context, exact):
413 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
415 expected_content = set()
416 for row in context.table:
417 nid = NominatimID(row['object'])
418 where, params = nid.table_select()
419 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
420 ST_GeometryType(geometry) as geometrytype
421 FROM place where %s""" % where,
423 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
427 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
428 for h in row.headings:
429 msg = "%s: %s" % (row['object'], h)
430 if h in ('name', 'extratags', 'address'):
432 assert_is_none(res[h], msg)
434 vdict = eval('{' + row[h] + '}')
435 assert_equals(vdict, res[h], msg)
436 elif h.startswith('name+'):
437 assert_equals(res['name'][h[5:]], row[h], msg)
438 elif h.startswith('extratags+'):
439 assert_equals(res['extratags'][h[10:]], row[h], msg)
440 elif h.startswith('addr+'):
442 if res['address'] is not None:
443 assert_not_in(h[5:], res['address'])
445 assert_equals(res['address'][h[5:]], row[h], msg)
446 elif h in ('linked_place_id', 'parent_place_id'):
447 compare_place_id(row[h], res[h], h, context)
449 assert_db_column(res, h, row[h], context)
452 cur.execute('SELECT osm_type, osm_id, class from place')
453 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
457 @then("search_name contains(?P<exclude> not)?")
458 def check_search_name_contents(context, exclude):
459 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
461 for row in context.table:
462 pid = NominatimID(row['object']).get_place_id(cur)
463 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
464 FROM search_name WHERE place_id = %s""", (pid, ))
465 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
468 for h in row.headings:
469 if h in ('name_vector', 'nameaddress_vector'):
470 terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
471 subcur = context.db.cursor()
472 subcur.execute("""SELECT word_id, word_token
473 FROM word, (SELECT unnest(%s) as term) t
474 WHERE word_token = make_standard_name(t.term)""",
477 ok_(subcur.rowcount >= len(terms),
478 "No word entry found for " + row[h])
481 assert_not_in(wid[0], res[h],
482 "Found term for %s/%s: %s" % (pid, h, wid[1]))
484 assert_in(wid[0], res[h],
485 "Missing term for %s/%s: %s" % (pid, h, wid[1]))
487 assert_db_column(res, h, row[h], context)
492 @then("location_postcode contains exactly")
493 def check_location_postcode(context):
494 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
496 cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
497 eq_(cur.rowcount, len(list(context.table)),
498 "Postcode table has %d rows, expected %d rows."
499 % (cur.rowcount, len(list(context.table))))
502 for row in context.table:
503 for i in range(len(table)):
504 if table[i]['country_code'] != row['country'] \
505 or table[i]['postcode'] != row['postcode']:
507 for h in row.headings:
508 if h not in ('country', 'postcode'):
509 assert_db_column(table[i], h, row[h], context)
511 @then("word contains(?P<exclude> not)?")
512 def check_word_table(context, exclude):
513 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
515 for row in context.table:
518 for h in row.headings:
519 wheres.append("%s = %%s" % h)
520 values.append(row[h])
521 cur.execute("SELECT * from word WHERE %s" % ' AND '.join(wheres), values)
524 "Row still in word table: %s" % '/'.join(values))
526 assert_greater(cur.rowcount, 0,
527 "Row not in word table: %s" % '/'.join(values))
529 @then("place_addressline contains")
530 def check_place_addressline(context):
531 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
533 for row in context.table:
534 pid = NominatimID(row['object']).get_place_id(cur)
535 apid = NominatimID(row['address']).get_place_id(cur)
536 cur.execute(""" SELECT * FROM place_addressline
537 WHERE place_id = %s AND address_place_id = %s""",
539 assert_less(0, cur.rowcount,
540 "No rows found for place %s and address %s"
541 % (row['object'], row['address']))
544 for h in row.headings:
545 if h not in ('address', 'object'):
546 assert_db_column(res, h, row[h], context)
550 @then("place_addressline doesn't contain")
551 def check_place_addressline_exclude(context):
552 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
554 for row in context.table:
555 pid = NominatimID(row['object']).get_place_id(cur)
556 apid = NominatimID(row['address']).get_place_id(cur)
557 cur.execute(""" SELECT * FROM place_addressline
558 WHERE place_id = %s AND address_place_id = %s""",
561 "Row found for place %s and address %s" % (row['object'], row['address']))
565 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
566 def check_location_property_osmline(context, oid, neg):
567 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
568 nid = NominatimID(oid)
570 eq_('W', nid.typ, "interpolation must be a way")
572 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
573 FROM location_property_osmline
574 WHERE osm_id = %s AND startnumber IS NOT NULL""",
581 todo = list(range(len(list(context.table))))
584 row = context.table[i]
585 if (int(row['start']) == res['startnumber']
586 and int(row['end']) == res['endnumber']):
590 assert False, "Unexpected row %s" % (str(res))
592 for h in row.headings:
593 if h in ('start', 'end'):
595 elif h == 'parent_place_id':
596 compare_place_id(row[h], res[h], h, context)
598 assert_db_column(res, h, row[h], context)
603 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
604 def check_placex_has_entry(context, table, oid):
605 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
606 nid = NominatimID(oid)
607 where, params = nid.table_select()
608 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
612 @then("search_name has no entry for (?P<oid>.*)")
613 def check_search_name_has_entry(context, oid):
614 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
615 pid = NominatimID(oid).get_place_id(cur)
616 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))