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)
24 assert_in(key, ('class', 'type', 'street', 'addr_place',
26 self.columns[key] = None if value == '' else value
28 def set_key_name(self, value):
29 self.add_hstore('name', 'name', value)
31 def set_key_osm(self, value):
32 assert_in(value[0], 'NRW')
33 ok_(value[1:].isdigit())
35 self.columns['osm_type'] = value[0]
36 self.columns['osm_id'] = int(value[1:])
38 def set_key_admin(self, value):
39 self.columns['admin_level'] = int(value)
41 def set_key_housenr(self, value):
42 self.columns['housenumber'] = None if value == '' else value
44 def set_key_country(self, value):
45 self.columns['country_code'] = None if value == '' else value
47 def set_key_geometry(self, value):
48 self.geometry = self.context.osm.parse_geometry(value, self.context.scene)
49 assert_is_not_none(self.geometry)
51 def add_hstore(self, column, key, value):
52 if column in self.columns:
53 self.columns[column][key] = value
55 self.columns[column] = { key : value }
57 def db_insert(self, cursor):
58 assert_in('osm_type', self.columns)
59 if self.force_name and 'name' not in self.columns:
60 self.add_hstore('name', 'name', ''.join(random.choice(string.printable)
61 for _ in range(int(random.random()*30))))
63 if self.columns['osm_type'] == 'N' and self.geometry is None:
64 pt = self.context.osm.grid_node(self.columns['osm_id'])
66 pt = (random.random()*360 - 180, random.random()*180 - 90)
68 self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % pt
70 assert_is_not_none(self.geometry, "Geometry missing")
71 query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
72 ','.join(self.columns.keys()),
73 ','.join(['%s' for x in range(len(self.columns))]),
75 cursor.execute(query, list(self.columns.values()))
78 """ Splits a unique identifier for places into its components.
79 As place_ids cannot be used for testing, we use a unique
80 identifier instead that is of the form <osmtype><osmid>[:<class>].
83 id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
85 def __init__(self, oid):
86 self.typ = self.oid = self.cls = None
89 m = self.id_regex.fullmatch(oid)
90 assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
92 self.typ = m.group('tp')
93 self.oid = m.group('id')
94 self.cls = m.group('cls')
98 return self.typ + self.oid
100 return '%s%d:%s' % (self.typ, self.oid, self.cls)
102 def table_select(self):
103 """ Return where clause and parameter list to select the object
104 from a Nominatim table.
106 where = 'osm_type = %s and osm_id = %s'
107 params = [self.typ, self. oid]
109 if self.cls is not None:
110 where += ' and class = %s'
111 params.append(self.cls)
115 def get_place_id(self, cur):
116 where, params = self.table_select()
117 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
119 "Expected exactly 1 entry in placex for %s found %s"
120 % (str(self), cur.rowcount))
122 return cur.fetchone()[0]
125 def assert_db_column(row, column, value, context):
126 if column == 'object':
129 if column.startswith('centroid'):
130 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
131 x, y = value.split(' ')
132 assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
133 assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
134 elif column == 'geometry':
135 geom = context.osm.parse_geometry(value, context.scene)
136 cur = context.db.cursor()
137 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
138 geom, row['geomtxt'],)
140 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
142 assert_is_none(row[column], "Row %s" % column)
144 eq_(value, str(row[column]),
145 "Row '%s': expected: %s, got: %s"
146 % (column, value, str(row[column])))
149 ################################ STEPS ##################################
151 @given(u'the scene (?P<scene>.+)')
152 def set_default_scene(context, scene):
153 context.scene = scene
155 @given("the (?P<named>named )?places")
156 def add_data_to_place_table(context, named):
157 cur = context.db.cursor()
158 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
159 for r in context.table:
160 col = PlaceColumn(context, named is not None)
166 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
170 @given("the relations")
171 def add_data_to_planet_relations(context):
172 cur = context.db.cursor()
173 for r in context.table:
179 for m in r['members'].split(','):
182 parts.insert(last_node, int(mid.oid))
186 parts.insert(last_way, int(mid.oid))
189 parts.append(int(mid.oid))
191 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
197 if h.startswith("tags+"):
198 tags.extend((h[5:], r[h]))
200 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
201 VALUES (%s, %s, %s, %s, %s, %s)""",
202 (r['id'], last_node, last_way, parts, members, tags))
206 def add_data_to_planet_ways(context):
207 cur = context.db.cursor()
208 for r in context.table:
211 if h.startswith("tags+"):
212 tags.extend((h[5:], r[h]))
214 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
216 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
217 (r['id'], nodes, tags))
221 def import_and_index_data_from_place_table(context):
222 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
223 cur = context.db.cursor()
225 """insert into placex (osm_type, osm_id, class, type, name, admin_level,
226 housenumber, street, addr_place, isin, postcode, country_code, extratags,
228 select * from place where not (class='place' and type='houses' and osm_type='W')""")
230 """insert into location_property_osmline
231 (osm_id, interpolationtype, street, addr_place,
232 postcode, calculated_country_code, linegeo)
233 SELECT osm_id, housenumber, street, addr_place,
234 postcode, country_code, geometry from place
235 WHERE class='place' and type='houses' and osm_type='W'
236 and ST_GeometryType(geometry) = 'ST_LineString'""")
238 context.nominatim.run_setup_script('index', 'index-noanalyse')
240 @when("updating places")
241 def update_place_table(context):
242 context.nominatim.run_setup_script(
243 'create-functions', 'create-partition-functions', 'enable-diff-updates')
244 cur = context.db.cursor()
245 for r in context.table:
246 col = PlaceColumn(context, False)
256 context.nominatim.run_update_script('index')
258 cur = context.db.cursor()
259 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
260 if cur.rowcount == 0:
263 @when("marking for delete (?P<oids>.*)")
264 def delete_places(context, oids):
265 context.nominatim.run_setup_script(
266 'create-functions', 'create-partition-functions', 'enable-diff-updates')
267 cur = context.db.cursor()
268 for oid in oids.split(','):
269 where, params = NominatimID(oid).table_select()
270 cur.execute("DELETE FROM place WHERE " + where, params)
274 context.nominatim.run_update_script('index')
276 cur = context.db.cursor()
277 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
278 if cur.rowcount == 0:
281 @then("placex contains(?P<exact> exactly)?")
282 def check_placex_contents(context, exact):
283 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
285 expected_content = set()
286 for row in context.table:
287 nid = NominatimID(row['object'])
288 where, params = nid.table_select()
289 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
290 ST_X(centroid) as cx, ST_Y(centroid) as cy
291 FROM placex where %s""" % where,
293 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
297 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
298 for h in row.headings:
299 if h.startswith('name'):
300 name = h[5:] if h.startswith('name+') else 'name'
301 assert_in(name, res['name'])
302 eq_(res['name'][name], row[h])
303 elif h.startswith('extratags+'):
304 eq_(res['extratags'][h[10:]], row[h])
305 elif h in ('linked_place_id', 'parent_place_id'):
309 assert_is_none(res[h])
311 eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
314 assert_db_column(res, h, row[h], context)
317 cur.execute('SELECT osm_type, osm_id, class from placex')
318 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
322 @then("place contains(?P<exact> exactly)?")
323 def check_placex_contents(context, exact):
324 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
326 expected_content = set()
327 for row in context.table:
328 nid = NominatimID(row['object'])
329 where, params = nid.table_select()
330 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
331 ST_GeometryType(geometry) as geometrytype
332 FROM place where %s""" % where,
334 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
338 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
339 for h in row.headings:
340 msg = "%s: %s" % (row['object'], h)
341 if h in ('name', 'extratags'):
343 assert_is_none(res[h], msg)
345 vdict = eval('{' + row[h] + '}')
346 assert_equals(vdict, res[h], msg)
347 elif h.startswith('name+'):
348 assert_equals(res['name'][h[5:]], row[h], msg)
349 elif h.startswith('extratags+'):
350 assert_equals(res['extratags'][h[10:]], row[h], msg)
351 elif h in ('linked_place_id', 'parent_place_id'):
353 assert_equals(0, res[h], msg)
355 assert_is_none(res[h], msg)
357 assert_equals(NominatimID(row[h]).get_place_id(context.db.cursor()),
360 assert_db_column(res, h, row[h], context)
363 cur.execute('SELECT osm_type, osm_id, class from place')
364 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
368 @then("search_name contains")
369 def check_search_name_contents(context):
370 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
372 for row in context.table:
373 pid = NominatimID(row['object']).get_place_id(cur)
374 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
375 FROM search_name WHERE place_id = %s""", (pid, ))
376 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
379 for h in row.headings:
380 if h in ('name_vector', 'nameaddress_vector'):
381 terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
382 subcur = context.db.cursor()
383 subcur.execute("""SELECT word_id, word_token
384 FROM word, (SELECT unnest(%s) as term) t
385 WHERE word_token = make_standard_name(t.term)""",
387 ok_(subcur.rowcount >= len(terms))
389 assert_in(wid[0], res[h],
390 "Missing term for %s/%s: %s" % (pid, h, wid[1]))
392 assert_db_column(res, h, row[h], context)
397 @then("place_addressline contains")
398 def check_place_addressline(context):
399 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
401 for row in context.table:
402 pid = NominatimID(row['object']).get_place_id(cur)
403 apid = NominatimID(row['address']).get_place_id(cur)
404 cur.execute(""" SELECT * FROM place_addressline
405 WHERE place_id = %s AND address_place_id = %s""",
407 assert_less(0, cur.rowcount,
408 "No rows found for place %s and address %s"
409 % (row['object'], row['address']))
412 for h in row.headings:
413 if h not in ('address', 'object'):
414 assert_db_column(res, h, row[h], context)
418 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
419 def check_location_property_osmline(context, oid, neg):
420 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
421 nid = NominatimID(oid)
423 eq_('W', nid.typ, "interpolation must be a way")
425 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
426 FROM location_property_osmline
427 WHERE osm_id = %s AND startnumber IS NOT NULL""",
434 todo = list(range(len(list(context.table))))
437 row = context.table[i]
438 if (int(row['start']) == res['startnumber']
439 and int(row['end']) == res['endnumber']):
443 assert False, "Unexpected row %s" % (str(res))
445 for h in row.headings:
446 if h in ('start', 'end'):
448 elif h == 'parent_place_id':
452 assert_is_none(res[h])
454 eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
457 assert_db_column(res, h, row[h], context)
462 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
463 def check_placex_has_entry(context, table, oid):
464 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
465 nid = NominatimID(oid)
466 where, params = nid.table_select()
467 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
471 @then("search_name has no entry for (?P<oid>.*)")
472 def check_search_name_has_entry(context, oid):
473 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
474 pid = NominatimID(oid).get_place_id(cur)
475 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))