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')
96 def table_select(self):
97 """ Return where clause and parameter list to select the object
98 from a Nominatim table.
100 where = 'osm_type = %s and osm_id = %s'
101 params = [self.typ, self. oid]
103 if self.cls is not None:
104 where += ' and class = %s'
105 params.append(self.cls)
109 def get_place_id(self, cur):
110 where, params = self.table_select()
111 cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
112 eq_(1, cur.rowcount, "Expected exactly 1 entry in placex found %s" % cur.rowcount)
114 return cur.fetchone()[0]
117 def assert_db_column(row, column, value, context):
118 if column == 'object':
121 if column.startswith('centroid'):
122 fac = float(column[9:]) if column.startswith('centroid*') else 1.0
123 x, y = value.split(' ')
124 assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
125 assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
126 elif column == 'geometry':
127 geom = context.osm.parse_geometry(value, context.scene)
128 cur = context.db.cursor()
129 query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
130 geom, row['geomtxt'],)
132 eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
134 assert_is_none(row[column], "Row %s" % column)
136 eq_(value, str(row[column]),
137 "Row '%s': expected: %s, got: %s"
138 % (column, value, str(row[column])))
141 ################################ STEPS ##################################
143 @given(u'the scene (?P<scene>.+)')
144 def set_default_scene(context, scene):
145 context.scene = scene
147 @given("the (?P<named>named )?places")
148 def add_data_to_place_table(context, named):
149 cur = context.db.cursor()
150 cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
151 for r in context.table:
152 col = PlaceColumn(context, named is not None)
158 cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
162 @given("the relations")
163 def add_data_to_planet_relations(context):
164 cur = context.db.cursor()
165 for r in context.table:
171 for m in r['members'].split(','):
174 parts.insert(last_node, int(mid.oid))
178 parts.insert(last_way, int(mid.oid))
181 parts.append(int(mid.oid))
183 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
189 if h.startswith("tags+"):
190 tags.extend((h[5:], r[h]))
192 cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
193 VALUES (%s, %s, %s, %s, %s, %s)""",
194 (r['id'], last_node, last_way, parts, members, tags))
198 def add_data_to_planet_ways(context):
199 cur = context.db.cursor()
200 for r in context.table:
203 if h.startswith("tags+"):
204 tags.extend((h[5:], r[h]))
206 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
208 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
209 (r['id'], nodes, tags))
213 def import_and_index_data_from_place_table(context):
214 context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
215 cur = context.db.cursor()
217 """insert into placex (osm_type, osm_id, class, type, name, admin_level,
218 housenumber, street, addr_place, isin, postcode, country_code, extratags,
220 select * from place where not (class='place' and type='houses' and osm_type='W')""")
222 """insert into location_property_osmline
223 (osm_id, interpolationtype, street, addr_place,
224 postcode, calculated_country_code, linegeo)
225 SELECT osm_id, housenumber, street, addr_place,
226 postcode, country_code, geometry from place
227 WHERE class='place' and type='houses' and osm_type='W'
228 and ST_GeometryType(geometry) = 'ST_LineString'""")
230 context.nominatim.run_setup_script('index', 'index-noanalyse')
232 @when("updating places")
233 def update_place_table(context):
234 context.nominatim.run_setup_script(
235 'create-functions', 'create-partition-functions', 'enable-diff-updates')
236 cur = context.db.cursor()
237 for r in context.table:
238 col = PlaceColumn(context, False)
246 context.nominatim.run_update_script('index')
248 @when("marking for delete (?P<oids>.*)")
249 def delete_places(context, oids):
250 context.nominatim.run_setup_script(
251 'create-functions', 'create-partition-functions', 'enable-diff-updates')
252 cur = context.db.cursor()
253 for oid in oids.split(','):
254 where, params = NominatimID(oid).table_select()
255 cur.execute("DELETE FROM place WHERE " + where, params)
257 context.nominatim.run_update_script('index')
259 @then("placex contains(?P<exact> exactly)?")
260 def check_placex_contents(context, exact):
261 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
263 expected_content = set()
264 for row in context.table:
265 nid = NominatimID(row['object'])
266 where, params = nid.table_select()
267 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
268 ST_X(centroid) as cx, ST_Y(centroid) as cy
269 FROM placex where %s""" % where,
271 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
275 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
276 for h in row.headings:
277 if h.startswith('name'):
278 name = h[5:] if h.startswith('name+') else 'name'
279 assert_in(name, res['name'])
280 eq_(res['name'][name], row[h])
281 elif h.startswith('extratags+'):
282 eq_(res['extratags'][h[10:]], row[h])
283 elif h in ('linked_place_id', 'parent_place_id'):
287 assert_is_none(res[h])
289 eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
292 assert_db_column(res, h, row[h], context)
295 cur.execute('SELECT osm_type, osm_id, class from placex')
296 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
300 @then("place contains(?P<exact> exactly)?")
301 def check_placex_contents(context, exact):
302 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
304 expected_content = set()
305 for row in context.table:
306 nid = NominatimID(row['object'])
307 where, params = nid.table_select()
308 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
309 ST_GeometryType(geometry) as geometrytype
310 FROM place where %s""" % where,
312 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
316 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
317 for h in row.headings:
318 msg = "%s: %s" % (row['object'], h)
319 if h in ('name', 'extratags'):
321 assert_is_none(res[h], msg)
323 vdict = eval('{' + row[h] + '}')
324 assert_equals(vdict, res[h], msg)
325 elif h.startswith('name+'):
326 assert_equals(res['name'][h[5:]], row[h], msg)
327 elif h.startswith('extratags+'):
328 assert_equals(res['extratags'][h[10:]], row[h], msg)
329 elif h in ('linked_place_id', 'parent_place_id'):
331 assert_equals(0, res[h], msg)
333 assert_is_none(res[h], msg)
335 assert_equals(NominatimID(row[h]).get_place_id(context.db.cursor()),
338 assert_db_column(res, h, row[h], context)
341 cur.execute('SELECT osm_type, osm_id, class from place')
342 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
346 @then("search_name contains")
347 def check_search_name_contents(context):
348 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
350 for row in context.table:
351 pid = NominatimID(row['object']).get_place_id(cur)
352 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
353 FROM search_name WHERE place_id = %s""", (pid, ))
354 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
357 for h in row.headings:
358 if h in ('name_vector', 'nameaddress_vector'):
359 terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
360 subcur = context.db.cursor()
361 subcur.execute("""SELECT word_id, word_token
362 FROM word, (SELECT unnest(%s) as term) t
363 WHERE word_token = make_standard_name(t.term)""",
365 ok_(subcur.rowcount >= len(terms))
367 assert_in(wid[0], res[h],
368 "Missing term for %s/%s: %s" % (pid, h, wid[1]))
370 assert_db_column(res, h, row[h], context)
375 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
376 def check_location_property_osmline(context, oid, neg):
377 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
378 nid = NominatimID(oid)
380 eq_('W', nid.typ, "interpolation must be a way")
382 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
383 FROM location_property_osmline
384 WHERE osm_id = %s AND startnumber IS NOT NULL""",
391 todo = list(range(len(list(context.table))))
394 row = context.table[i]
395 if (int(row['start']) == res['startnumber']
396 and int(row['end']) == res['endnumber']):
400 assert False, "Unexpected row %s" % (str(res))
402 for h in row.headings:
403 if h in ('start', 'end'):
405 elif h == 'parent_place_id':
409 assert_is_none(res[h])
411 eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
414 assert_db_column(res, h, row[h], context)
419 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
420 def check_placex_has_entry(context, table, oid):
421 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
422 nid = NominatimID(oid)
423 where, params = nid.table_select()
424 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
428 @then("search_name has no entry for (?P<oid>.*)")
429 def check_search_name_has_entry(context, oid):
430 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
431 pid = NominatimID(oid).get_place_id(cur)
432 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))