]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/db_ops.py
add placex import 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
67         query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
68                      ','.join(self.columns.keys()),
69                      ','.join(['%s' for x in range(len(self.columns))]),
70                      self.geometry)
71         cursor.execute(query, list(self.columns.values()))
72
73 class NominatimID:
74     """ Splits a unique identifier for places into its components.
75         As place_ids cannot be used for testing, we use a unique
76         identifier instead that is of the form <osmtype><osmid>[:<class>].
77     """
78
79     id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(?P<cls>:\w+)?")
80
81     def __init__(self, oid):
82         self.typ = self.oid = self.cls = None
83
84         if oid is not None:
85             m = self.id_regex.fullmatch(oid)
86             assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
87
88             self.typ = m.group('tp')
89             self.oid = m.group('id')
90             self.cls = m.group('cls')
91
92     def table_select(self):
93         """ Return where clause and parameter list to select the object
94             from a Nominatim table.
95         """
96         where = 'osm_type = %s and osm_id = %s'
97         params = [self.typ, self. oid]
98
99         if self.cls is not None:
100             where += ' class = %s'
101             params.append(self.cls)
102
103         return where, params
104
105 @given(u'the scene (?P<scene>.+)')
106 def set_default_scene(context, scene):
107     context.scene = scene
108
109 @given("the (?P<named>named )?places")
110 def add_data_to_place_table(context, named):
111     cur = context.db.cursor()
112     cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
113     for r in context.table:
114         col = PlaceColumn(context, named is not None)
115
116         for h in r.headings:
117             col.add(h, r[h])
118
119         col.db_insert(cur)
120     cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
121     cur.close()
122     context.db.commit()
123
124
125 @when("importing")
126 def import_and_index_data_from_place_table(context):
127     context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
128     cur = context.db.cursor()
129     cur.execute(
130         """insert into placex (osm_type, osm_id, class, type, name, admin_level,
131            housenumber, street, addr_place, isin, postcode, country_code, extratags,
132            geometry)
133            select * from place where not (class='place' and type='houses' and osm_type='W')""")
134     cur.execute(
135         """select insert_osmline (osm_id, housenumber, street, addr_place,
136            postcode, country_code, geometry)
137            from place where class='place' and type='houses' and osm_type='W'""")
138     context.db.commit()
139     context.nominatim.run_setup_script('index', 'index-noanalyse')
140
141
142 @then("placex contains(?P<exact> exactly)?")
143 def check_placex_contents(context, exact):
144     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
145     if exact:
146         cur.execute('SELECT osm_type, osm_id, class from placex')
147         to_match = [(r[0], r[1], r[2]) for r in cur]
148
149     for row in context.table:
150         nid = NominatimID(row['object'])
151         where, params = nid.table_select()
152         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
153                        ST_X(centroid) as cx, ST_Y(centroid) as cy
154                        FROM placex where %s""" % where,
155                     params)
156
157         for res in cur:
158             for h in row.headings:
159                 if h == 'object':
160                     pass
161                 elif h.startswith('name'):
162                     name = h[5:] if h.startswith('name+') else 'name'
163                     assert_in(name, res['name'])
164                     eq_(res['name'][name], row[h])
165                 elif h.startswith('extratags+'):
166                     eq_(res['extratags'][h[10:]], row[h])
167                 elif h.startswith('centroid'):
168                     fac = float(h[9:]) if h.startswith('centroid*') else 1.0
169                     x, y = row[h].split(' ')
170                     assert_almost_equal(float(x) * fac, res['cx'])
171                     assert_almost_equal(float(y) * fac, res['cy'])
172                 else:
173                     eq_(row[h], str(res[h]),
174                         "Row '%s': expected: %s, got: %s" % (h, row[h], str(res[h])))
175     context.db.commit()
176
177 @then("placex has no entry for (?P<oid>.*)")
178 def check_placex_has_entry(context, oid):
179     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
180     nid = NominatimID(oid)
181     where, params = nid.table_select()
182     cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
183                    ST_X(centroid) as cx, ST_Y(centroid) as cy
184                    FROM placex where %s""" % where,
185                 params)
186     eq_(0, cur.rowcount)
187     context.db.commit()