]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/db_ops.py
add parenting tests
[nominatim.git] / test / bdd / steps / db_ops.py
1 import base64
2 import random
3 import string
4 import re
5 from nose.tools import * # for assert functions
6 import psycopg2.extras
7
8 class PlaceColumn:
9
10     def __init__(self, context, force_name):
11         self.columns = { 'admin_level' : 100}
12         self.force_name = force_name
13         self.context = context
14         self.geometry = None
15
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         else:
24             assert_in(key, ('class', 'type', 'street', 'addr_place',
25                             'isin', 'postcode'))
26             self.columns[key] = value
27
28     def set_key_name(self, value):
29         self.add_hstore('name', 'name', value)
30
31     def set_key_osm(self, value):
32         assert_in(value[0], 'NRW')
33         ok_(value[1:].isdigit())
34
35         self.columns['osm_type'] = value[0]
36         self.columns['osm_id'] = int(value[1:])
37
38     def set_key_admin(self, value):
39         self.columns['admin_level'] = int(value)
40
41     def set_key_housenr(self, value):
42         self.columns['housenumber'] = value
43
44     def set_key_country(self, value):
45         self.columns['country_code'] = value
46
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)
50
51     def add_hstore(self, column, key, value):
52         if column in self.columns:
53             self.columns[column][key] = value
54         else:
55             self.columns[column] = { key : value }
56
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))))
62
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)
66         else:
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))]),
71                      self.geometry)
72         cursor.execute(query, list(self.columns.values()))
73
74 class NominatimID:
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>].
78     """
79
80     id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
81
82     def __init__(self, oid):
83         self.typ = self.oid = self.cls = None
84
85         if oid is not None:
86             m = self.id_regex.fullmatch(oid)
87             assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
88
89             self.typ = m.group('tp')
90             self.oid = m.group('id')
91             self.cls = m.group('cls')
92
93     def table_select(self):
94         """ Return where clause and parameter list to select the object
95             from a Nominatim table.
96         """
97         where = 'osm_type = %s and osm_id = %s'
98         params = [self.typ, self. oid]
99
100         if self.cls is not None:
101             where += ' class = %s'
102             params.append(self.cls)
103
104         return where, params
105
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)
110
111         return cur.fetchone()[0]
112
113
114 def assert_db_column(row, column, value):
115     if column == 'object':
116         return
117
118     if column.startswith('centroid'):
119         fac = float(column[9:]) if h.startswith('centroid*') else 1.0
120         x, y = value.split(' ')
121         assert_almost_equal(float(x) * fac, row['cx'])
122         assert_almost_equal(float(y) * fac, row['cy'])
123     else:
124         eq_(value, str(row[column]),
125             "Row '%s': expected: %s, got: %s"
126             % (column, value, str(row[column])))
127
128
129 ################################ STEPS ##################################
130
131 @given(u'the scene (?P<scene>.+)')
132 def set_default_scene(context, scene):
133     context.scene = scene
134
135 @given("the (?P<named>named )?places")
136 def add_data_to_place_table(context, named):
137     cur = context.db.cursor()
138     cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
139     for r in context.table:
140         col = PlaceColumn(context, named is not None)
141
142         for h in r.headings:
143             col.add(h, r[h])
144
145         col.db_insert(cur)
146     cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
147     cur.close()
148     context.db.commit()
149
150 @given("the relations")
151 def add_data_to_planet_relations(context):
152     cur = context.db.cursor()
153     for r in context.table:
154         last_node = 0
155         last_way = 0
156         parts = []
157         members = []
158         for m in r['members'].split(','):
159             mid = NominatimID(m)
160             if mid.typ == 'N':
161                 parts.insert(last_node, int(mid.oid))
162                 members.insert(2 * last_node, mid.cls)
163                 members.insert(2 * last_node, 'n' + mid.oid)
164                 last_node += 1
165                 last_way += 1
166             elif mid.typ == 'W':
167                 parts.insert(last_way, int(mid.oid))
168                 members.insert(2 * last_way, mid.cls)
169                 members.insert(2 * last_way, 'w' + mid.oid)
170                 last_way += 1
171             else:
172                 parts.append(int(mid.oid))
173                 members.extend(('r' + mid.oid, mid.cls))
174
175         tags = []
176         for h in r.headings:
177             if h.startswith("tags+"):
178                 tags.extend((h[5:], r[h]))
179
180         cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
181                        VALUES (%s, %s, %s, %s, %s, %s)""",
182                     (r['id'], last_node, last_way, parts, members, tags))
183     context.db.commit()
184
185 @given("the ways")
186 def add_data_to_planet_ways(context):
187     cur = context.db.cursor()
188     for r in context.table:
189         tags = []
190         for h in r.headings:
191             if h.startswith("tags+"):
192                 tags.extend((h[5:], r[h]))
193
194         nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
195
196         cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
197                     (r['id'], nodes, tags))
198     context.db.commit()
199
200 @when("importing")
201 def import_and_index_data_from_place_table(context):
202     context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
203     cur = context.db.cursor()
204     cur.execute(
205         """insert into placex (osm_type, osm_id, class, type, name, admin_level,
206            housenumber, street, addr_place, isin, postcode, country_code, extratags,
207            geometry)
208            select * from place where not (class='place' and type='houses' and osm_type='W')""")
209     cur.execute(
210         """select insert_osmline (osm_id, housenumber, street, addr_place,
211            postcode, country_code, geometry)
212            from place where class='place' and type='houses' and osm_type='W'""")
213     context.db.commit()
214     context.nominatim.run_setup_script('index', 'index-noanalyse')
215
216
217
218 @then("placex contains(?P<exact> exactly)?")
219 def check_placex_contents(context, exact):
220     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
221
222     expected_content = set()
223     for row in context.table:
224         nid = NominatimID(row['object'])
225         where, params = nid.table_select()
226         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
227                        ST_X(centroid) as cx, ST_Y(centroid) as cy
228                        FROM placex where %s""" % where,
229                     params)
230
231         for res in cur:
232             if exact:
233                 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
234             for h in row.headings:
235                 if h.startswith('name'):
236                     name = h[5:] if h.startswith('name+') else 'name'
237                     assert_in(name, res['name'])
238                     eq_(res['name'][name], row[h])
239                 elif h.startswith('extratags+'):
240                     eq_(res['extratags'][h[10:]], row[h])
241                 elif h == 'parent_place_id':
242                     if row[h] == '0':
243                         eq_(0, res[h])
244                     else:
245                         eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
246                             res[h])
247                 else:
248                     assert_db_column(res, h, row[h])
249
250     if exact:
251         cur.execute('SELECT osm_type, osm_id, class from placex')
252         eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
253
254     context.db.commit()
255
256 @then("search_name contains")
257 def check_search_name_contents(context):
258     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
259
260     for row in context.table:
261         pid = NominatimID(row['object']).get_place_id(cur)
262         cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
263                        FROM search_name WHERE place_id = %s""", (pid, ))
264
265         for res in cur:
266             for h in row.headings:
267                 if h in ('name_vector', 'nameaddress_vector'):
268                     terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
269                     subcur = context.db.cursor()
270                     subcur.execute("""SELECT word_id, word_token
271                                       FROM word, (SELECT unnest(%s) as term) t
272                                       WHERE word_token = make_standard_name(t.term)""",
273                                    (terms,))
274                     ok_(subcur.rowcount >= len(terms))
275                     for wid in subcur:
276                         assert_in(wid[0], res[h],
277                                   "Missing term for %s/%s: %s" % (pid, h, wid[1]))
278                 else:
279                     assert_db_column(res, h, row[h])
280
281
282     context.db.commit()
283
284
285 @then("placex has no entry for (?P<oid>.*)")
286 def check_placex_has_entry(context, oid):
287     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
288     nid = NominatimID(oid)
289     where, params = nid.table_select()
290     cur.execute("SELECT * FROM placex where %s" % where, params)
291     eq_(0, cur.rowcount)
292     context.db.commit()
293
294 @then("search_name has no entry for (?P<oid>.*)")
295 def check_search_name_has_entry(context, oid):
296     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
297     pid = NominatimID(oid).get_place_id(cur)
298     cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))
299     eq_(0, cur.rowcount)
300     context.db.commit()