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)
26 assert_in(key, ('class', 'type'))
27 self.columns[key] = None if value == '' else value
29 def set_key_name(self, value):
30 self.add_hstore('name', 'name', value)
32 def set_key_osm(self, value):
33 assert_in(value[0], 'NRW')
34 ok_(value[1:].isdigit())
36 self.columns['osm_type'] = value[0]
37 self.columns['osm_id'] = int(value[1:])
39 def set_key_admin(self, value):
40 self.columns['admin_level'] = int(value)
42 def set_key_housenr(self, value):
44 self.add_hstore('address', 'housenumber', value)
46 def set_key_postcode(self, value):
48 self.add_hstore('address', 'postcode', value)
50 def set_key_street(self, value):
52 self.add_hstore('address', 'street', value)
54 def set_key_addr_place(self, value):
56 self.add_hstore('address', 'place', value)
58 def set_key_country(self, value):
60 self.add_hstore('address', 'country', value)
62 def set_key_geometry(self, value):
63 self.geometry = self.context.osm.parse_geometry(value, self.context.scene)
64 assert_is_not_none(self.geometry)
66 def add_hstore(self, column, key, value):
67 if column in self.columns:
68 self.columns[column][key] = value
70 self.columns[column] = { key : value }
72 def db_insert(self, cursor):
73 assert_in('osm_type', self.columns)
74 if self.force_name and 'name' not in self.columns:
75 self.add_hstore('name', 'name', ''.join(random.choice(string.printable)
76 for _ in range(int(random.random()*30))))
78 if self.columns['osm_type'] == 'N' and self.geometry is None:
79 pt = self.context.osm.grid_node(self.columns['osm_id'])
81 pt = (random.random()*360 - 180, random.random()*180 - 90)
83 self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % pt
85 assert_is_not_none(self.geometry, "Geometry missing")
86 query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
87 ','.join(self.columns.keys()),
88 ','.join(['%s' for x in range(len(self.columns))]),
90 cursor.execute(query, list(self.columns.values()))
92 class LazyFmt(object):
94 def __init__(self, fmtstr, *args):
99 return self.fmt % self.args
101 class PlaceObjName(object):
103 def __init__(self, placeid, conn):
111 cur = self.conn.cursor()
112 cur.execute("""SELECT osm_type, osm_id, class
113 FROM placex WHERE place_id = %s""",
115 eq_(1, cur.rowcount, "No entry found for place id %s" % self.pid)
117 return "%s%s:%s" % cur.fetchone()
119 def compare_place_id(expected, result, column, context):
122 LazyFmt("Bad place id in column %s. Expected: 0, got: %s.",
123 column, PlaceObjName(result, context.db)))
124 elif expected == '-':
125 assert_is_none(result,
126 LazyFmt("bad place id in column %s: %s.",
127 column, PlaceObjName(result, context.db)))
129 eq_(NominatimID(expected).get_place_id(context.db.cursor()), result,
130 LazyFmt("Bad place id in column %s. Expected: %s, got: %s.",
131 column, expected, PlaceObjName(result, context.db)))
134 """ Splits a unique identifier for places into its components.
135 As place_ids cannot be used for testing, we use a unique
136 identifier instead that is of the form <osmtype><osmid>[:<class>].
139 id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
141 def __init__(self, oid):
142 self.typ = self.oid = self.cls = None
145 m = self.id_regex.fullmatch(oid)
146 assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
148 self.typ = m.group('tp')
149 self.oid = m.group('id')
150 self.cls = m.group('cls')
154 return self.typ + self.oid
156 return '%s%d:%s' % (self.typ, self.oid, self.cls)
158 def table_select(self):
159 """ Return where clause and parameter list to select the object
160 from a Nominatim table.
162 where = 'osm_type = %s and osm_id = %s'
163 params = [self.typ, self. oid]
165 if self.cls is not None:
166 where += ' and class = %s'
167 params.append(self.cls)
171 def get_place_id(self, cur):
172 where, params = self.table_select()
173 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
175 "Expected exactly 1 entry in placex for %s found %s"
176 % (str(self), cur.rowcount))
178 return cur.fetchone()[0]
181 def assert_db_column(row, column, value, context):
182 if column == 'object':
185 if column.startswith('centroid'):
186 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
187 x, y = value.split(' ')
188 assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
189 assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
190 elif column == 'geometry':
191 geom = context.osm.parse_geometry(value, context.scene)
192 cur = context.db.cursor()
193 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
194 geom, row['geomtxt'],)
196 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
198 assert_is_none(row[column], "Row %s" % column)
200 eq_(value, str(row[column]),
201 "Row '%s': expected: %s, got: %s"
202 % (column, value, str(row[column])))
205 ################################ STEPS ##################################
207 @given(u'the scene (?P<scene>.+)')
208 def set_default_scene(context, scene):
209 context.scene = scene
211 @given("the (?P<named>named )?places")
212 def add_data_to_place_table(context, named):
213 cur = context.db.cursor()
214 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
215 for r in context.table:
216 col = PlaceColumn(context, named is not None)
222 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
226 @given("the relations")
227 def add_data_to_planet_relations(context):
228 cur = context.db.cursor()
229 for r in context.table:
235 for m in r['members'].split(','):
238 parts.insert(last_node, int(mid.oid))
242 parts.insert(last_way, int(mid.oid))
245 parts.append(int(mid.oid))
247 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
253 if h.startswith("tags+"):
254 tags.extend((h[5:], r[h]))
256 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
257 VALUES (%s, %s, %s, %s, %s, %s)""",
258 (r['id'], last_node, last_way, parts, members, tags))
262 def add_data_to_planet_ways(context):
263 cur = context.db.cursor()
264 for r in context.table:
267 if h.startswith("tags+"):
268 tags.extend((h[5:], r[h]))
270 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
272 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
273 (r['id'], nodes, tags))
277 def import_and_index_data_from_place_table(context):
278 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
279 cur = context.db.cursor()
281 """insert into placex (osm_type, osm_id, class, type, name, admin_level,
282 address, extratags, geometry)
283 select * from place where not (class='place' and type='houses' and osm_type='W')""")
285 """insert into location_property_osmline (osm_id, address, linegeo)
286 SELECT osm_id, address, geometry from place
287 WHERE class='place' and type='houses' and osm_type='W'
288 and ST_GeometryType(geometry) = 'ST_LineString'""")
290 context.nominatim.run_setup_script('index', 'index-noanalyse')
292 @when("updating places")
293 def update_place_table(context):
294 context.nominatim.run_setup_script(
295 'create-functions', 'create-partition-functions', 'enable-diff-updates')
296 cur = context.db.cursor()
297 for r in context.table:
298 col = PlaceColumn(context, False)
308 context.nominatim.run_update_script('index')
310 cur = context.db.cursor()
311 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
312 if cur.rowcount == 0:
315 @when("marking for delete (?P<oids>.*)")
316 def delete_places(context, oids):
317 context.nominatim.run_setup_script(
318 'create-functions', 'create-partition-functions', 'enable-diff-updates')
319 cur = context.db.cursor()
320 for oid in oids.split(','):
321 where, params = NominatimID(oid).table_select()
322 cur.execute("DELETE FROM place WHERE " + where, params)
326 context.nominatim.run_update_script('index')
328 cur = context.db.cursor()
329 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
330 if cur.rowcount == 0:
333 @then("placex contains(?P<exact> exactly)?")
334 def check_placex_contents(context, exact):
335 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
337 expected_content = set()
338 for row in context.table:
339 nid = NominatimID(row['object'])
340 where, params = nid.table_select()
341 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
342 ST_X(centroid) as cx, ST_Y(centroid) as cy
343 FROM placex where %s""" % where,
345 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
349 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
350 for h in row.headings:
351 if h.startswith('name'):
352 name = h[5:] if h.startswith('name+') else 'name'
353 assert_in(name, res['name'])
354 eq_(res['name'][name], row[h])
355 elif h.startswith('extratags+'):
356 eq_(res['extratags'][h[10:]], row[h])
357 elif h.startswith('addr+'):
359 if res['address'] is not None:
360 assert_not_in(h[5:], res['address'])
362 assert_in(h[5:], res['address'], "column " + h)
363 assert_equals(res['address'][h[5:]], row[h],
365 elif h in ('linked_place_id', 'parent_place_id'):
366 compare_place_id(row[h], res[h], h, context)
368 assert_db_column(res, h, row[h], context)
371 cur.execute('SELECT osm_type, osm_id, class from placex')
372 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
376 @then("place contains(?P<exact> exactly)?")
377 def check_placex_contents(context, exact):
378 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
380 expected_content = set()
381 for row in context.table:
382 nid = NominatimID(row['object'])
383 where, params = nid.table_select()
384 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
385 ST_GeometryType(geometry) as geometrytype
386 FROM place where %s""" % where,
388 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
392 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
393 for h in row.headings:
394 msg = "%s: %s" % (row['object'], h)
395 if h in ('name', 'extratags', 'address'):
397 assert_is_none(res[h], msg)
399 vdict = eval('{' + row[h] + '}')
400 assert_equals(vdict, res[h], msg)
401 elif h.startswith('name+'):
402 assert_equals(res['name'][h[5:]], row[h], msg)
403 elif h.startswith('extratags+'):
404 assert_equals(res['extratags'][h[10:]], row[h], msg)
405 elif h.startswith('addr+'):
407 if res['address'] is not None:
408 assert_not_in(h[5:], res['address'])
410 assert_equals(res['address'][h[5:]], row[h], msg)
411 elif h in ('linked_place_id', 'parent_place_id'):
412 compare_place_id(row[h], res[h], h, context)
414 assert_db_column(res, h, row[h], context)
417 cur.execute('SELECT osm_type, osm_id, class from place')
418 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
422 @then("search_name contains")
423 def check_search_name_contents(context):
424 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
426 for row in context.table:
427 pid = NominatimID(row['object']).get_place_id(cur)
428 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
429 FROM search_name WHERE place_id = %s""", (pid, ))
430 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
433 for h in row.headings:
434 if h in ('name_vector', 'nameaddress_vector'):
435 terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
436 subcur = context.db.cursor()
437 subcur.execute("""SELECT word_id, word_token
438 FROM word, (SELECT unnest(%s) as term) t
439 WHERE word_token = make_standard_name(t.term)""",
441 ok_(subcur.rowcount >= len(terms),
442 "No word entry found for " + row[h])
444 assert_in(wid[0], res[h],
445 "Missing term for %s/%s: %s" % (pid, h, wid[1]))
447 assert_db_column(res, h, row[h], context)
452 @then("place_addressline contains")
453 def check_place_addressline(context):
454 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
456 for row in context.table:
457 pid = NominatimID(row['object']).get_place_id(cur)
458 apid = NominatimID(row['address']).get_place_id(cur)
459 cur.execute(""" SELECT * FROM place_addressline
460 WHERE place_id = %s AND address_place_id = %s""",
462 assert_less(0, cur.rowcount,
463 "No rows found for place %s and address %s"
464 % (row['object'], row['address']))
467 for h in row.headings:
468 if h not in ('address', 'object'):
469 assert_db_column(res, h, row[h], context)
473 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
474 def check_location_property_osmline(context, oid, neg):
475 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
476 nid = NominatimID(oid)
478 eq_('W', nid.typ, "interpolation must be a way")
480 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
481 FROM location_property_osmline
482 WHERE osm_id = %s AND startnumber IS NOT NULL""",
489 todo = list(range(len(list(context.table))))
492 row = context.table[i]
493 if (int(row['start']) == res['startnumber']
494 and int(row['end']) == res['endnumber']):
498 assert False, "Unexpected row %s" % (str(res))
500 for h in row.headings:
501 if h in ('start', 'end'):
503 elif h == 'parent_place_id':
504 compare_place_id(row[h], res[h], h, context)
506 assert_db_column(res, h, row[h], context)
511 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
512 def check_placex_has_entry(context, table, oid):
513 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
514 nid = NominatimID(oid)
515 where, params = nid.table_select()
516 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
520 @then("search_name has no entry for (?P<oid>.*)")
521 def check_search_name_has_entry(context, oid):
522 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
523 pid = NominatimID(oid).get_place_id(cur)
524 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))