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)
 
  25         elif key in ('name', 'address', 'extratags'):
 
  26             self.columns[key] = eval('{' + value + '}')
 
  28             assert_in(key, ('class', 'type'))
 
  29             self.columns[key] = None if value == '' else value
 
  31     def set_key_name(self, value):
 
  32         self.add_hstore('name', 'name', value)
 
  34     def set_key_osm(self, value):
 
  35         assert_in(value[0], 'NRW')
 
  36         ok_(value[1:].isdigit())
 
  38         self.columns['osm_type'] = value[0]
 
  39         self.columns['osm_id'] = int(value[1:])
 
  41     def set_key_admin(self, value):
 
  42         self.columns['admin_level'] = int(value)
 
  44     def set_key_housenr(self, value):
 
  46             self.add_hstore('address', 'housenumber', value)
 
  48     def set_key_postcode(self, value):
 
  50             self.add_hstore('address', 'postcode', value)
 
  52     def set_key_street(self, value):
 
  54             self.add_hstore('address', 'street', value)
 
  56     def set_key_addr_place(self, value):
 
  58             self.add_hstore('address', 'place', value)
 
  60     def set_key_country(self, value):
 
  62             self.add_hstore('address', 'country', value)
 
  64     def set_key_geometry(self, value):
 
  65         self.geometry = self.context.osm.parse_geometry(value, self.context.scene)
 
  66         assert_is_not_none(self.geometry)
 
  68     def add_hstore(self, column, key, value):
 
  69         if column in self.columns:
 
  70             self.columns[column][key] = value
 
  72             self.columns[column] = { key : value }
 
  74     def db_insert(self, cursor):
 
  75         assert_in('osm_type', self.columns)
 
  76         if self.force_name and 'name' not in self.columns:
 
  77             self.add_hstore('name', 'name', ''.join(random.choice(string.printable)
 
  78                                            for _ in range(int(random.random()*30))))
 
  80         if self.columns['osm_type'] == 'N' and self.geometry is None:
 
  81             pt = self.context.osm.grid_node(self.columns['osm_id'])
 
  83                 pt = (random.random()*360 - 180, random.random()*180 - 90)
 
  85             self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % pt
 
  87             assert_is_not_none(self.geometry, "Geometry missing")
 
  88         query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
 
  89                      ','.join(self.columns.keys()),
 
  90                      ','.join(['%s' for x in range(len(self.columns))]),
 
  92         cursor.execute(query, list(self.columns.values()))
 
  94 class LazyFmt(object):
 
  96     def __init__(self, fmtstr, *args):
 
 101         return self.fmt % self.args
 
 103 class PlaceObjName(object):
 
 105     def __init__(self, placeid, conn):
 
 113         cur = self.conn.cursor()
 
 114         cur.execute("""SELECT osm_type, osm_id, class
 
 115                        FROM placex WHERE place_id = %s""",
 
 117         eq_(1, cur.rowcount, "No entry found for place id %s" % self.pid)
 
 119         return "%s%s:%s" % cur.fetchone()
 
 121 def compare_place_id(expected, result, column, context):
 
 124             LazyFmt("Bad place id in column %s. Expected: 0, got: %s.",
 
 125                     column, PlaceObjName(result, context.db)))
 
 126     elif expected == '-':
 
 127         assert_is_none(result,
 
 128                 LazyFmt("bad place id in column %s: %s.",
 
 129                         column, PlaceObjName(result, context.db)))
 
 131         eq_(NominatimID(expected).get_place_id(context.db.cursor()), result,
 
 132             LazyFmt("Bad place id in column %s. Expected: %s, got: %s.",
 
 133                     column, expected, PlaceObjName(result, context.db)))
 
 135 def check_database_integrity(context):
 
 136     """ Check some generic constraints on the tables.
 
 138     # place_addressline should not have duplicate (place_id, address_place_id)
 
 139     cur = context.db.cursor()
 
 140     cur.execute("""SELECT count(*) FROM
 
 141                     (SELECT place_id, address_place_id, count(*) as c
 
 142                      FROM place_addressline GROUP BY place_id, address_place_id) x
 
 144     eq_(0, cur.fetchone()[0], "Duplicates found in place_addressline")
 
 148     """ Splits a unique identifier for places into its components.
 
 149         As place_ids cannot be used for testing, we use a unique
 
 150         identifier instead that is of the form <osmtype><osmid>[:<class>].
 
 153     id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
 
 155     def __init__(self, oid):
 
 156         self.typ = self.oid = self.cls = None
 
 159             m = self.id_regex.fullmatch(oid)
 
 160             assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
 
 162             self.typ = m.group('tp')
 
 163             self.oid = m.group('id')
 
 164             self.cls = m.group('cls')
 
 168             return self.typ + self.oid
 
 170         return '%s%d:%s' % (self.typ, self.oid, self.cls)
 
 172     def table_select(self):
 
 173         """ Return where clause and parameter list to select the object
 
 174             from a Nominatim table.
 
 176         where = 'osm_type = %s and osm_id = %s'
 
 177         params = [self.typ, self. oid]
 
 179         if self.cls is not None:
 
 180             where += ' and class = %s'
 
 181             params.append(self.cls)
 
 185     def get_place_id(self, cur):
 
 186         where, params = self.table_select()
 
 187         cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
 
 189             "Expected exactly 1 entry in placex for %s found %s"
 
 190               % (str(self), cur.rowcount))
 
 192         return cur.fetchone()[0]
 
 195 def assert_db_column(row, column, value, context):
 
 196     if column == 'object':
 
 199     if column.startswith('centroid'):
 
 200         fac = float(column[9:]) if column.startswith('centroid*') else 1.0
 
 201         x, y = value.split(' ')
 
 202         assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
 
 203         assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
 
 204     elif column == 'geometry':
 
 205         geom = context.osm.parse_geometry(value, context.scene)
 
 206         cur = context.db.cursor()
 
 207         query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
 
 208                  geom, row['geomtxt'],)
 
 210         eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
 
 212         assert_is_none(row[column], "Row %s" % column)
 
 214         eq_(value, str(row[column]),
 
 215             "Row '%s': expected: %s, got: %s"
 
 216             % (column, value, str(row[column])))
 
 219 ################################ STEPS ##################################
 
 221 @given(u'the scene (?P<scene>.+)')
 
 222 def set_default_scene(context, scene):
 
 223     context.scene = scene
 
 225 @given("the (?P<named>named )?places")
 
 226 def add_data_to_place_table(context, named):
 
 227     cur = context.db.cursor()
 
 228     cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
 
 229     for r in context.table:
 
 230         col = PlaceColumn(context, named is not None)
 
 236     cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
 
 240 @given("the relations")
 
 241 def add_data_to_planet_relations(context):
 
 242     cur = context.db.cursor()
 
 243     for r in context.table:
 
 249             for m in r['members'].split(','):
 
 252                     parts.insert(last_node, int(mid.oid))
 
 256                     parts.insert(last_way, int(mid.oid))
 
 259                     parts.append(int(mid.oid))
 
 261                 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
 
 267             if h.startswith("tags+"):
 
 268                 tags.extend((h[5:], r[h]))
 
 270         cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
 
 271                        VALUES (%s, %s, %s, %s, %s, %s)""",
 
 272                     (r['id'], last_node, last_way, parts, members, tags))
 
 276 def add_data_to_planet_ways(context):
 
 277     cur = context.db.cursor()
 
 278     for r in context.table:
 
 281             if h.startswith("tags+"):
 
 282                 tags.extend((h[5:], r[h]))
 
 284         nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
 
 286         cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
 
 287                     (r['id'], nodes, tags))
 
 291 def import_and_index_data_from_place_table(context):
 
 292     context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
 
 293     cur = context.db.cursor()
 
 295         """insert into placex (osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry)
 
 296            select              osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry
 
 297            from place where not (class='place' and type='houses' and osm_type='W')""")
 
 299             """insert into location_property_osmline (osm_id, address, linegeo)
 
 300              SELECT osm_id, address, geometry from place
 
 301               WHERE class='place' and type='houses' and osm_type='W'
 
 302                     and ST_GeometryType(geometry) = 'ST_LineString'""")
 
 304     context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
 
 305     check_database_integrity(context)
 
 307 @when("updating places")
 
 308 def update_place_table(context):
 
 309     context.nominatim.run_setup_script(
 
 310         'create-functions', 'create-partition-functions', 'enable-diff-updates')
 
 311     cur = context.db.cursor()
 
 312     for r in context.table:
 
 313         col = PlaceColumn(context, False)
 
 323         context.nominatim.run_update_script('index')
 
 325         cur = context.db.cursor()
 
 326         cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
 
 327         if cur.rowcount == 0:
 
 330     check_database_integrity(context)
 
 332 @when("updating postcodes")
 
 333 def update_postcodes(context):
 
 334     context.nominatim.run_update_script('calculate-postcodes')
 
 336 @when("marking for delete (?P<oids>.*)")
 
 337 def delete_places(context, oids):
 
 338     context.nominatim.run_setup_script(
 
 339         'create-functions', 'create-partition-functions', 'enable-diff-updates')
 
 340     cur = context.db.cursor()
 
 341     for oid in oids.split(','):
 
 342         where, params = NominatimID(oid).table_select()
 
 343         cur.execute("DELETE FROM place WHERE " + where, params)
 
 347         context.nominatim.run_update_script('index')
 
 349         cur = context.db.cursor()
 
 350         cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
 
 351         if cur.rowcount == 0:
 
 354 @then("placex contains(?P<exact> exactly)?")
 
 355 def check_placex_contents(context, exact):
 
 356     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 358     expected_content = set()
 
 359     for row in context.table:
 
 360         nid = NominatimID(row['object'])
 
 361         where, params = nid.table_select()
 
 362         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
 
 363                        ST_X(centroid) as cx, ST_Y(centroid) as cy
 
 364                        FROM placex where %s""" % where,
 
 366         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
 
 370                 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
 
 371             for h in row.headings:
 
 372                 if h in ('extratags', 'address'):
 
 374                         assert_is_none(res[h])
 
 376                         vdict = eval('{' + row[h] + '}')
 
 377                         assert_equals(vdict, res[h])
 
 378                 elif h.startswith('name'):
 
 379                     name = h[5:] if h.startswith('name+') else 'name'
 
 380                     assert_in(name, res['name'])
 
 381                     eq_(res['name'][name], row[h])
 
 382                 elif h.startswith('extratags+'):
 
 383                     eq_(res['extratags'][h[10:]], row[h])
 
 384                 elif h.startswith('addr+'):
 
 386                         if res['address'] is not None:
 
 387                             assert_not_in(h[5:], res['address'])
 
 389                         assert_in(h[5:], res['address'], "column " + h)
 
 390                         assert_equals(res['address'][h[5:]], row[h],
 
 392                 elif h in ('linked_place_id', 'parent_place_id'):
 
 393                     compare_place_id(row[h], res[h], h, context)
 
 395                     assert_db_column(res, h, row[h], context)
 
 398         cur.execute('SELECT osm_type, osm_id, class from placex')
 
 399         eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
 
 403 @then("place contains(?P<exact> exactly)?")
 
 404 def check_placex_contents(context, exact):
 
 405     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 407     expected_content = set()
 
 408     for row in context.table:
 
 409         nid = NominatimID(row['object'])
 
 410         where, params = nid.table_select()
 
 411         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
 
 412                        ST_GeometryType(geometry) as geometrytype
 
 413                        FROM place where %s""" % where,
 
 415         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
 
 419                 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
 
 420             for h in row.headings:
 
 421                 msg = "%s: %s" % (row['object'], h)
 
 422                 if h in ('name', 'extratags', 'address'):
 
 424                         assert_is_none(res[h], msg)
 
 426                         vdict = eval('{' + row[h] + '}')
 
 427                         assert_equals(vdict, res[h], msg)
 
 428                 elif h.startswith('name+'):
 
 429                     assert_equals(res['name'][h[5:]], row[h], msg)
 
 430                 elif h.startswith('extratags+'):
 
 431                     assert_equals(res['extratags'][h[10:]], row[h], msg)
 
 432                 elif h.startswith('addr+'):
 
 434                         if res['address']  is not None:
 
 435                             assert_not_in(h[5:], res['address'])
 
 437                         assert_equals(res['address'][h[5:]], row[h], msg)
 
 438                 elif h in ('linked_place_id', 'parent_place_id'):
 
 439                     compare_place_id(row[h], res[h], h, context)
 
 441                     assert_db_column(res, h, row[h], context)
 
 444         cur.execute('SELECT osm_type, osm_id, class from place')
 
 445         eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
 
 449 @then("search_name contains(?P<exclude> not)?")
 
 450 def check_search_name_contents(context, exclude):
 
 451     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 453     for row in context.table:
 
 454         pid = NominatimID(row['object']).get_place_id(cur)
 
 455         cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
 
 456                        FROM search_name WHERE place_id = %s""", (pid, ))
 
 457         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
 
 460             for h in row.headings:
 
 461                 if h in ('name_vector', 'nameaddress_vector'):
 
 462                     terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
 
 463                     subcur = context.db.cursor()
 
 464                     subcur.execute("""SELECT word_id, word_token
 
 465                                       FROM word, (SELECT unnest(%s) as term) t
 
 466                                       WHERE word_token = make_standard_name(t.term)""",
 
 469                         ok_(subcur.rowcount >= len(terms),
 
 470                             "No word entry found for " + row[h])
 
 473                             assert_not_in(wid[0], res[h],
 
 474                                           "Found term for %s/%s: %s" % (pid, h, wid[1]))
 
 476                             assert_in(wid[0], res[h],
 
 477                                       "Missing term for %s/%s: %s" % (pid, h, wid[1]))
 
 479                     assert_db_column(res, h, row[h], context)
 
 484 @then("location_postcode contains exactly")
 
 485 def check_location_postcode(context):
 
 486     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 488     cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
 
 489     eq_(cur.rowcount, len(list(context.table)),
 
 490         "Postcode table has %d rows, expected %d rows."
 
 491           % (cur.rowcount, len(list(context.table))))
 
 494     for row in context.table:
 
 495         for i in range(len(table)):
 
 496             if table[i]['country_code'] != row['country'] \
 
 497                     or table[i]['postcode'] != row['postcode']:
 
 499             for h in row.headings:
 
 500                 if h not in ('country', 'postcode'):
 
 501                     assert_db_column(table[i], h, row[h], context)
 
 503 @then("word contains(?P<exclude> not)?")
 
 504 def check_word_table(context, exclude):
 
 505     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 507     for row in context.table:
 
 510         for h in row.headings:
 
 511             wheres.append("%s = %%s" % h)
 
 512             values.append(row[h])
 
 513         cur.execute("SELECT * from word WHERE %s" % ' AND '.join(wheres), values)
 
 516                 "Row still in word table: %s" % '/'.join(values))
 
 518             assert_greater(cur.rowcount, 0,
 
 519                            "Row not in word table: %s" % '/'.join(values))
 
 521 @then("place_addressline contains")
 
 522 def check_place_addressline(context):
 
 523     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 525     for row in context.table:
 
 526         pid = NominatimID(row['object']).get_place_id(cur)
 
 527         apid = NominatimID(row['address']).get_place_id(cur)
 
 528         cur.execute(""" SELECT * FROM place_addressline
 
 529                         WHERE place_id = %s AND address_place_id = %s""",
 
 531         assert_less(0, cur.rowcount,
 
 532                     "No rows found for place %s and address %s"
 
 533                       % (row['object'], row['address']))
 
 536             for h in row.headings:
 
 537                 if h not in ('address', 'object'):
 
 538                     assert_db_column(res, h, row[h], context)
 
 542 @then("place_addressline doesn't contain")
 
 543 def check_place_addressline_exclude(context):
 
 544     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 546     for row in context.table:
 
 547         pid = NominatimID(row['object']).get_place_id(cur)
 
 548         apid = NominatimID(row['address']).get_place_id(cur)
 
 549         cur.execute(""" SELECT * FROM place_addressline
 
 550                         WHERE place_id = %s AND address_place_id = %s""",
 
 553             "Row found for place %s and address %s" % (row['object'], row['address']))
 
 557 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
 
 558 def check_location_property_osmline(context, oid, neg):
 
 559     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 560     nid = NominatimID(oid)
 
 562     eq_('W', nid.typ, "interpolation must be a way")
 
 564     cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
 
 565                    FROM location_property_osmline
 
 566                    WHERE osm_id = %s AND startnumber IS NOT NULL""",
 
 573     todo = list(range(len(list(context.table))))
 
 576             row = context.table[i]
 
 577             if (int(row['start']) == res['startnumber']
 
 578                 and int(row['end']) == res['endnumber']):
 
 582             assert False, "Unexpected row %s" % (str(res))
 
 584         for h in row.headings:
 
 585             if h in ('start', 'end'):
 
 587             elif h == 'parent_place_id':
 
 588                 compare_place_id(row[h], res[h], h, context)
 
 590                 assert_db_column(res, h, row[h], context)
 
 595 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
 
 596 def check_placex_has_entry(context, table, oid):
 
 597     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 598     nid = NominatimID(oid)
 
 599     where, params = nid.table_select()
 
 600     cur.execute("SELECT * FROM %s where %s" % (table, where), params)
 
 604 @then("search_name has no entry for (?P<oid>.*)")
 
 605 def check_search_name_has_entry(context, oid):
 
 606     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 607     pid = NominatimID(oid).get_place_id(cur)
 
 608     cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))