5 from nose.tools import * # for assert functions
10 def __init__(self, context, force_name):
11 self.columns = { 'admin_level' : 100}
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[6:], 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_street(self, value):
46 self.add_hstore('address', 'street', None if value == '' else value)
48 def set_key_addr_place(self, value):
49 self.add_hstore('address', 'place', None if value == '' else value)
51 def set_key_country(self, value):
52 self.add_hstore('address', 'country', None if value == '' else value)
54 def set_key_geometry(self, value):
55 self.geometry = self.context.osm.parse_geometry(value, self.context.scene)
56 assert_is_not_none(self.geometry)
58 def add_hstore(self, column, key, value):
59 if column in self.columns:
60 self.columns[column][key] = value
62 self.columns[column] = { key : value }
64 def db_insert(self, cursor):
65 assert_in('osm_type', self.columns)
66 if self.force_name and 'name' not in self.columns:
67 self.add_hstore('name', 'name', ''.join(random.choice(string.printable)
68 for _ in range(int(random.random()*30))))
70 if self.columns['osm_type'] == 'N' and self.geometry is None:
71 pt = self.context.osm.grid_node(self.columns['osm_id'])
73 pt = (random.random()*360 - 180, random.random()*180 - 90)
75 self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % pt
77 assert_is_not_none(self.geometry, "Geometry missing")
78 query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
79 ','.join(self.columns.keys()),
80 ','.join(['%s' for x in range(len(self.columns))]),
82 cursor.execute(query, list(self.columns.values()))
85 """ Splits a unique identifier for places into its components.
86 As place_ids cannot be used for testing, we use a unique
87 identifier instead that is of the form <osmtype><osmid>[:<class>].
90 id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
92 def __init__(self, oid):
93 self.typ = self.oid = self.cls = None
96 m = self.id_regex.fullmatch(oid)
97 assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
99 self.typ = m.group('tp')
100 self.oid = m.group('id')
101 self.cls = m.group('cls')
105 return self.typ + self.oid
107 return '%s%d:%s' % (self.typ, self.oid, self.cls)
109 def table_select(self):
110 """ Return where clause and parameter list to select the object
111 from a Nominatim table.
113 where = 'osm_type = %s and osm_id = %s'
114 params = [self.typ, self. oid]
116 if self.cls is not None:
117 where += ' and class = %s'
118 params.append(self.cls)
122 def get_place_id(self, cur):
123 where, params = self.table_select()
124 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
126 "Expected exactly 1 entry in placex for %s found %s"
127 % (str(self), cur.rowcount))
129 return cur.fetchone()[0]
132 def assert_db_column(row, column, value, context):
133 if column == 'object':
136 if column.startswith('centroid'):
137 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
138 x, y = value.split(' ')
139 assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
140 assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
141 elif column == 'geometry':
142 geom = context.osm.parse_geometry(value, context.scene)
143 cur = context.db.cursor()
144 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
145 geom, row['geomtxt'],)
147 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
149 assert_is_none(row[column], "Row %s" % column)
151 eq_(value, str(row[column]),
152 "Row '%s': expected: %s, got: %s"
153 % (column, value, str(row[column])))
156 ################################ STEPS ##################################
158 @given(u'the scene (?P<scene>.+)')
159 def set_default_scene(context, scene):
160 context.scene = scene
162 @given("the (?P<named>named )?places")
163 def add_data_to_place_table(context, named):
164 cur = context.db.cursor()
165 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
166 for r in context.table:
167 col = PlaceColumn(context, named is not None)
173 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
177 @given("the relations")
178 def add_data_to_planet_relations(context):
179 cur = context.db.cursor()
180 for r in context.table:
186 for m in r['members'].split(','):
189 parts.insert(last_node, int(mid.oid))
193 parts.insert(last_way, int(mid.oid))
196 parts.append(int(mid.oid))
198 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
204 if h.startswith("tags+"):
205 tags.extend((h[5:], r[h]))
207 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
208 VALUES (%s, %s, %s, %s, %s, %s)""",
209 (r['id'], last_node, last_way, parts, members, tags))
213 def add_data_to_planet_ways(context):
214 cur = context.db.cursor()
215 for r in context.table:
218 if h.startswith("tags+"):
219 tags.extend((h[5:], r[h]))
221 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
223 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
224 (r['id'], nodes, tags))
228 def import_and_index_data_from_place_table(context):
229 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
230 cur = context.db.cursor()
232 """insert into placex (osm_type, osm_id, class, type, name, admin_level,
233 address, extratags, geometry)
234 select * from place where not (class='place' and type='houses' and osm_type='W')""")
236 """insert into location_property_osmline (osm_id, address, linegeo)
237 SELECT osm_id, address, geometry from place
238 WHERE class='place' and type='houses' and osm_type='W'
239 and ST_GeometryType(geometry) = 'ST_LineString'""")
241 context.nominatim.run_setup_script('index', 'index-noanalyse')
243 @when("updating places")
244 def update_place_table(context):
245 context.nominatim.run_setup_script(
246 'create-functions', 'create-partition-functions', 'enable-diff-updates')
247 cur = context.db.cursor()
248 for r in context.table:
249 col = PlaceColumn(context, False)
259 context.nominatim.run_update_script('index')
261 cur = context.db.cursor()
262 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
263 if cur.rowcount == 0:
266 @when("marking for delete (?P<oids>.*)")
267 def delete_places(context, oids):
268 context.nominatim.run_setup_script(
269 'create-functions', 'create-partition-functions', 'enable-diff-updates')
270 cur = context.db.cursor()
271 for oid in oids.split(','):
272 where, params = NominatimID(oid).table_select()
273 cur.execute("DELETE FROM place WHERE " + where, params)
277 context.nominatim.run_update_script('index')
279 cur = context.db.cursor()
280 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
281 if cur.rowcount == 0:
284 @then("placex contains(?P<exact> exactly)?")
285 def check_placex_contents(context, exact):
286 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
288 expected_content = set()
289 for row in context.table:
290 nid = NominatimID(row['object'])
291 where, params = nid.table_select()
292 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
293 ST_X(centroid) as cx, ST_Y(centroid) as cy
294 FROM placex where %s""" % where,
296 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
300 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
301 for h in row.headings:
302 if h.startswith('name'):
303 name = h[5:] if h.startswith('name+') else 'name'
304 assert_in(name, res['name'])
305 eq_(res['name'][name], row[h])
306 elif h.startswith('extratags+'):
307 eq_(res['extratags'][h[10:]], row[h])
308 elif h in ('linked_place_id', 'parent_place_id'):
312 assert_is_none(res[h])
314 eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
317 assert_db_column(res, h, row[h], context)
320 cur.execute('SELECT osm_type, osm_id, class from placex')
321 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
325 @then("place contains(?P<exact> exactly)?")
326 def check_placex_contents(context, exact):
327 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
329 expected_content = set()
330 for row in context.table:
331 nid = NominatimID(row['object'])
332 where, params = nid.table_select()
333 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
334 ST_GeometryType(geometry) as geometrytype
335 FROM place where %s""" % where,
337 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
341 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
342 for h in row.headings:
343 msg = "%s: %s" % (row['object'], h)
344 if h in ('name', 'extratags', 'address'):
346 assert_is_none(res[h], msg)
348 vdict = eval('{' + row[h] + '}')
349 assert_equals(vdict, res[h], msg)
350 elif h.startswith('name+'):
351 assert_equals(res['name'][h[5:]], row[h], msg)
352 elif h.startswith('extratags+'):
353 assert_equals(res['extratags'][h[10:]], row[h], msg)
354 elif h.startswith('addr+'):
356 if res['address'] is not None:
357 assert_not_in(h[5:], res['address'])
359 assert_equals(res['address'][h[5:]], row[h], msg)
360 elif h in ('linked_place_id', 'parent_place_id'):
362 assert_equals(0, res[h], msg)
364 assert_is_none(res[h], msg)
366 assert_equals(NominatimID(row[h]).get_place_id(context.db.cursor()),
369 assert_db_column(res, h, row[h], context)
372 cur.execute('SELECT osm_type, osm_id, class from place')
373 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
377 @then("search_name contains")
378 def check_search_name_contents(context):
379 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
381 for row in context.table:
382 pid = NominatimID(row['object']).get_place_id(cur)
383 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
384 FROM search_name WHERE place_id = %s""", (pid, ))
385 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
388 for h in row.headings:
389 if h in ('name_vector', 'nameaddress_vector'):
390 terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
391 subcur = context.db.cursor()
392 subcur.execute("""SELECT word_id, word_token
393 FROM word, (SELECT unnest(%s) as term) t
394 WHERE word_token = make_standard_name(t.term)""",
396 ok_(subcur.rowcount >= len(terms))
398 assert_in(wid[0], res[h],
399 "Missing term for %s/%s: %s" % (pid, h, wid[1]))
401 assert_db_column(res, h, row[h], context)
406 @then("place_addressline contains")
407 def check_place_addressline(context):
408 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
410 for row in context.table:
411 pid = NominatimID(row['object']).get_place_id(cur)
412 apid = NominatimID(row['address']).get_place_id(cur)
413 cur.execute(""" SELECT * FROM place_addressline
414 WHERE place_id = %s AND address_place_id = %s""",
416 assert_less(0, cur.rowcount,
417 "No rows found for place %s and address %s"
418 % (row['object'], row['address']))
421 for h in row.headings:
422 if h not in ('address', 'object'):
423 assert_db_column(res, h, row[h], context)
427 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
428 def check_location_property_osmline(context, oid, neg):
429 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
430 nid = NominatimID(oid)
432 eq_('W', nid.typ, "interpolation must be a way")
434 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
435 FROM location_property_osmline
436 WHERE osm_id = %s AND startnumber IS NOT NULL""",
443 todo = list(range(len(list(context.table))))
446 row = context.table[i]
447 if (int(row['start']) == res['startnumber']
448 and int(row['end']) == res['endnumber']):
452 assert False, "Unexpected row %s" % (str(res))
454 for h in row.headings:
455 if h in ('start', 'end'):
457 elif h == 'parent_place_id':
461 assert_is_none(res[h])
463 eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
466 assert_db_column(res, h, row[h], context)
471 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
472 def check_placex_has_entry(context, table, oid):
473 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
474 nid = NominatimID(oid)
475 where, params = nid.table_select()
476 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
480 @then("search_name has no entry for (?P<oid>.*)")
481 def check_search_name_has_entry(context, oid):
482 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
483 pid = NominatimID(oid).get_place_id(cur)
484 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))