1 """ Steps that run search queries.
 
   3     Queries may either be run directly via PHP using the query script
 
   4     or via the HTTP interface.
 
  12 from tidylib import tidy_document
 
  13 import xml.etree.ElementTree as ET
 
  15 from urllib.parse import urlencode
 
  16 from collections import OrderedDict
 
  17 from nose.tools import * # for assert functions
 
  19 logger = logging.getLogger(__name__)
 
  22     'HTTP_HOST' : 'localhost',
 
  23     'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
 
  24     'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
 
  25     'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
 
  26     'HTTP_CONNECTION' : 'keep-alive',
 
  27     'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
 
  28     'SERVER_SOFTWARE' : 'Nominatim test',
 
  29     'SERVER_NAME' : 'localhost',
 
  30     'SERVER_ADDR' : '127.0.1.1',
 
  32     'REMOTE_ADDR' : '127.0.0.1',
 
  33     'DOCUMENT_ROOT' : '/var/www',
 
  34     'REQUEST_SCHEME' : 'http',
 
  35     'CONTEXT_PREFIX' : '/',
 
  36     'SERVER_ADMIN' : 'webmaster@localhost',
 
  37     'REMOTE_PORT' : '49319',
 
  38     'GATEWAY_INTERFACE' : 'CGI/1.1',
 
  39     'SERVER_PROTOCOL' : 'HTTP/1.1',
 
  40     'REQUEST_METHOD' : 'GET',
 
  41     'REDIRECT_STATUS' : 'CGI'
 
  45 def compare(operator, op1, op2):
 
  46     if operator == 'less than':
 
  48     elif operator == 'more than':
 
  50     elif operator == 'exactly':
 
  52     elif operator == 'at least':
 
  54     elif operator == 'at most':
 
  57         raise Exception("unknown operator '%s'" % operator)
 
  59 class GenericResponse(object):
 
  61     def match_row(self, row):
 
  62         if 'ID' in row.headings:
 
  63             todo = [int(row['ID'])]
 
  65             todo = range(len(self.result))
 
  69             for h in row.headings:
 
  73                     assert_equal(res['osm_type'], row[h][0])
 
  74                     assert_equal(res['osm_id'], int(row[h][1:]))
 
  76                     x, y = row[h].split(' ')
 
  77                     assert_almost_equal(float(y), float(res['lat']))
 
  78                     assert_almost_equal(float(x), float(res['lon']))
 
  79                 elif row[h].startswith("^"):
 
  81                     assert_is_not_none(re.fullmatch(row[h], res[h]),
 
  82                                        "attribute '%s': expected: '%s', got '%s'"
 
  83                                           % (h, row[h], res[h]))
 
  86                     assert_equal(str(res[h]), str(row[h]))
 
  88     def property_list(self, prop):
 
  89         return [ x[prop] for x in self.result ]
 
  92 class SearchResponse(GenericResponse):
 
  94     def __init__(self, page, fmt='json', errorcode=200):
 
  97         self.errorcode = errorcode
 
 102             getattr(self, 'parse_' + fmt)()
 
 104     def parse_json(self):
 
 105         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
 
 110             self.header['json_func'] = m.group(1)
 
 111         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
 
 113     def parse_geojson(self):
 
 115         self.result = geojson_results_to_json_results(self.result)
 
 117     def parse_geocodejson(self):
 
 119         if self.result is not None:
 
 120             self.result = [r['geocoding'] for r in self.result]
 
 122     def parse_html(self):
 
 123         content, errors = tidy_document(self.page,
 
 124                                         options={'char-encoding' : 'utf8'})
 
 125         #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
 
 128         b = content.find('nominatim_results =')
 
 129         e = content.find('</script>')
 
 130         if b >= 0 and e >= 0:
 
 131             content = content[b:e]
 
 133             b = content.find('[')
 
 134             e = content.rfind(']')
 
 135             if b >= 0 and e >= 0:
 
 136                 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict)\
 
 137                                   .decode(content[b:e+1])
 
 140         et = ET.fromstring(self.page)
 
 142         self.header = dict(et.attrib)
 
 145             assert_equal(child.tag, "place")
 
 146             self.result.append(dict(child.attrib))
 
 150                 if sub.tag == 'extratags':
 
 151                     self.result[-1]['extratags'] = {}
 
 153                         self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 154                 elif sub.tag == 'namedetails':
 
 155                     self.result[-1]['namedetails'] = {}
 
 157                         self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
 
 158                 elif sub.tag in ('geokml'):
 
 159                     self.result[-1][sub.tag] = True
 
 161                     address[sub.tag] = sub.text
 
 164                 self.result[-1]['address'] = address
 
 167 class ReverseResponse(GenericResponse):
 
 169     def __init__(self, page, fmt='json', errorcode=200):
 
 172         self.errorcode = errorcode
 
 177             getattr(self, 'parse_' + fmt)()
 
 179     def parse_html(self):
 
 180         content, errors = tidy_document(self.page,
 
 181                                         options={'char-encoding' : 'utf8'})
 
 182         #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
 
 184         b = content.find('nominatim_results =')
 
 185         e = content.find('</script>')
 
 186         content = content[b:e]
 
 187         b = content.find('[')
 
 188         e = content.rfind(']')
 
 190         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
 
 192     def parse_json(self):
 
 193         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
 
 198             self.header['json_func'] = m.group(1)
 
 199         self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)]
 
 201     def parse_geojson(self):
 
 203         if 'error' in self.result:
 
 205         self.result = geojson_results_to_json_results(self.result[0])
 
 207     def parse_geocodejson(self):
 
 209         if self.result is not None:
 
 210             self.result = [r['geocoding'] for r in self.result]
 
 213         et = ET.fromstring(self.page)
 
 215         self.header = dict(et.attrib)
 
 219             if child.tag == 'result':
 
 220                 eq_(0, len(self.result), "More than one result in reverse result")
 
 221                 self.result.append(dict(child.attrib))
 
 222             elif child.tag == 'addressparts':
 
 225                     address[sub.tag] = sub.text
 
 226                 self.result[0]['address'] = address
 
 227             elif child.tag == 'extratags':
 
 228                 self.result[0]['extratags'] = {}
 
 230                     self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 231             elif child.tag == 'namedetails':
 
 232                 self.result[0]['namedetails'] = {}
 
 234                     self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
 
 235             elif child.tag in ('geokml'):
 
 236                 self.result[0][child.tag] = True
 
 238                 assert child.tag == 'error', \
 
 239                         "Unknown XML tag %s on page: %s" % (child.tag, self.page)
 
 242 class DetailsResponse(GenericResponse):
 
 244     def __init__(self, page, fmt='json', errorcode=200):
 
 247         self.errorcode = errorcode
 
 252             getattr(self, 'parse_' + fmt)()
 
 254     def parse_html(self):
 
 255         content, errors = tidy_document(self.page,
 
 256                                         options={'char-encoding' : 'utf8'})
 
 259     def parse_json(self):
 
 260         self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
 
 263 class StatusResponse(GenericResponse):
 
 265     def __init__(self, page, fmt='text', errorcode=200):
 
 268         self.errorcode = errorcode
 
 270         if errorcode == 200 and fmt != 'text':
 
 271             getattr(self, 'parse_' + fmt)()
 
 273     def parse_json(self):
 
 274         self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
 
 277 def geojson_result_to_json_result(geojson_result):
 
 278     result = geojson_result['properties']
 
 279     result['geojson'] = geojson_result['geometry']
 
 280     if 'bbox' in geojson_result:
 
 281         # bbox is  minlon, minlat, maxlon, maxlat
 
 282         # boundingbox is minlat, maxlat, minlon, maxlon
 
 283         result['boundingbox'] = [
 
 284                                     geojson_result['bbox'][1],
 
 285                                     geojson_result['bbox'][3],
 
 286                                     geojson_result['bbox'][0],
 
 287                                     geojson_result['bbox'][2]
 
 292 def geojson_results_to_json_results(geojson_results):
 
 293     if 'error' in geojson_results:
 
 295     return list(map(geojson_result_to_json_result, geojson_results['features']))
 
 298 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
 
 299 def query_cmd(context, query, dups):
 
 300     """ Query directly via PHP script.
 
 302     cmd = ['/usr/bin/env', 'php']
 
 303     cmd.append(os.path.join(context.nominatim.build_dir, 'utils', 'query.php'))
 
 305         cmd.extend(['--search', query])
 
 306     # add more parameters in table form
 
 308         for h in context.table.headings:
 
 309             value = context.table[0][h].strip()
 
 311                 cmd.extend(('--' + h, value))
 
 314         cmd.extend(('--dedupe', '0'))
 
 316     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
 
 317                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
 318     (outp, err) = proc.communicate()
 
 320     assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
 
 322     context.response = SearchResponse(outp.decode('utf-8'), 'json')
 
 324 def send_api_query(endpoint, params, fmt, context):
 
 326         params['format'] = fmt.strip()
 
 328         if context.table.headings[0] == 'param':
 
 329             for line in context.table:
 
 330                 params[line['param']] = line['value']
 
 332             for h in context.table.headings:
 
 333                 params[h] = context.table[0][h]
 
 335     env = dict(BASE_SERVER_ENV)
 
 336     env['QUERY_STRING'] = urlencode(params)
 
 338     env['SCRIPT_NAME'] = '/%s.php' % endpoint
 
 339     env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
 
 340     env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
 
 341     env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
 
 343     env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
 
 345     logger.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
 
 347     if hasattr(context, 'http_headers'):
 
 348         env.update(context.http_headers)
 
 350     cmd = ['/usr/bin/env', 'php-cgi', '-f']
 
 351     if context.nominatim.code_coverage_path:
 
 352         env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
 
 353         env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
 
 354         env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
 
 355         env['SCRIPT_FILENAME'] = \
 
 356                 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
 
 357         cmd.append(env['SCRIPT_FILENAME'])
 
 358         env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
 
 360         cmd.append(env['SCRIPT_FILENAME'])
 
 362     for k,v in params.items():
 
 363         cmd.append("%s=%s" % (k, v))
 
 365     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
 
 366                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
 368     (outp, err) = proc.communicate()
 
 369     outp = outp.decode('utf-8')
 
 370     err = err.decode("utf-8")
 
 372     logger.debug("Result: \n===============================\n"
 
 373                  + outp + "\n===============================\n")
 
 375     assert_equals(0, proc.returncode,
 
 376                   "%s failed with message: %s" % (
 
 377                       os.path.basename(env['SCRIPT_FILENAME']),
 
 380     assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
 
 382     if outp.startswith('Status: '):
 
 383         status = int(outp[8:11])
 
 387     content_start = outp.find('\r\n\r\n')
 
 389     return outp[content_start + 4:], status
 
 391 @given(u'the HTTP header')
 
 392 def add_http_header(context):
 
 393     if not hasattr(context, 'http_headers'):
 
 394         context.http_headers = {}
 
 396     for h in context.table.headings:
 
 397         envvar = 'HTTP_' + h.upper().replace('-', '_')
 
 398         context.http_headers[envvar] = context.table[0][h]
 
 401 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
 
 402 def website_search_request(context, fmt, query, addr):
 
 407         params['addressdetails'] = '1'
 
 409     outp, status = send_api_query('search', params, fmt, context)
 
 413     elif fmt == 'jsonv2 ':
 
 418     context.response = SearchResponse(outp, outfmt, status)
 
 420 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
 
 421 def website_reverse_request(context, fmt, lat, lon):
 
 428     outp, status = send_api_query('reverse', params, fmt, context)
 
 432     elif fmt == 'jsonv2 ':
 
 437     context.response = ReverseResponse(outp, outfmt, status)
 
 439 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
 
 440 def website_details_request(context, fmt, query):
 
 442     if query[0] in 'NWR':
 
 443         params['osmtype'] = query[0]
 
 444         params['osmid'] = query[1:]
 
 446         params['place_id'] = query
 
 447     outp, status = send_api_query('details', params, fmt, context)
 
 454     context.response = DetailsResponse(outp, outfmt, status)
 
 456 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
 
 457 def website_lookup_request(context, fmt, query):
 
 458     params = { 'osm_ids' : query }
 
 459     outp, status = send_api_query('lookup', params, fmt, context)
 
 463     elif fmt == 'jsonv2 ':
 
 465     elif fmt == 'geojson ':
 
 467     elif fmt == 'geocodejson ':
 
 468         outfmt = 'geocodejson'
 
 472     context.response = SearchResponse(outp, outfmt, status)
 
 474 @when(u'sending (?P<fmt>\S+ )?status query')
 
 475 def website_status_request(context, fmt):
 
 477     outp, status = send_api_query('status', params, fmt, context)
 
 484     context.response = StatusResponse(outp, outfmt, status)
 
 486 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
 
 487 def validate_result_number(context, operator, number):
 
 488     eq_(context.response.errorcode, 200)
 
 489     numres = len(context.response.result)
 
 490     ok_(compare(operator, numres, int(number)),
 
 491         "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
 
 493 @then(u'a HTTP (?P<status>\d+) is returned')
 
 494 def check_http_return_status(context, status):
 
 495     eq_(context.response.errorcode, int(status))
 
 497 @then(u'the page contents equals "(?P<text>.+)"')
 
 498 def check_page_content_equals(context, text):
 
 499     eq_(context.response.page, text)
 
 501 @then(u'the result is valid (?P<fmt>\w+)')
 
 502 def step_impl(context, fmt):
 
 503     context.execute_steps("Then a HTTP 200 is returned")
 
 504     eq_(context.response.format, fmt)
 
 506 @then(u'a (?P<fmt>\w+) user error is returned')
 
 507 def check_page_error(context, fmt):
 
 508     context.execute_steps("Then a HTTP 400 is returned")
 
 509     eq_(context.response.format, fmt)
 
 512         assert_is_not_none(re.search(r'<html( |>).+</html>', context.response.page, re.DOTALL))
 
 514         assert_is_not_none(re.search(r'<error>.+</error>', context.response.page, re.DOTALL))
 
 516         assert_is_not_none(re.search(r'({"error":)', context.response.page, re.DOTALL))
 
 518 @then(u'result header contains')
 
 519 def check_header_attr(context):
 
 520     for line in context.table:
 
 521         assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
 
 522                      "attribute '%s': expected: '%s', got '%s'"
 
 523                        % (line['attr'], line['value'],
 
 524                           context.response.header[line['attr']]))
 
 526 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
 
 527 def check_header_no_attr(context, neg, attrs):
 
 528     for attr in attrs.split(','):
 
 530             assert_not_in(attr, context.response.header)
 
 532             assert_in(attr, context.response.header)
 
 534 @then(u'results contain')
 
 535 def step_impl(context):
 
 536     context.execute_steps("then at least 1 result is returned")
 
 538     for line in context.table:
 
 539         context.response.match_row(line)
 
 541 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
 
 542 def validate_attributes(context, lid, neg, attrs):
 
 544         idx = range(len(context.response.result))
 
 545         context.execute_steps("then at least 1 result is returned")
 
 547         idx = [int(lid.strip())]
 
 548         context.execute_steps("then more than %sresults are returned" % lid)
 
 551         for attr in attrs.split(','):
 
 553                 assert_not_in(attr, context.response.result[i])
 
 555                 assert_in(attr, context.response.result[i])
 
 557 @then(u'result addresses contain')
 
 558 def step_impl(context):
 
 559     context.execute_steps("then at least 1 result is returned")
 
 561     if 'ID' not in context.table.headings:
 
 562         addr_parts = context.response.property_list('address')
 
 564     for line in context.table:
 
 565         if 'ID' in context.table.headings:
 
 566             addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
 
 568         for h in context.table.headings:
 
 572                     assert_equal(p[h], line[h], "Bad address value for %s" % h)
 
 574 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
 
 575 def check_address(context, lid, neg, attrs):
 
 576     context.execute_steps("then more than %s results are returned" % lid)
 
 578     addr_parts = context.response.result[int(lid)]['address']
 
 580     for attr in attrs.split(','):
 
 582             assert_not_in(attr, addr_parts)
 
 584             assert_in(attr, addr_parts)
 
 586 @then(u'address of result (?P<lid>\d+) is')
 
 587 def check_address(context, lid):
 
 588     context.execute_steps("then more than %s results are returned" % lid)
 
 590     addr_parts = dict(context.response.result[int(lid)]['address'])
 
 592     for line in context.table:
 
 593         assert_in(line['type'], addr_parts)
 
 594         assert_equal(addr_parts[line['type']], line['value'],
 
 595                      "Bad address value for %s" % line['type'])
 
 596         del addr_parts[line['type']]
 
 598     eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
 
 600 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
 
 601 def step_impl(context, lid, coords):
 
 603         context.execute_steps("then at least 1 result is returned")
 
 604         bboxes = context.response.property_list('boundingbox')
 
 606         context.execute_steps("then more than %sresults are returned" % lid)
 
 607         bboxes = [ context.response.result[int(lid)]['boundingbox']]
 
 609     coord = [ float(x) for x in coords.split(',') ]
 
 612         if isinstance(bbox, str):
 
 613             bbox = bbox.split(',')
 
 614         bbox = [ float(x) for x in bbox ]
 
 616         assert_greater_equal(bbox[0], coord[0])
 
 617         assert_less_equal(bbox[1], coord[1])
 
 618         assert_greater_equal(bbox[2], coord[2])
 
 619         assert_less_equal(bbox[3], coord[3])
 
 621 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
 
 622 def step_impl(context, lid, coords):
 
 624         context.execute_steps("then at least 1 result is returned")
 
 625         bboxes = zip(context.response.property_list('lat'),
 
 626                      context.response.property_list('lon'))
 
 628         context.execute_steps("then more than %sresults are returned" % lid)
 
 629         res = context.response.result[int(lid)]
 
 630         bboxes = [ (res['lat'], res['lon']) ]
 
 632     coord = [ float(x) for x in coords.split(',') ]
 
 634     for lat, lon in bboxes:
 
 637         assert_greater_equal(lat, coord[0])
 
 638         assert_less_equal(lat, coord[1])
 
 639         assert_greater_equal(lon, coord[2])
 
 640         assert_less_equal(lon, coord[3])
 
 642 @then(u'there are(?P<neg> no)? duplicates')
 
 643 def check_for_duplicates(context, neg):
 
 644     context.execute_steps("then at least 1 result is returned")
 
 649     for res in context.response.result:
 
 650         dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
 
 657         assert not has_dupe, "Found duplicate for %s" % (dup, )
 
 659         assert has_dupe, "No duplicates found"