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)))
136 """ Splits a unique identifier for places into its components.
137 As place_ids cannot be used for testing, we use a unique
138 identifier instead that is of the form <osmtype><osmid>[:<class>].
141 id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
143 def __init__(self, oid):
144 self.typ = self.oid = self.cls = None
147 m = self.id_regex.fullmatch(oid)
148 assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
150 self.typ = m.group('tp')
151 self.oid = m.group('id')
152 self.cls = m.group('cls')
156 return self.typ + self.oid
158 return '%s%d:%s' % (self.typ, self.oid, self.cls)
160 def table_select(self):
161 """ Return where clause and parameter list to select the object
162 from a Nominatim table.
164 where = 'osm_type = %s and osm_id = %s'
165 params = [self.typ, self. oid]
167 if self.cls is not None:
168 where += ' and class = %s'
169 params.append(self.cls)
173 def get_place_id(self, cur):
174 where, params = self.table_select()
175 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
177 "Expected exactly 1 entry in placex for %s found %s"
178 % (str(self), cur.rowcount))
180 return cur.fetchone()[0]
183 def assert_db_column(row, column, value, context):
184 if column == 'object':
187 if column.startswith('centroid'):
188 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
189 x, y = value.split(' ')
190 assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
191 assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
192 elif column == 'geometry':
193 geom = context.osm.parse_geometry(value, context.scene)
194 cur = context.db.cursor()
195 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
196 geom, row['geomtxt'],)
198 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
200 assert_is_none(row[column], "Row %s" % column)
202 eq_(value, str(row[column]),
203 "Row '%s': expected: %s, got: %s"
204 % (column, value, str(row[column])))
207 ################################ STEPS ##################################
209 @given(u'the scene (?P<scene>.+)')
210 def set_default_scene(context, scene):
211 context.scene = scene
213 @given("the (?P<named>named )?places")
214 def add_data_to_place_table(context, named):
215 cur = context.db.cursor()
216 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
217 for r in context.table:
218 col = PlaceColumn(context, named is not None)
224 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
228 @given("the relations")
229 def add_data_to_planet_relations(context):
230 cur = context.db.cursor()
231 for r in context.table:
237 for m in r['members'].split(','):
240 parts.insert(last_node, int(mid.oid))
244 parts.insert(last_way, int(mid.oid))
247 parts.append(int(mid.oid))
249 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
255 if h.startswith("tags+"):
256 tags.extend((h[5:], r[h]))
258 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
259 VALUES (%s, %s, %s, %s, %s, %s)""",
260 (r['id'], last_node, last_way, parts, members, tags))
264 def add_data_to_planet_ways(context):
265 cur = context.db.cursor()
266 for r in context.table:
269 if h.startswith("tags+"):
270 tags.extend((h[5:], r[h]))
272 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
274 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
275 (r['id'], nodes, tags))
279 def import_and_index_data_from_place_table(context):
280 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
281 cur = context.db.cursor()
283 """insert into placex (osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry)
284 select osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry
285 from place where not (class='place' and type='houses' and osm_type='W')""")
287 """insert into location_property_osmline (osm_id, address, linegeo)
288 SELECT osm_id, address, geometry from place
289 WHERE class='place' and type='houses' and osm_type='W'
290 and ST_GeometryType(geometry) = 'ST_LineString'""")
292 context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
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 cur = context.db.cursor()
299 for r in context.table:
300 col = PlaceColumn(context, False)
310 context.nominatim.run_update_script('index')
312 cur = context.db.cursor()
313 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
314 if cur.rowcount == 0:
317 @when("marking for delete (?P<oids>.*)")
318 def delete_places(context, oids):
319 context.nominatim.run_setup_script(
320 'create-functions', 'create-partition-functions', 'enable-diff-updates')
321 cur = context.db.cursor()
322 for oid in oids.split(','):
323 where, params = NominatimID(oid).table_select()
324 cur.execute("DELETE FROM place WHERE " + where, params)
328 context.nominatim.run_update_script('index')
330 cur = context.db.cursor()
331 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
332 if cur.rowcount == 0:
335 @then("placex contains(?P<exact> exactly)?")
336 def check_placex_contents(context, exact):
337 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
339 expected_content = set()
340 for row in context.table:
341 nid = NominatimID(row['object'])
342 where, params = nid.table_select()
343 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
344 ST_X(centroid) as cx, ST_Y(centroid) as cy
345 FROM placex where %s""" % where,
347 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
351 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
352 for h in row.headings:
353 if h in ('extratags', 'address'):
355 assert_is_none(res[h])
357 vdict = eval('{' + row[h] + '}')
358 assert_equals(vdict, res[h])
359 elif h.startswith('name'):
360 name = h[5:] if h.startswith('name+') else 'name'
361 assert_in(name, res['name'])
362 eq_(res['name'][name], row[h])
363 elif h.startswith('extratags+'):
364 eq_(res['extratags'][h[10:]], row[h])
365 elif h.startswith('addr+'):
367 if res['address'] is not None:
368 assert_not_in(h[5:], res['address'])
370 assert_in(h[5:], res['address'], "column " + h)
371 assert_equals(res['address'][h[5:]], row[h],
373 elif h in ('linked_place_id', 'parent_place_id'):
374 compare_place_id(row[h], res[h], h, context)
376 assert_db_column(res, h, row[h], context)
379 cur.execute('SELECT osm_type, osm_id, class from placex')
380 eq_(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 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
388 expected_content = set()
389 for row in context.table:
390 nid = NominatimID(row['object'])
391 where, params = nid.table_select()
392 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
393 ST_GeometryType(geometry) as geometrytype
394 FROM place where %s""" % where,
396 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
400 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
401 for h in row.headings:
402 msg = "%s: %s" % (row['object'], h)
403 if h in ('name', 'extratags', 'address'):
405 assert_is_none(res[h], msg)
407 vdict = eval('{' + row[h] + '}')
408 assert_equals(vdict, res[h], msg)
409 elif h.startswith('name+'):
410 assert_equals(res['name'][h[5:]], row[h], msg)
411 elif h.startswith('extratags+'):
412 assert_equals(res['extratags'][h[10:]], row[h], msg)
413 elif h.startswith('addr+'):
415 if res['address'] is not None:
416 assert_not_in(h[5:], res['address'])
418 assert_equals(res['address'][h[5:]], row[h], msg)
419 elif h in ('linked_place_id', 'parent_place_id'):
420 compare_place_id(row[h], res[h], h, context)
422 assert_db_column(res, h, row[h], context)
425 cur.execute('SELECT osm_type, osm_id, class from place')
426 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
430 @then("search_name contains")
431 def check_search_name_contents(context):
432 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
434 for row in context.table:
435 pid = NominatimID(row['object']).get_place_id(cur)
436 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
437 FROM search_name WHERE place_id = %s""", (pid, ))
438 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
441 for h in row.headings:
442 if h in ('name_vector', 'nameaddress_vector'):
443 terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
444 subcur = context.db.cursor()
445 subcur.execute("""SELECT word_id, word_token
446 FROM word, (SELECT unnest(%s) as term) t
447 WHERE word_token = make_standard_name(t.term)""",
449 ok_(subcur.rowcount >= len(terms),
450 "No word entry found for " + row[h])
452 assert_in(wid[0], res[h],
453 "Missing term for %s/%s: %s" % (pid, h, wid[1]))
455 assert_db_column(res, h, row[h], context)
460 @then("place_addressline contains")
461 def check_place_addressline(context):
462 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
464 for row in context.table:
465 pid = NominatimID(row['object']).get_place_id(cur)
466 apid = NominatimID(row['address']).get_place_id(cur)
467 cur.execute(""" SELECT * FROM place_addressline
468 WHERE place_id = %s AND address_place_id = %s""",
470 assert_less(0, cur.rowcount,
471 "No rows found for place %s and address %s"
472 % (row['object'], row['address']))
475 for h in row.headings:
476 if h not in ('address', 'object'):
477 assert_db_column(res, h, row[h], context)
481 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
482 def check_location_property_osmline(context, oid, neg):
483 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
484 nid = NominatimID(oid)
486 eq_('W', nid.typ, "interpolation must be a way")
488 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
489 FROM location_property_osmline
490 WHERE osm_id = %s AND startnumber IS NOT NULL""",
497 todo = list(range(len(list(context.table))))
500 row = context.table[i]
501 if (int(row['start']) == res['startnumber']
502 and int(row['end']) == res['endnumber']):
506 assert False, "Unexpected row %s" % (str(res))
508 for h in row.headings:
509 if h in ('start', 'end'):
511 elif h == 'parent_place_id':
512 compare_place_id(row[h], res[h], h, context)
514 assert_db_column(res, h, row[h], context)
519 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
520 def check_placex_has_entry(context, table, oid):
521 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
522 nid = NominatimID(oid)
523 where, params = nid.table_select()
524 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
528 @then("search_name has no entry for (?P<oid>.*)")
529 def check_search_name_has_entry(context, oid):
530 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
531 pid = NominatimID(oid).get_place_id(cur)
532 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))