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 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
201 x, y = value.split(' ')
202 assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
203 assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
204 elif column == 'geometry':
205 geom = context.osm.parse_geometry(value, context.scene)
206 cur = context.db.cursor()
207 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
208 geom, row['geomtxt'],)
210 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
212 assert_is_none(row[column], "Row %s" % column)
214 eq_(value, str(row[column]),
215 "Row '%s': expected: %s, got: %s"
216 % (column, value, str(row[column])))
219 ################################ STEPS ##################################
221 @given(u'the scene (?P<scene>.+)')
222 def set_default_scene(context, scene):
223 context.scene = scene
225 @given("the (?P<named>named )?places")
226 def add_data_to_place_table(context, named):
227 cur = context.db.cursor()
228 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
229 for r in context.table:
230 col = PlaceColumn(context, named is not None)
236 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
240 @given("the relations")
241 def add_data_to_planet_relations(context):
242 cur = context.db.cursor()
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))
276 def add_data_to_planet_ways(context):
277 cur = context.db.cursor()
278 for r in context.table:
281 if h.startswith("tags+"):
282 tags.extend((h[5:], r[h]))
284 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
286 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
287 (r['id'], nodes, tags))
291 def import_and_index_data_from_place_table(context):
292 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
293 cur = context.db.cursor()
295 """insert into placex (osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry)
296 select osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry
297 from place where not (class='place' and type='houses' and osm_type='W')""")
299 """insert into location_property_osmline (osm_id, address, linegeo)
300 SELECT osm_id, address, geometry from place
301 WHERE class='place' and type='houses' and osm_type='W'
302 and ST_GeometryType(geometry) = 'ST_LineString'""")
304 context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
305 check_database_integrity(context)
307 @when("updating places")
308 def update_place_table(context):
309 context.nominatim.run_setup_script(
310 'create-functions', 'create-partition-functions', 'enable-diff-updates')
311 cur = context.db.cursor()
312 for r in context.table:
313 col = PlaceColumn(context, False)
323 context.nominatim.run_update_script('index')
325 cur = context.db.cursor()
326 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
327 if cur.rowcount == 0:
330 check_database_integrity(context)
332 @when("marking for delete (?P<oids>.*)")
333 def delete_places(context, oids):
334 context.nominatim.run_setup_script(
335 'create-functions', 'create-partition-functions', 'enable-diff-updates')
336 cur = context.db.cursor()
337 for oid in oids.split(','):
338 where, params = NominatimID(oid).table_select()
339 cur.execute("DELETE FROM place WHERE " + where, params)
343 context.nominatim.run_update_script('index')
345 cur = context.db.cursor()
346 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
347 if cur.rowcount == 0:
350 @then("placex contains(?P<exact> exactly)?")
351 def check_placex_contents(context, exact):
352 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
354 expected_content = set()
355 for row in context.table:
356 nid = NominatimID(row['object'])
357 where, params = nid.table_select()
358 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
359 ST_X(centroid) as cx, ST_Y(centroid) as cy
360 FROM placex where %s""" % where,
362 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
366 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
367 for h in row.headings:
368 if h in ('extratags', 'address'):
370 assert_is_none(res[h])
372 vdict = eval('{' + row[h] + '}')
373 assert_equals(vdict, res[h])
374 elif h.startswith('name'):
375 name = h[5:] if h.startswith('name+') else 'name'
376 assert_in(name, res['name'])
377 eq_(res['name'][name], row[h])
378 elif h.startswith('extratags+'):
379 eq_(res['extratags'][h[10:]], row[h])
380 elif h.startswith('addr+'):
382 if res['address'] is not None:
383 assert_not_in(h[5:], res['address'])
385 assert_in(h[5:], res['address'], "column " + h)
386 assert_equals(res['address'][h[5:]], row[h],
388 elif h in ('linked_place_id', 'parent_place_id'):
389 compare_place_id(row[h], res[h], h, context)
391 assert_db_column(res, h, row[h], context)
394 cur.execute('SELECT osm_type, osm_id, class from placex')
395 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
399 @then("place contains(?P<exact> exactly)?")
400 def check_placex_contents(context, exact):
401 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
403 expected_content = set()
404 for row in context.table:
405 nid = NominatimID(row['object'])
406 where, params = nid.table_select()
407 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
408 ST_GeometryType(geometry) as geometrytype
409 FROM place where %s""" % where,
411 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
415 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
416 for h in row.headings:
417 msg = "%s: %s" % (row['object'], h)
418 if h in ('name', 'extratags', 'address'):
420 assert_is_none(res[h], msg)
422 vdict = eval('{' + row[h] + '}')
423 assert_equals(vdict, res[h], msg)
424 elif h.startswith('name+'):
425 assert_equals(res['name'][h[5:]], row[h], msg)
426 elif h.startswith('extratags+'):
427 assert_equals(res['extratags'][h[10:]], row[h], msg)
428 elif h.startswith('addr+'):
430 if res['address'] is not None:
431 assert_not_in(h[5:], res['address'])
433 assert_equals(res['address'][h[5:]], row[h], msg)
434 elif h in ('linked_place_id', 'parent_place_id'):
435 compare_place_id(row[h], res[h], h, context)
437 assert_db_column(res, h, row[h], context)
440 cur.execute('SELECT osm_type, osm_id, class from place')
441 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
445 @then("search_name contains(?P<exclude> not)?")
446 def check_search_name_contents(context, exclude):
447 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
449 for row in context.table:
450 pid = NominatimID(row['object']).get_place_id(cur)
451 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
452 FROM search_name WHERE place_id = %s""", (pid, ))
453 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
456 for h in row.headings:
457 if h in ('name_vector', 'nameaddress_vector'):
458 terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
459 subcur = context.db.cursor()
460 subcur.execute("""SELECT word_id, word_token
461 FROM word, (SELECT unnest(%s) as term) t
462 WHERE word_token = make_standard_name(t.term)""",
465 ok_(subcur.rowcount >= len(terms),
466 "No word entry found for " + row[h])
469 assert_not_in(wid[0], res[h],
470 "Found term for %s/%s: %s" % (pid, h, wid[1]))
472 assert_in(wid[0], res[h],
473 "Missing term for %s/%s: %s" % (pid, h, wid[1]))
475 assert_db_column(res, h, row[h], context)
480 @then("place_addressline contains")
481 def check_place_addressline(context):
482 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
484 for row in context.table:
485 pid = NominatimID(row['object']).get_place_id(cur)
486 apid = NominatimID(row['address']).get_place_id(cur)
487 cur.execute(""" SELECT * FROM place_addressline
488 WHERE place_id = %s AND address_place_id = %s""",
490 assert_less(0, cur.rowcount,
491 "No rows found for place %s and address %s"
492 % (row['object'], row['address']))
495 for h in row.headings:
496 if h not in ('address', 'object'):
497 assert_db_column(res, h, row[h], context)
501 @then("place_addressline doesn't contain")
502 def check_place_addressline_exclude(context):
503 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
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""",
512 "Row found for place %s and address %s" % (row['object'], row['address']))
516 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
517 def check_location_property_osmline(context, oid, neg):
518 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
519 nid = NominatimID(oid)
521 eq_('W', nid.typ, "interpolation must be a way")
523 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
524 FROM location_property_osmline
525 WHERE osm_id = %s AND startnumber IS NOT NULL""",
532 todo = list(range(len(list(context.table))))
535 row = context.table[i]
536 if (int(row['start']) == res['startnumber']
537 and int(row['end']) == res['endnumber']):
541 assert False, "Unexpected row %s" % (str(res))
543 for h in row.headings:
544 if h in ('start', 'end'):
546 elif h == 'parent_place_id':
547 compare_place_id(row[h], res[h], h, context)
549 assert_db_column(res, h, row[h], context)
554 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
555 def check_placex_has_entry(context, table, oid):
556 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
557 nid = NominatimID(oid)
558 where, params = nid.table_select()
559 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
563 @then("search_name has no entry for (?P<oid>.*)")
564 def check_search_name_has_entry(context, oid):
565 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
566 pid = NominatimID(oid).get_place_id(cur)
567 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))