5 from nose.tools import * # for assert functions
 
  10     def __init__(self, context, force_name):
 
  11         self.columns = { 'admin_level' : 15}
 
  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)
 
  23         elif key.startswith('addr+'):
 
  24             self.add_hstore('address', key[5:], value)
 
  26             assert_in(key, ('class', 'type'))
 
  27             self.columns[key] = None if value == '' else value
 
  29     def set_key_name(self, value):
 
  30         self.add_hstore('name', 'name', value)
 
  32     def set_key_osm(self, value):
 
  33         assert_in(value[0], 'NRW')
 
  34         ok_(value[1:].isdigit())
 
  36         self.columns['osm_type'] = value[0]
 
  37         self.columns['osm_id'] = int(value[1:])
 
  39     def set_key_admin(self, value):
 
  40         self.columns['admin_level'] = int(value)
 
  42     def set_key_housenr(self, value):
 
  44             self.add_hstore('address', 'housenumber', value)
 
  46     def set_key_postcode(self, value):
 
  48             self.add_hstore('address', 'postcode', value)
 
  50     def set_key_street(self, value):
 
  52             self.add_hstore('address', 'street', value)
 
  54     def set_key_addr_place(self, value):
 
  56             self.add_hstore('address', 'place', value)
 
  58     def set_key_country(self, value):
 
  60             self.add_hstore('address', 'country', value)
 
  62     def set_key_geometry(self, value):
 
  63         self.geometry = self.context.osm.parse_geometry(value, self.context.scene)
 
  64         assert_is_not_none(self.geometry)
 
  66     def add_hstore(self, column, key, value):
 
  67         if column in self.columns:
 
  68             self.columns[column][key] = value
 
  70             self.columns[column] = { key : value }
 
  72     def db_insert(self, cursor):
 
  73         assert_in('osm_type', self.columns)
 
  74         if self.force_name and 'name' not in self.columns:
 
  75             self.add_hstore('name', 'name', ''.join(random.choice(string.printable)
 
  76                                            for _ in range(int(random.random()*30))))
 
  78         if self.columns['osm_type'] == 'N' and self.geometry is None:
 
  79             pt = self.context.osm.grid_node(self.columns['osm_id'])
 
  81                 pt = (random.random()*360 - 180, random.random()*180 - 90)
 
  83             self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % pt
 
  85             assert_is_not_none(self.geometry, "Geometry missing")
 
  86         query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
 
  87                      ','.join(self.columns.keys()),
 
  88                      ','.join(['%s' for x in range(len(self.columns))]),
 
  90         cursor.execute(query, list(self.columns.values()))
 
  92 class LazyFmt(object):
 
  94     def __init__(self, fmtstr, *args):
 
  99         return self.fmt % self.args
 
 101 class PlaceObjName(object):
 
 103     def __init__(self, placeid, conn):
 
 111         cur = self.conn.cursor()
 
 112         cur.execute("""SELECT osm_type, osm_id, class
 
 113                        FROM placex WHERE place_id = %s""",
 
 115         eq_(1, cur.rowcount, "No entry found for place id %s" % self.pid)
 
 117         return "%s%s:%s" % cur.fetchone()
 
 119 def compare_place_id(expected, result, column, context):
 
 122             LazyFmt("Bad place id in column %s. Expected: 0, got: %s.",
 
 123                     column, PlaceObjName(result, context.db)))
 
 124     elif expected == '-':
 
 125         assert_is_none(result,
 
 126                 LazyFmt("bad place id in column %s: %s.",
 
 127                         column, PlaceObjName(result, context.db)))
 
 129         eq_(NominatimID(expected).get_place_id(context.db.cursor()), result,
 
 130             LazyFmt("Bad place id in column %s. Expected: %s, got: %s.",
 
 131                     column, expected, PlaceObjName(result, context.db)))
 
 134     """ Splits a unique identifier for places into its components.
 
 135         As place_ids cannot be used for testing, we use a unique
 
 136         identifier instead that is of the form <osmtype><osmid>[:<class>].
 
 139     id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
 
 141     def __init__(self, oid):
 
 142         self.typ = self.oid = self.cls = None
 
 145             m = self.id_regex.fullmatch(oid)
 
 146             assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
 
 148             self.typ = m.group('tp')
 
 149             self.oid = m.group('id')
 
 150             self.cls = m.group('cls')
 
 154             return self.typ + self.oid
 
 156         return '%s%d:%s' % (self.typ, self.oid, self.cls)
 
 158     def table_select(self):
 
 159         """ Return where clause and parameter list to select the object
 
 160             from a Nominatim table.
 
 162         where = 'osm_type = %s and osm_id = %s'
 
 163         params = [self.typ, self. oid]
 
 165         if self.cls is not None:
 
 166             where += ' and class = %s'
 
 167             params.append(self.cls)
 
 171     def get_place_id(self, cur):
 
 172         where, params = self.table_select()
 
 173         cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
 
 175             "Expected exactly 1 entry in placex for %s found %s"
 
 176               % (str(self), cur.rowcount))
 
 178         return cur.fetchone()[0]
 
 181 def assert_db_column(row, column, value, context):
 
 182     if column == 'object':
 
 185     if column.startswith('centroid'):
 
 186         fac = float(column[9:]) if column.startswith('centroid*') else 1.0
 
 187         x, y = value.split(' ')
 
 188         assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
 
 189         assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
 
 190     elif column == 'geometry':
 
 191         geom = context.osm.parse_geometry(value, context.scene)
 
 192         cur = context.db.cursor()
 
 193         query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
 
 194                  geom, row['geomtxt'],)
 
 196         eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
 
 198         assert_is_none(row[column], "Row %s" % column)
 
 200         eq_(value, str(row[column]),
 
 201             "Row '%s': expected: %s, got: %s"
 
 202             % (column, value, str(row[column])))
 
 205 ################################ STEPS ##################################
 
 207 @given(u'the scene (?P<scene>.+)')
 
 208 def set_default_scene(context, scene):
 
 209     context.scene = scene
 
 211 @given("the (?P<named>named )?places")
 
 212 def add_data_to_place_table(context, named):
 
 213     cur = context.db.cursor()
 
 214     cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
 
 215     for r in context.table:
 
 216         col = PlaceColumn(context, named is not None)
 
 222     cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
 
 226 @given("the relations")
 
 227 def add_data_to_planet_relations(context):
 
 228     cur = context.db.cursor()
 
 229     for r in context.table:
 
 235             for m in r['members'].split(','):
 
 238                     parts.insert(last_node, int(mid.oid))
 
 242                     parts.insert(last_way, int(mid.oid))
 
 245                     parts.append(int(mid.oid))
 
 247                 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
 
 253             if h.startswith("tags+"):
 
 254                 tags.extend((h[5:], r[h]))
 
 256         cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
 
 257                        VALUES (%s, %s, %s, %s, %s, %s)""",
 
 258                     (r['id'], last_node, last_way, parts, members, tags))
 
 262 def add_data_to_planet_ways(context):
 
 263     cur = context.db.cursor()
 
 264     for r in context.table:
 
 267             if h.startswith("tags+"):
 
 268                 tags.extend((h[5:], r[h]))
 
 270         nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
 
 272         cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
 
 273                     (r['id'], nodes, tags))
 
 277 def import_and_index_data_from_place_table(context):
 
 278     context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
 
 279     cur = context.db.cursor()
 
 281         """insert into placex (osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry)
 
 282            select              osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry
 
 283            from place where not (class='place' and type='houses' and osm_type='W')""")
 
 285             """insert into location_property_osmline (osm_id, address, linegeo)
 
 286              SELECT osm_id, address, geometry from place
 
 287               WHERE class='place' and type='houses' and osm_type='W'
 
 288                     and ST_GeometryType(geometry) = 'ST_LineString'""")
 
 290     context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
 
 292 @when("updating places")
 
 293 def update_place_table(context):
 
 294     context.nominatim.run_setup_script(
 
 295         'create-functions', 'create-partition-functions', 'enable-diff-updates')
 
 296     cur = context.db.cursor()
 
 297     for r in context.table:
 
 298         col = PlaceColumn(context, False)
 
 308         context.nominatim.run_update_script('index')
 
 310         cur = context.db.cursor()
 
 311         cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
 
 312         if cur.rowcount == 0:
 
 315 @when("marking for delete (?P<oids>.*)")
 
 316 def delete_places(context, oids):
 
 317     context.nominatim.run_setup_script(
 
 318         'create-functions', 'create-partition-functions', 'enable-diff-updates')
 
 319     cur = context.db.cursor()
 
 320     for oid in oids.split(','):
 
 321         where, params = NominatimID(oid).table_select()
 
 322         cur.execute("DELETE FROM place WHERE " + where, params)
 
 326         context.nominatim.run_update_script('index')
 
 328         cur = context.db.cursor()
 
 329         cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
 
 330         if cur.rowcount == 0:
 
 333 @then("placex contains(?P<exact> exactly)?")
 
 334 def check_placex_contents(context, exact):
 
 335     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 337     expected_content = set()
 
 338     for row in context.table:
 
 339         nid = NominatimID(row['object'])
 
 340         where, params = nid.table_select()
 
 341         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
 
 342                        ST_X(centroid) as cx, ST_Y(centroid) as cy
 
 343                        FROM placex where %s""" % where,
 
 345         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
 
 349                 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
 
 350             for h in row.headings:
 
 351                 if h in ('extratags', 'address'):
 
 353                         assert_is_none(res[h])
 
 355                         vdict = eval('{' + row[h] + '}')
 
 356                         assert_equals(vdict, res[h])
 
 357                 elif h.startswith('name'):
 
 358                     name = h[5:] if h.startswith('name+') else 'name'
 
 359                     assert_in(name, res['name'])
 
 360                     eq_(res['name'][name], row[h])
 
 361                 elif h.startswith('extratags+'):
 
 362                     eq_(res['extratags'][h[10:]], row[h])
 
 363                 elif h.startswith('addr+'):
 
 365                         if res['address'] is not None:
 
 366                             assert_not_in(h[5:], res['address'])
 
 368                         assert_in(h[5:], res['address'], "column " + h)
 
 369                         assert_equals(res['address'][h[5:]], row[h],
 
 371                 elif h in ('linked_place_id', 'parent_place_id'):
 
 372                     compare_place_id(row[h], res[h], h, context)
 
 374                     assert_db_column(res, h, row[h], context)
 
 377         cur.execute('SELECT osm_type, osm_id, class from placex')
 
 378         eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
 
 382 @then("place contains(?P<exact> exactly)?")
 
 383 def check_placex_contents(context, exact):
 
 384     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 386     expected_content = set()
 
 387     for row in context.table:
 
 388         nid = NominatimID(row['object'])
 
 389         where, params = nid.table_select()
 
 390         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
 
 391                        ST_GeometryType(geometry) as geometrytype
 
 392                        FROM place where %s""" % where,
 
 394         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
 
 398                 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
 
 399             for h in row.headings:
 
 400                 msg = "%s: %s" % (row['object'], h)
 
 401                 if h in ('name', 'extratags', 'address'):
 
 403                         assert_is_none(res[h], msg)
 
 405                         vdict = eval('{' + row[h] + '}')
 
 406                         assert_equals(vdict, res[h], msg)
 
 407                 elif h.startswith('name+'):
 
 408                     assert_equals(res['name'][h[5:]], row[h], msg)
 
 409                 elif h.startswith('extratags+'):
 
 410                     assert_equals(res['extratags'][h[10:]], row[h], msg)
 
 411                 elif h.startswith('addr+'):
 
 413                         if res['address']  is not None:
 
 414                             assert_not_in(h[5:], res['address'])
 
 416                         assert_equals(res['address'][h[5:]], row[h], msg)
 
 417                 elif h in ('linked_place_id', 'parent_place_id'):
 
 418                     compare_place_id(row[h], res[h], h, context)
 
 420                     assert_db_column(res, h, row[h], context)
 
 423         cur.execute('SELECT osm_type, osm_id, class from place')
 
 424         eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
 
 428 @then("search_name contains")
 
 429 def check_search_name_contents(context):
 
 430     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 432     for row in context.table:
 
 433         pid = NominatimID(row['object']).get_place_id(cur)
 
 434         cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
 
 435                        FROM search_name WHERE place_id = %s""", (pid, ))
 
 436         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
 
 439             for h in row.headings:
 
 440                 if h in ('name_vector', 'nameaddress_vector'):
 
 441                     terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
 
 442                     subcur = context.db.cursor()
 
 443                     subcur.execute("""SELECT word_id, word_token
 
 444                                       FROM word, (SELECT unnest(%s) as term) t
 
 445                                       WHERE word_token = make_standard_name(t.term)""",
 
 447                     ok_(subcur.rowcount >= len(terms),
 
 448                         "No word entry found for " + row[h])
 
 450                         assert_in(wid[0], res[h],
 
 451                                   "Missing term for %s/%s: %s" % (pid, h, wid[1]))
 
 453                     assert_db_column(res, h, row[h], context)
 
 458 @then("place_addressline contains")
 
 459 def check_place_addressline(context):
 
 460     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 462     for row in context.table:
 
 463         pid = NominatimID(row['object']).get_place_id(cur)
 
 464         apid = NominatimID(row['address']).get_place_id(cur)
 
 465         cur.execute(""" SELECT * FROM place_addressline
 
 466                         WHERE place_id = %s AND address_place_id = %s""",
 
 468         assert_less(0, cur.rowcount,
 
 469                     "No rows found for place %s and address %s"
 
 470                       % (row['object'], row['address']))
 
 473             for h in row.headings:
 
 474                 if h not in ('address', 'object'):
 
 475                     assert_db_column(res, h, row[h], context)
 
 479 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
 
 480 def check_location_property_osmline(context, oid, neg):
 
 481     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 482     nid = NominatimID(oid)
 
 484     eq_('W', nid.typ, "interpolation must be a way")
 
 486     cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
 
 487                    FROM location_property_osmline
 
 488                    WHERE osm_id = %s AND startnumber IS NOT NULL""",
 
 495     todo = list(range(len(list(context.table))))
 
 498             row = context.table[i]
 
 499             if (int(row['start']) == res['startnumber']
 
 500                 and int(row['end']) == res['endnumber']):
 
 504             assert False, "Unexpected row %s" % (str(res))
 
 506         for h in row.headings:
 
 507             if h in ('start', 'end'):
 
 509             elif h == 'parent_place_id':
 
 510                 compare_place_id(row[h], res[h], h, context)
 
 512                 assert_db_column(res, h, row[h], context)
 
 517 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
 
 518 def check_placex_has_entry(context, table, oid):
 
 519     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 520     nid = NominatimID(oid)
 
 521     where, params = nid.table_select()
 
 522     cur.execute("SELECT * FROM %s where %s" % (table, where), params)
 
 526 @then("search_name has no entry for (?P<oid>.*)")
 
 527 def check_search_name_has_entry(context, oid):
 
 528     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 529     pid = NominatimID(oid).get_place_id(cur)
 
 530     cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))