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):
43 self.add_hstore('address', 'housenumber', None if value == '' else value)
45 def set_key_postcode(self, value):
46 self.add_hstore('address', 'postcode', None if value == '' else value)
48 def set_key_street(self, value):
49 self.add_hstore('address', 'street', None if value == '' else value)
51 def set_key_addr_place(self, value):
52 self.add_hstore('address', 'place', None if value == '' else value)
54 def set_key_country(self, value):
55 self.add_hstore('address', 'country', None if value == '' else value)
57 def set_key_geometry(self, value):
58 self.geometry = self.context.osm.parse_geometry(value, self.context.scene)
59 assert_is_not_none(self.geometry)
61 def add_hstore(self, column, key, value):
62 if column in self.columns:
63 self.columns[column][key] = value
65 self.columns[column] = { key : value }
67 def db_insert(self, cursor):
68 assert_in('osm_type', self.columns)
69 if self.force_name and 'name' not in self.columns:
70 self.add_hstore('name', 'name', ''.join(random.choice(string.printable)
71 for _ in range(int(random.random()*30))))
73 if self.columns['osm_type'] == 'N' and self.geometry is None:
74 pt = self.context.osm.grid_node(self.columns['osm_id'])
76 pt = (random.random()*360 - 180, random.random()*180 - 90)
78 self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % pt
80 assert_is_not_none(self.geometry, "Geometry missing")
81 query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
82 ','.join(self.columns.keys()),
83 ','.join(['%s' for x in range(len(self.columns))]),
85 cursor.execute(query, list(self.columns.values()))
87 class LazyFmt(object):
89 def __init__(self, fmtstr, *args):
94 return self.fmt % self.args
96 class PlaceObjName(object):
98 def __init__(self, placeid, conn):
106 self.conn.cursor().execute("""SELECT osm_type, osm_id, class
107 FROM placex WHERE place_id = %s""",
109 eq_(1, cur.rowcount, "No entry found for place id %s" % self.pid)
111 return "%s%s:%s" % cur.fetchone()
113 def compare_place_id(expected, result, column, context):
116 LazyFmt("Bad place id in column %s. Expected: 0, got: %s.",
117 column, PlaceObjName(result, context.db)))
118 elif expected == '-':
119 assert_is_none(result,
120 LazyFmt("bad place id in column %s: %s.",
121 column, PlaceObjName(result, context.db)))
123 eq_(NominatimID(expected).get_place_id(context.db.cursor()), result,
124 LazyFmt("Bad place id in column %s. Expected: %s, got: %s.",
125 column, expected, PlaceObjName(result, context.db)))
128 """ Splits a unique identifier for places into its components.
129 As place_ids cannot be used for testing, we use a unique
130 identifier instead that is of the form <osmtype><osmid>[:<class>].
133 id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
135 def __init__(self, oid):
136 self.typ = self.oid = self.cls = None
139 m = self.id_regex.fullmatch(oid)
140 assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
142 self.typ = m.group('tp')
143 self.oid = m.group('id')
144 self.cls = m.group('cls')
148 return self.typ + self.oid
150 return '%s%d:%s' % (self.typ, self.oid, self.cls)
152 def table_select(self):
153 """ Return where clause and parameter list to select the object
154 from a Nominatim table.
156 where = 'osm_type = %s and osm_id = %s'
157 params = [self.typ, self. oid]
159 if self.cls is not None:
160 where += ' and class = %s'
161 params.append(self.cls)
165 def get_place_id(self, cur):
166 where, params = self.table_select()
167 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
169 "Expected exactly 1 entry in placex for %s found %s"
170 % (str(self), cur.rowcount))
172 return cur.fetchone()[0]
175 def assert_db_column(row, column, value, context):
176 if column == 'object':
179 if column.startswith('centroid'):
180 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
181 x, y = value.split(' ')
182 assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
183 assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
184 elif column == 'geometry':
185 geom = context.osm.parse_geometry(value, context.scene)
186 cur = context.db.cursor()
187 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
188 geom, row['geomtxt'],)
190 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
192 assert_is_none(row[column], "Row %s" % column)
194 eq_(value, str(row[column]),
195 "Row '%s': expected: %s, got: %s"
196 % (column, value, str(row[column])))
199 ################################ STEPS ##################################
201 @given(u'the scene (?P<scene>.+)')
202 def set_default_scene(context, scene):
203 context.scene = scene
205 @given("the (?P<named>named )?places")
206 def add_data_to_place_table(context, named):
207 cur = context.db.cursor()
208 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
209 for r in context.table:
210 col = PlaceColumn(context, named is not None)
216 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
220 @given("the relations")
221 def add_data_to_planet_relations(context):
222 cur = context.db.cursor()
223 for r in context.table:
229 for m in r['members'].split(','):
232 parts.insert(last_node, int(mid.oid))
236 parts.insert(last_way, int(mid.oid))
239 parts.append(int(mid.oid))
241 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
247 if h.startswith("tags+"):
248 tags.extend((h[5:], r[h]))
250 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
251 VALUES (%s, %s, %s, %s, %s, %s)""",
252 (r['id'], last_node, last_way, parts, members, tags))
256 def add_data_to_planet_ways(context):
257 cur = context.db.cursor()
258 for r in context.table:
261 if h.startswith("tags+"):
262 tags.extend((h[5:], r[h]))
264 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
266 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
267 (r['id'], nodes, tags))
271 def import_and_index_data_from_place_table(context):
272 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
273 cur = context.db.cursor()
275 """insert into placex (osm_type, osm_id, class, type, name, admin_level,
276 address, extratags, geometry)
277 select * from place where not (class='place' and type='houses' and osm_type='W')""")
279 """insert into location_property_osmline (osm_id, address, linegeo)
280 SELECT osm_id, address, geometry from place
281 WHERE class='place' and type='houses' and osm_type='W'
282 and ST_GeometryType(geometry) = 'ST_LineString'""")
284 context.nominatim.run_setup_script('index', 'index-noanalyse')
286 @when("updating places")
287 def update_place_table(context):
288 context.nominatim.run_setup_script(
289 'create-functions', 'create-partition-functions', 'enable-diff-updates')
290 cur = context.db.cursor()
291 for r in context.table:
292 col = PlaceColumn(context, False)
302 context.nominatim.run_update_script('index')
304 cur = context.db.cursor()
305 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
306 if cur.rowcount == 0:
309 @when("marking for delete (?P<oids>.*)")
310 def delete_places(context, oids):
311 context.nominatim.run_setup_script(
312 'create-functions', 'create-partition-functions', 'enable-diff-updates')
313 cur = context.db.cursor()
314 for oid in oids.split(','):
315 where, params = NominatimID(oid).table_select()
316 cur.execute("DELETE FROM place WHERE " + where, params)
320 context.nominatim.run_update_script('index')
322 cur = context.db.cursor()
323 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
324 if cur.rowcount == 0:
327 @then("placex contains(?P<exact> exactly)?")
328 def check_placex_contents(context, exact):
329 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
331 expected_content = set()
332 for row in context.table:
333 nid = NominatimID(row['object'])
334 where, params = nid.table_select()
335 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
336 ST_X(centroid) as cx, ST_Y(centroid) as cy
337 FROM placex where %s""" % where,
339 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
343 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
344 for h in row.headings:
345 if h.startswith('name'):
346 name = h[5:] if h.startswith('name+') else 'name'
347 assert_in(name, res['name'])
348 eq_(res['name'][name], row[h])
349 elif h.startswith('extratags+'):
350 eq_(res['extratags'][h[10:]], row[h])
351 elif h.startswith('addr+'):
353 if res['address'] is not None:
354 assert_not_in(h[5:], res['address'])
356 assert_in(h[5:], res['address'], "column " + h)
357 assert_equals(res['address'][h[5:]], row[h],
359 elif h in ('linked_place_id', 'parent_place_id'):
360 compare_place_id(row[h], res[h], h, context)
362 assert_db_column(res, h, row[h], context)
365 cur.execute('SELECT osm_type, osm_id, class from placex')
366 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
370 @then("place contains(?P<exact> exactly)?")
371 def check_placex_contents(context, exact):
372 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
374 expected_content = set()
375 for row in context.table:
376 nid = NominatimID(row['object'])
377 where, params = nid.table_select()
378 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
379 ST_GeometryType(geometry) as geometrytype
380 FROM place where %s""" % where,
382 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
386 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
387 for h in row.headings:
388 msg = "%s: %s" % (row['object'], h)
389 if h in ('name', 'extratags', 'address'):
391 assert_is_none(res[h], msg)
393 vdict = eval('{' + row[h] + '}')
394 assert_equals(vdict, res[h], msg)
395 elif h.startswith('name+'):
396 assert_equals(res['name'][h[5:]], row[h], msg)
397 elif h.startswith('extratags+'):
398 assert_equals(res['extratags'][h[10:]], row[h], msg)
399 elif h.startswith('addr+'):
401 if res['address'] is not None:
402 assert_not_in(h[5:], res['address'])
404 assert_equals(res['address'][h[5:]], row[h], msg)
405 elif h in ('linked_place_id', 'parent_place_id'):
406 compare_place_id(row[h], res[h], h, context)
408 assert_db_column(res, h, row[h], context)
411 cur.execute('SELECT osm_type, osm_id, class from place')
412 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
416 @then("search_name contains")
417 def check_search_name_contents(context):
418 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
420 for row in context.table:
421 pid = NominatimID(row['object']).get_place_id(cur)
422 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
423 FROM search_name WHERE place_id = %s""", (pid, ))
424 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
427 for h in row.headings:
428 if h in ('name_vector', 'nameaddress_vector'):
429 terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
430 subcur = context.db.cursor()
431 subcur.execute("""SELECT word_id, word_token
432 FROM word, (SELECT unnest(%s) as term) t
433 WHERE word_token = make_standard_name(t.term)""",
435 ok_(subcur.rowcount >= len(terms))
437 assert_in(wid[0], res[h],
438 "Missing term for %s/%s: %s" % (pid, h, wid[1]))
440 assert_db_column(res, h, row[h], context)
445 @then("place_addressline contains")
446 def check_place_addressline(context):
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 apid = NominatimID(row['address']).get_place_id(cur)
452 cur.execute(""" SELECT * FROM place_addressline
453 WHERE place_id = %s AND address_place_id = %s""",
455 assert_less(0, cur.rowcount,
456 "No rows found for place %s and address %s"
457 % (row['object'], row['address']))
460 for h in row.headings:
461 if h not in ('address', 'object'):
462 assert_db_column(res, h, row[h], context)
466 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
467 def check_location_property_osmline(context, oid, neg):
468 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
469 nid = NominatimID(oid)
471 eq_('W', nid.typ, "interpolation must be a way")
473 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
474 FROM location_property_osmline
475 WHERE osm_id = %s AND startnumber IS NOT NULL""",
482 todo = list(range(len(list(context.table))))
485 row = context.table[i]
486 if (int(row['start']) == res['startnumber']
487 and int(row['end']) == res['endnumber']):
491 assert False, "Unexpected row %s" % (str(res))
493 for h in row.headings:
494 if h in ('start', 'end'):
496 elif h == 'parent_place_id':
497 compare_place_id(row[h], res[h], h, context)
499 assert_db_column(res, h, row[h], context)
504 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
505 def check_placex_has_entry(context, table, oid):
506 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
507 nid = NominatimID(oid)
508 where, params = nid.table_select()
509 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
513 @then("search_name has no entry for (?P<oid>.*)")
514 def check_search_name_has_entry(context, oid):
515 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
516 pid = NominatimID(oid).get_place_id(cur)
517 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))