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 self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % (
65 random.random()*360 - 180, random.random()*180 - 90)
67 assert_is_not_none(self.geometry, "Geometry missing")
68 query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
69 ','.join(self.columns.keys()),
70 ','.join(['%s' for x in range(len(self.columns))]),
72 cursor.execute(query, list(self.columns.values()))
75 """ Splits a unique identifier for places into its components.
76 As place_ids cannot be used for testing, we use a unique
77 identifier instead that is of the form <osmtype><osmid>[:<class>].
80 id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
82 def __init__(self, oid):
83 self.typ = self.oid = self.cls = None
86 m = self.id_regex.fullmatch(oid)
87 assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
89 self.typ = m.group('tp')
90 self.oid = m.group('id')
91 self.cls = m.group('cls')
93 def table_select(self):
94 """ Return where clause and parameter list to select the object
95 from a Nominatim table.
97 where = 'osm_type = %s and osm_id = %s'
98 params = [self.typ, self. oid]
100 if self.cls is not None:
101 where += ' and class = %s'
102 params.append(self.cls)
106 def get_place_id(self, cur):
107 where, params = self.table_select()
108 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
109 eq_(1, cur.rowcount, "Expected exactly 1 entry in placex found %s" % cur.rowcount)
111 return cur.fetchone()[0]
114 def assert_db_column(row, column, value, context):
115 if column == 'object':
118 if column.startswith('centroid'):
119 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
120 x, y = value.split(' ')
121 assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
122 assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
123 elif column == 'geometry':
124 geom = context.osm.parse_geometry(value, context.scene)
125 cur = context.db.cursor()
126 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
127 geom, row['geomtxt'],)
129 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
131 assert_is_none(row[column], "Row %s" % column)
133 eq_(value, str(row[column]),
134 "Row '%s': expected: %s, got: %s"
135 % (column, value, str(row[column])))
138 ################################ STEPS ##################################
140 @given(u'the scene (?P<scene>.+)')
141 def set_default_scene(context, scene):
142 context.scene = scene
144 @given("the (?P<named>named )?places")
145 def add_data_to_place_table(context, named):
146 cur = context.db.cursor()
147 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
148 for r in context.table:
149 col = PlaceColumn(context, named is not None)
155 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
159 @given("the relations")
160 def add_data_to_planet_relations(context):
161 cur = context.db.cursor()
162 for r in context.table:
168 for m in r['members'].split(','):
171 parts.insert(last_node, int(mid.oid))
175 parts.insert(last_way, int(mid.oid))
178 parts.append(int(mid.oid))
180 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
186 if h.startswith("tags+"):
187 tags.extend((h[5:], r[h]))
189 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
190 VALUES (%s, %s, %s, %s, %s, %s)""",
191 (r['id'], last_node, last_way, parts, members, tags))
195 def add_data_to_planet_ways(context):
196 cur = context.db.cursor()
197 for r in context.table:
200 if h.startswith("tags+"):
201 tags.extend((h[5:], r[h]))
203 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
205 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
206 (r['id'], nodes, tags))
210 def import_and_index_data_from_place_table(context):
211 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
212 cur = context.db.cursor()
214 """insert into placex (osm_type, osm_id, class, type, name, admin_level,
215 housenumber, street, addr_place, isin, postcode, country_code, extratags,
217 select * from place where not (class='place' and type='houses' and osm_type='W')""")
219 """insert into location_property_osmline
220 (osm_id, interpolationtype, street, addr_place,
221 postcode, calculated_country_code, linegeo)
222 SELECT osm_id, housenumber, street, addr_place,
223 postcode, country_code, geometry from place
224 WHERE class='place' and type='houses' and osm_type='W'
225 and ST_GeometryType(geometry) = 'ST_LineString'""")
227 context.nominatim.run_setup_script('index', 'index-noanalyse')
229 @when("updating places")
230 def update_place_table(context):
231 context.nominatim.run_setup_script(
232 'create-functions', 'create-partition-functions', 'enable-diff-updates')
233 cur = context.db.cursor()
234 for r in context.table:
235 col = PlaceColumn(context, False)
243 context.nominatim.run_update_script('index')
245 @when("marking for delete (?P<oids>.*)")
246 def delete_places(context, oids):
247 context.nominatim.run_setup_script(
248 'create-functions', 'create-partition-functions', 'enable-diff-updates')
249 cur = context.db.cursor()
250 for oid in oids.split(','):
251 where, params = NominatimID(oid).table_select()
252 cur.execute("DELETE FROM place WHERE " + where, params)
254 context.nominatim.run_update_script('index')
256 @then("placex contains(?P<exact> exactly)?")
257 def check_placex_contents(context, exact):
258 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
260 expected_content = set()
261 for row in context.table:
262 nid = NominatimID(row['object'])
263 where, params = nid.table_select()
264 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
265 ST_X(centroid) as cx, ST_Y(centroid) as cy
266 FROM placex where %s""" % where,
268 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
272 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
273 for h in row.headings:
274 if h.startswith('name'):
275 name = h[5:] if h.startswith('name+') else 'name'
276 assert_in(name, res['name'])
277 eq_(res['name'][name], row[h])
278 elif h.startswith('extratags+'):
279 eq_(res['extratags'][h[10:]], row[h])
280 elif h in ('linked_place_id', 'parent_place_id'):
284 assert_is_none(res[h])
286 eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
289 assert_db_column(res, h, row[h], context)
292 cur.execute('SELECT osm_type, osm_id, class from placex')
293 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
297 @then("place contains(?P<exact> exactly)?")
298 def check_placex_contents(context, exact):
299 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
301 expected_content = set()
302 for row in context.table:
303 nid = NominatimID(row['object'])
304 where, params = nid.table_select()
305 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
306 ST_GeometryType(geometry) as geometrytype
307 FROM place where %s""" % where,
309 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
313 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
314 for h in row.headings:
315 msg = "%s: %s" % (row['object'], h)
316 if h in ('name', 'extratags'):
318 assert_is_none(res[h], msg)
320 vdict = eval('{' + row[h] + '}')
321 assert_equals(vdict, res[h], msg)
322 elif h.startswith('name+'):
323 assert_equals(res['name'][h[5:]], row[h], msg)
324 elif h.startswith('extratags+'):
325 assert_equals(res['extratags'][h[10:]], row[h], msg)
326 elif h in ('linked_place_id', 'parent_place_id'):
328 assert_equals(0, res[h], msg)
330 assert_is_none(res[h], msg)
332 assert_equals(NominatimID(row[h]).get_place_id(context.db.cursor()),
335 assert_db_column(res, h, row[h], context)
338 cur.execute('SELECT osm_type, osm_id, class from place')
339 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
343 @then("search_name contains")
344 def check_search_name_contents(context):
345 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
347 for row in context.table:
348 pid = NominatimID(row['object']).get_place_id(cur)
349 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
350 FROM search_name WHERE place_id = %s""", (pid, ))
351 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
354 for h in row.headings:
355 if h in ('name_vector', 'nameaddress_vector'):
356 terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
357 subcur = context.db.cursor()
358 subcur.execute("""SELECT word_id, word_token
359 FROM word, (SELECT unnest(%s) as term) t
360 WHERE word_token = make_standard_name(t.term)""",
362 ok_(subcur.rowcount >= len(terms))
364 assert_in(wid[0], res[h],
365 "Missing term for %s/%s: %s" % (pid, h, wid[1]))
367 assert_db_column(res, h, row[h], context)
372 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
373 def check_location_property_osmline(context, oid, neg):
374 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
375 nid = NominatimID(oid)
377 eq_('W', nid.typ, "interpolation must be a way")
379 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
380 FROM location_property_osmline
381 WHERE osm_id = %s AND startnumber IS NOT NULL""",
388 todo = list(range(len(list(context.table))))
391 row = context.table[i]
392 if (int(row['start']) == res['startnumber']
393 and int(row['end']) == res['endnumber']):
397 assert False, "Unexpected row %s" % (str(res))
399 for h in row.headings:
400 if h in ('start', 'end'):
402 elif h == 'parent_place_id':
406 assert_is_none(res[h])
408 eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
411 assert_db_column(res, h, row[h], context)
416 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
417 def check_placex_has_entry(context, table, oid):
418 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
419 nid = NominatimID(oid)
420 where, params = nid.table_select()
421 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
425 @then("search_name has no entry for (?P<oid>.*)")
426 def check_search_name_has_entry(context, oid):
427 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
428 pid = NominatimID(oid).get_place_id(cur)
429 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))