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):
 
 116         cur = self.conn.cursor()
 
 117         cur.execute("""SELECT osm_type, osm_id, class
 
 118                        FROM placex WHERE place_id = %s""",
 
 120         eq_(1, cur.rowcount, "No entry found for place id %s" % self.pid)
 
 122         return "%s%s:%s" % cur.fetchone()
 
 124 def compare_place_id(expected, result, column, context):
 
 127             LazyFmt("Bad place id in column %s. Expected: 0, got: %s.",
 
 128                     column, PlaceObjName(result, context.db)))
 
 129     elif expected == '-':
 
 130         assert_is_none(result,
 
 131                 LazyFmt("bad place id in column %s: %s.",
 
 132                         column, PlaceObjName(result, context.db)))
 
 134         eq_(NominatimID(expected).get_place_id(context.db.cursor()), result,
 
 135             LazyFmt("Bad place id in column %s. Expected: %s, got: %s.",
 
 136                     column, expected, PlaceObjName(result, context.db)))
 
 138 def check_database_integrity(context):
 
 139     """ Check some generic constraints on the tables.
 
 141     # place_addressline should not have duplicate (place_id, address_place_id)
 
 142     cur = context.db.cursor()
 
 143     cur.execute("""SELECT count(*) FROM
 
 144                     (SELECT place_id, address_place_id, count(*) as c
 
 145                      FROM place_addressline GROUP BY place_id, address_place_id) x
 
 147     eq_(0, cur.fetchone()[0], "Duplicates found in place_addressline")
 
 151     """ Splits a unique identifier for places into its components.
 
 152         As place_ids cannot be used for testing, we use a unique
 
 153         identifier instead that is of the form <osmtype><osmid>[:<class>].
 
 156     id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
 
 158     def __init__(self, oid):
 
 159         self.typ = self.oid = self.cls = None
 
 162             m = self.id_regex.fullmatch(oid)
 
 163             assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
 
 165             self.typ = m.group('tp')
 
 166             self.oid = m.group('id')
 
 167             self.cls = m.group('cls')
 
 171             return self.typ + self.oid
 
 173         return '%s%d:%s' % (self.typ, self.oid, self.cls)
 
 175     def table_select(self):
 
 176         """ Return where clause and parameter list to select the object
 
 177             from a Nominatim table.
 
 179         where = 'osm_type = %s and osm_id = %s'
 
 180         params = [self.typ, self. oid]
 
 182         if self.cls is not None:
 
 183             where += ' and class = %s'
 
 184             params.append(self.cls)
 
 188     def get_place_id(self, cur):
 
 189         where, params = self.table_select()
 
 190         cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
 
 192             "Expected exactly 1 entry in placex for %s found %s"
 
 193               % (str(self), cur.rowcount))
 
 195         return cur.fetchone()[0]
 
 198 def assert_db_column(row, column, value, context):
 
 199     if column == 'object':
 
 202     if column.startswith('centroid'):
 
 203         if value == 'in geometry':
 
 204             query = """SELECT ST_Within(ST_SetSRID(ST_Point({}, {}), 4326),
 
 205                                         ST_SetSRID('{}'::geometry, 4326))""".format(
 
 206                       row['cx'], row['cy'], row['geomtxt'])
 
 207             cur = context.db.cursor()
 
 209             eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
 
 211             fac = float(column[9:]) if column.startswith('centroid*') else 1.0
 
 212             x, y = value.split(' ')
 
 213             assert_almost_equal(float(x) * fac, row['cx'], msg="Bad x coordinate")
 
 214             assert_almost_equal(float(y) * fac, row['cy'], msg="Bad y coordinate")
 
 215     elif column == 'geometry':
 
 216         geom = context.osm.parse_geometry(value, context.scene)
 
 217         cur = context.db.cursor()
 
 218         query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
 
 219                  geom, row['geomtxt'],)
 
 221         eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
 
 223         assert_is_none(row[column], "Row %s" % column)
 
 225         eq_(value, str(row[column]),
 
 226             "Row '%s': expected: %s, got: %s"
 
 227             % (column, value, str(row[column])))
 
 230 ################################ STEPS ##################################
 
 232 @given(u'the scene (?P<scene>.+)')
 
 233 def set_default_scene(context, scene):
 
 234     context.scene = scene
 
 236 @given("the (?P<named>named )?places")
 
 237 def add_data_to_place_table(context, named):
 
 238     cur = context.db.cursor()
 
 239     cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
 
 240     for r in context.table:
 
 241         col = PlaceColumn(context, named is not None)
 
 247     cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
 
 251 @given("the relations")
 
 252 def add_data_to_planet_relations(context):
 
 253     cur = context.db.cursor()
 
 254     for r in context.table:
 
 260             for m in r['members'].split(','):
 
 263                     parts.insert(last_node, int(mid.oid))
 
 267                     parts.insert(last_way, int(mid.oid))
 
 270                     parts.append(int(mid.oid))
 
 272                 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
 
 278             if h.startswith("tags+"):
 
 279                 tags.extend((h[5:], r[h]))
 
 281         cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
 
 282                        VALUES (%s, %s, %s, %s, %s, %s)""",
 
 283                     (r['id'], last_node, last_way, parts, members, tags))
 
 287 def add_data_to_planet_ways(context):
 
 288     cur = context.db.cursor()
 
 289     for r in context.table:
 
 292             if h.startswith("tags+"):
 
 293                 tags.extend((h[5:], r[h]))
 
 295         nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
 
 297         cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
 
 298                     (r['id'], nodes, tags))
 
 302 def import_and_index_data_from_place_table(context):
 
 303     context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
 
 304     cur = context.db.cursor()
 
 306         """insert into placex (osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry)
 
 307            select              osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry
 
 308            from place where not (class='place' and type='houses' and osm_type='W')""")
 
 310             """insert into location_property_osmline (osm_id, address, linegeo)
 
 311              SELECT osm_id, address, geometry from place
 
 312               WHERE class='place' and type='houses' and osm_type='W'
 
 313                     and ST_GeometryType(geometry) = 'ST_LineString'""")
 
 315     context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
 
 316     check_database_integrity(context)
 
 318 @when("updating places")
 
 319 def update_place_table(context):
 
 320     context.nominatim.run_setup_script(
 
 321         'create-functions', 'create-partition-functions', 'enable-diff-updates')
 
 322     cur = context.db.cursor()
 
 323     for r in context.table:
 
 324         col = PlaceColumn(context, False)
 
 334         context.nominatim.run_update_script('index')
 
 336         cur = context.db.cursor()
 
 337         cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
 
 338         if cur.rowcount == 0:
 
 341     check_database_integrity(context)
 
 343 @when("updating postcodes")
 
 344 def update_postcodes(context):
 
 345     context.nominatim.run_update_script('calculate-postcodes')
 
 347 @when("marking for delete (?P<oids>.*)")
 
 348 def delete_places(context, oids):
 
 349     context.nominatim.run_setup_script(
 
 350         'create-functions', 'create-partition-functions', 'enable-diff-updates')
 
 351     cur = context.db.cursor()
 
 352     for oid in oids.split(','):
 
 353         where, params = NominatimID(oid).table_select()
 
 354         cur.execute("DELETE FROM place WHERE " + where, params)
 
 358         context.nominatim.run_update_script('index')
 
 360         cur = context.db.cursor()
 
 361         cur.execute("SELECT 'a' FROM placex WHERE indexed_status != 0 LIMIT 1")
 
 362         if cur.rowcount == 0:
 
 365 @then("placex contains(?P<exact> exactly)?")
 
 366 def check_placex_contents(context, exact):
 
 367     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 369     expected_content = set()
 
 370     for row in context.table:
 
 371         nid = NominatimID(row['object'])
 
 372         where, params = nid.table_select()
 
 373         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
 
 374                        ST_X(centroid) as cx, ST_Y(centroid) as cy
 
 375                        FROM placex where %s""" % where,
 
 377         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
 
 381                 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
 
 382             for h in row.headings:
 
 383                 if h in ('extratags', 'address'):
 
 385                         assert_is_none(res[h])
 
 387                         vdict = eval('{' + row[h] + '}')
 
 388                         assert_equals(vdict, res[h])
 
 389                 elif h.startswith('name'):
 
 390                     name = h[5:] if h.startswith('name+') else 'name'
 
 391                     assert_in(name, res['name'])
 
 392                     eq_(res['name'][name], row[h])
 
 393                 elif h.startswith('extratags+'):
 
 394                     eq_(res['extratags'][h[10:]], row[h])
 
 395                 elif h.startswith('addr+'):
 
 397                         if res['address'] is not None:
 
 398                             assert_not_in(h[5:], res['address'])
 
 400                         assert_in(h[5:], res['address'], "column " + h)
 
 401                         assert_equals(res['address'][h[5:]], row[h],
 
 403                 elif h in ('linked_place_id', 'parent_place_id'):
 
 404                     compare_place_id(row[h], res[h], h, context)
 
 406                     assert_db_column(res, h, row[h], context)
 
 409         cur.execute('SELECT osm_type, osm_id, class from placex')
 
 410         eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
 
 414 @then("place contains(?P<exact> exactly)?")
 
 415 def check_placex_contents(context, exact):
 
 416     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 418     expected_content = set()
 
 419     for row in context.table:
 
 420         nid = NominatimID(row['object'])
 
 421         where, params = nid.table_select()
 
 422         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
 
 423                        ST_GeometryType(geometry) as geometrytype
 
 424                        FROM place where %s""" % where,
 
 426         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
 
 430                 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
 
 431             for h in row.headings:
 
 432                 msg = "%s: %s" % (row['object'], h)
 
 433                 if h in ('name', 'extratags', 'address'):
 
 435                         assert_is_none(res[h], msg)
 
 437                         vdict = eval('{' + row[h] + '}')
 
 438                         assert_equals(vdict, res[h], msg)
 
 439                 elif h.startswith('name+'):
 
 440                     assert_equals(res['name'][h[5:]], row[h], msg)
 
 441                 elif h.startswith('extratags+'):
 
 442                     assert_equals(res['extratags'][h[10:]], row[h], msg)
 
 443                 elif h.startswith('addr+'):
 
 445                         if res['address']  is not None:
 
 446                             assert_not_in(h[5:], res['address'])
 
 448                         assert_equals(res['address'][h[5:]], row[h], msg)
 
 449                 elif h in ('linked_place_id', 'parent_place_id'):
 
 450                     compare_place_id(row[h], res[h], h, context)
 
 452                     assert_db_column(res, h, row[h], context)
 
 455         cur.execute('SELECT osm_type, osm_id, class from place')
 
 456         eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
 
 460 @then("search_name contains(?P<exclude> not)?")
 
 461 def check_search_name_contents(context, exclude):
 
 462     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 464     for row in context.table:
 
 465         pid = NominatimID(row['object']).get_place_id(cur)
 
 466         cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
 
 467                        FROM search_name WHERE place_id = %s""", (pid, ))
 
 468         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
 
 471             for h in row.headings:
 
 472                 if h in ('name_vector', 'nameaddress_vector'):
 
 473                     terms = [x.strip() for x in row[h].split(',') if not x.strip().startswith('#')]
 
 474                     words = [x.strip()[1:] for x in row[h].split(',') if x.strip().startswith('#')]
 
 475                     subcur = context.db.cursor()
 
 476                     subcur.execute(""" SELECT word_id, word_token
 
 477                                        FROM word, (SELECT unnest(%s::TEXT[]) as term) t
 
 478                                        WHERE word_token = make_standard_name(t.term)
 
 479                                              and class is null and country_code is null
 
 482                                        SELECT word_id, word_token
 
 483                                        FROM word, (SELECT unnest(%s::TEXT[]) as term) t
 
 484                                        WHERE word_token = ' ' || make_standard_name(t.term)
 
 485                                              and class is null and country_code is null
 
 490                         ok_(subcur.rowcount >= len(terms) + len(words),
 
 491                             "No word entry found for " + row[h] + ". Entries found: " + str(subcur.rowcount))
 
 494                             assert_not_in(wid[0], res[h],
 
 495                                           "Found term for %s/%s: %s" % (pid, h, wid[1]))
 
 497                             assert_in(wid[0], res[h],
 
 498                                       "Missing term for %s/%s: %s" % (pid, h, wid[1]))
 
 500                     assert_db_column(res, h, row[h], context)
 
 505 @then("location_postcode contains exactly")
 
 506 def check_location_postcode(context):
 
 507     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 509     cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
 
 510     eq_(cur.rowcount, len(list(context.table)),
 
 511         "Postcode table has %d rows, expected %d rows."
 
 512           % (cur.rowcount, len(list(context.table))))
 
 515     for row in context.table:
 
 516         for i in range(len(table)):
 
 517             if table[i]['country_code'] != row['country'] \
 
 518                     or table[i]['postcode'] != row['postcode']:
 
 520             for h in row.headings:
 
 521                 if h not in ('country', 'postcode'):
 
 522                     assert_db_column(table[i], h, row[h], context)
 
 524 @then("word contains(?P<exclude> not)?")
 
 525 def check_word_table(context, exclude):
 
 526     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 528     for row in context.table:
 
 531         for h in row.headings:
 
 532             wheres.append("%s = %%s" % h)
 
 533             values.append(row[h])
 
 534         cur.execute("SELECT * from word WHERE %s" % ' AND '.join(wheres), values)
 
 537                 "Row still in word table: %s" % '/'.join(values))
 
 539             assert_greater(cur.rowcount, 0,
 
 540                            "Row not in word table: %s" % '/'.join(values))
 
 542 @then("place_addressline contains")
 
 543 def check_place_addressline(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""",
 
 552         assert_less(0, cur.rowcount,
 
 553                     "No rows found for place %s and address %s"
 
 554                       % (row['object'], row['address']))
 
 557             for h in row.headings:
 
 558                 if h not in ('address', 'object'):
 
 559                     assert_db_column(res, h, row[h], context)
 
 563 @then("place_addressline doesn't contain")
 
 564 def check_place_addressline_exclude(context):
 
 565     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 567     for row in context.table:
 
 568         pid = NominatimID(row['object']).get_place_id(cur)
 
 569         apid = NominatimID(row['address']).get_place_id(cur)
 
 570         cur.execute(""" SELECT * FROM place_addressline
 
 571                         WHERE place_id = %s AND address_place_id = %s""",
 
 574             "Row found for place %s and address %s" % (row['object'], row['address']))
 
 578 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
 
 579 def check_location_property_osmline(context, oid, neg):
 
 580     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 581     nid = NominatimID(oid)
 
 583     eq_('W', nid.typ, "interpolation must be a way")
 
 585     cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
 
 586                    FROM location_property_osmline
 
 587                    WHERE osm_id = %s AND startnumber IS NOT NULL""",
 
 594     todo = list(range(len(list(context.table))))
 
 597             row = context.table[i]
 
 598             if (int(row['start']) == res['startnumber']
 
 599                 and int(row['end']) == res['endnumber']):
 
 603             assert False, "Unexpected row %s" % (str(res))
 
 605         for h in row.headings:
 
 606             if h in ('start', 'end'):
 
 608             elif h == 'parent_place_id':
 
 609                 compare_place_id(row[h], res[h], h, context)
 
 611                 assert_db_column(res, h, row[h], context)
 
 616 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
 
 617 def check_placex_has_entry(context, table, oid):
 
 618     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 619     nid = NominatimID(oid)
 
 620     where, params = nid.table_select()
 
 621     cur.execute("SELECT * FROM %s where %s" % (table, where), params)
 
 625 @then("search_name has no entry for (?P<oid>.*)")
 
 626 def check_search_name_has_entry(context, oid):
 
 627     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
 628     pid = NominatimID(oid).get_place_id(cur)
 
 629     cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))