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)
248 context.nominatim.run_update_script('index')
250 cur = context.db.cursor()
251 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
252 if cur.rowcount == 0:
255 @when("marking for delete (?P<oids>.*)")
256 def delete_places(context, oids):
257 context.nominatim.run_setup_script(
258 'create-functions', 'create-partition-functions', 'enable-diff-updates')
259 cur = context.db.cursor()
260 for oid in oids.split(','):
261 where, params = NominatimID(oid).table_select()
262 cur.execute("DELETE FROM place WHERE " + where, params)
266 context.nominatim.run_update_script('index')
268 cur = context.db.cursor()
269 cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
270 if cur.rowcount == 0:
273 @then("placex contains(?P<exact> exactly)?")
274 def check_placex_contents(context, exact):
275 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
277 expected_content = set()
278 for row in context.table:
279 nid = NominatimID(row['object'])
280 where, params = nid.table_select()
281 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
282 ST_X(centroid) as cx, ST_Y(centroid) as cy
283 FROM placex where %s""" % where,
285 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
289 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
290 for h in row.headings:
291 if h.startswith('name'):
292 name = h[5:] if h.startswith('name+') else 'name'
293 assert_in(name, res['name'])
294 eq_(res['name'][name], row[h])
295 elif h.startswith('extratags+'):
296 eq_(res['extratags'][h[10:]], row[h])
297 elif h in ('linked_place_id', 'parent_place_id'):
301 assert_is_none(res[h])
303 eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
306 assert_db_column(res, h, row[h], context)
309 cur.execute('SELECT osm_type, osm_id, class from placex')
310 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
314 @then("place contains(?P<exact> exactly)?")
315 def check_placex_contents(context, exact):
316 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
318 expected_content = set()
319 for row in context.table:
320 nid = NominatimID(row['object'])
321 where, params = nid.table_select()
322 cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
323 ST_GeometryType(geometry) as geometrytype
324 FROM place where %s""" % where,
326 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
330 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
331 for h in row.headings:
332 msg = "%s: %s" % (row['object'], h)
333 if h in ('name', 'extratags'):
335 assert_is_none(res[h], msg)
337 vdict = eval('{' + row[h] + '}')
338 assert_equals(vdict, res[h], msg)
339 elif h.startswith('name+'):
340 assert_equals(res['name'][h[5:]], row[h], msg)
341 elif h.startswith('extratags+'):
342 assert_equals(res['extratags'][h[10:]], row[h], msg)
343 elif h in ('linked_place_id', 'parent_place_id'):
345 assert_equals(0, res[h], msg)
347 assert_is_none(res[h], msg)
349 assert_equals(NominatimID(row[h]).get_place_id(context.db.cursor()),
352 assert_db_column(res, h, row[h], context)
355 cur.execute('SELECT osm_type, osm_id, class from place')
356 eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
360 @then("search_name contains")
361 def check_search_name_contents(context):
362 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
364 for row in context.table:
365 pid = NominatimID(row['object']).get_place_id(cur)
366 cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
367 FROM search_name WHERE place_id = %s""", (pid, ))
368 assert_less(0, cur.rowcount, "No rows found for " + row['object'])
371 for h in row.headings:
372 if h in ('name_vector', 'nameaddress_vector'):
373 terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
374 subcur = context.db.cursor()
375 subcur.execute("""SELECT word_id, word_token
376 FROM word, (SELECT unnest(%s) as term) t
377 WHERE word_token = make_standard_name(t.term)""",
379 ok_(subcur.rowcount >= len(terms))
381 assert_in(wid[0], res[h],
382 "Missing term for %s/%s: %s" % (pid, h, wid[1]))
384 assert_db_column(res, h, row[h], context)
389 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
390 def check_location_property_osmline(context, oid, neg):
391 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
392 nid = NominatimID(oid)
394 eq_('W', nid.typ, "interpolation must be a way")
396 cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
397 FROM location_property_osmline
398 WHERE osm_id = %s AND startnumber IS NOT NULL""",
405 todo = list(range(len(list(context.table))))
408 row = context.table[i]
409 if (int(row['start']) == res['startnumber']
410 and int(row['end']) == res['endnumber']):
414 assert False, "Unexpected row %s" % (str(res))
416 for h in row.headings:
417 if h in ('start', 'end'):
419 elif h == 'parent_place_id':
423 assert_is_none(res[h])
425 eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
428 assert_db_column(res, h, row[h], context)
433 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
434 def check_placex_has_entry(context, table, oid):
435 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
436 nid = NominatimID(oid)
437 where, params = nid.table_select()
438 cur.execute("SELECT * FROM %s where %s" % (table, where), params)
442 @then("search_name has no entry for (?P<oid>.*)")
443 def check_search_name_has_entry(context, oid):
444 cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
445 pid = NominatimID(oid).get_place_id(cur)
446 cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))