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 import xml.etree.ElementTree as ET
 
  14 from urllib.parse import urlencode
 
  15 from collections import OrderedDict
 
  16 from nose.tools import * # for assert functions
 
  18 logger = logging.getLogger(__name__)
 
  21     'HTTP_HOST' : 'localhost',
 
  22     'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
 
  23     'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
 
  24     'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
 
  25     'HTTP_CONNECTION' : 'keep-alive',
 
  26     'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
 
  27     'SERVER_SOFTWARE' : 'Nominatim test',
 
  28     'SERVER_NAME' : 'localhost',
 
  29     'SERVER_ADDR' : '127.0.1.1',
 
  31     'REMOTE_ADDR' : '127.0.0.1',
 
  32     'DOCUMENT_ROOT' : '/var/www',
 
  33     'REQUEST_SCHEME' : 'http',
 
  34     'CONTEXT_PREFIX' : '/',
 
  35     'SERVER_ADMIN' : 'webmaster@localhost',
 
  36     'REMOTE_PORT' : '49319',
 
  37     'GATEWAY_INTERFACE' : 'CGI/1.1',
 
  38     'SERVER_PROTOCOL' : 'HTTP/1.1',
 
  39     'REQUEST_METHOD' : 'GET',
 
  40     'REDIRECT_STATUS' : 'CGI'
 
  44 def compare(operator, op1, op2):
 
  45     if operator == 'less than':
 
  47     elif operator == 'more than':
 
  49     elif operator == 'exactly':
 
  51     elif operator == 'at least':
 
  53     elif operator == 'at most':
 
  56         raise Exception("unknown operator '%s'" % operator)
 
  58 class GenericResponse(object):
 
  60     def match_row(self, row):
 
  61         if 'ID' in row.headings:
 
  62             todo = [int(row['ID'])]
 
  64             todo = range(len(self.result))
 
  68             for h in row.headings:
 
  72                     assert_equal(res['osm_type'], row[h][0])
 
  73                     assert_equal(res['osm_id'], int(row[h][1:]))
 
  75                     x, y = row[h].split(' ')
 
  76                     assert_almost_equal(float(y), float(res['lat']))
 
  77                     assert_almost_equal(float(x), float(res['lon']))
 
  78                 elif row[h].startswith("^"):
 
  80                     assert_is_not_none(re.fullmatch(row[h], res[h]),
 
  81                                        "attribute '%s': expected: '%s', got '%s'"
 
  82                                           % (h, row[h], res[h]))
 
  85                     assert_equal(str(res[h]), str(row[h]))
 
  87     def property_list(self, prop):
 
  88         return [ x[prop] for x in self.result ]
 
  91 class SearchResponse(GenericResponse):
 
  93     def __init__(self, page, fmt='json', errorcode=200):
 
  96         self.errorcode = errorcode
 
 101             getattr(self, 'parse_' + fmt)()
 
 103     def parse_json(self):
 
 104         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
 
 109             self.header['json_func'] = m.group(1)
 
 110         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
 
 112     def parse_geojson(self):
 
 114         self.result = geojson_results_to_json_results(self.result)
 
 116     def parse_geocodejson(self):
 
 118         if self.result is not None:
 
 119             self.result = [r['geocoding'] for r in self.result]
 
 122         et = ET.fromstring(self.page)
 
 124         self.header = dict(et.attrib)
 
 127             assert_equal(child.tag, "place")
 
 128             self.result.append(dict(child.attrib))
 
 132                 if sub.tag == 'extratags':
 
 133                     self.result[-1]['extratags'] = {}
 
 135                         self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 136                 elif sub.tag == 'namedetails':
 
 137                     self.result[-1]['namedetails'] = {}
 
 139                         self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
 
 140                 elif sub.tag in ('geokml'):
 
 141                     self.result[-1][sub.tag] = True
 
 143                     address[sub.tag] = sub.text
 
 146                 self.result[-1]['address'] = address
 
 149 class ReverseResponse(GenericResponse):
 
 151     def __init__(self, page, fmt='json', errorcode=200):
 
 154         self.errorcode = errorcode
 
 159             getattr(self, 'parse_' + fmt)()
 
 161     def parse_json(self):
 
 162         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
 
 167             self.header['json_func'] = m.group(1)
 
 168         self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)]
 
 170     def parse_geojson(self):
 
 172         if 'error' in self.result:
 
 174         self.result = geojson_results_to_json_results(self.result[0])
 
 176     def parse_geocodejson(self):
 
 178         if self.result is not None:
 
 179             self.result = [r['geocoding'] for r in self.result]
 
 182         et = ET.fromstring(self.page)
 
 184         self.header = dict(et.attrib)
 
 188             if child.tag == 'result':
 
 189                 eq_(0, len(self.result), "More than one result in reverse result")
 
 190                 self.result.append(dict(child.attrib))
 
 191             elif child.tag == 'addressparts':
 
 194                     address[sub.tag] = sub.text
 
 195                 self.result[0]['address'] = address
 
 196             elif child.tag == 'extratags':
 
 197                 self.result[0]['extratags'] = {}
 
 199                     self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
 
 200             elif child.tag == 'namedetails':
 
 201                 self.result[0]['namedetails'] = {}
 
 203                     self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
 
 204             elif child.tag in ('geokml'):
 
 205                 self.result[0][child.tag] = True
 
 207                 assert child.tag == 'error', \
 
 208                         "Unknown XML tag %s on page: %s" % (child.tag, self.page)
 
 211 class DetailsResponse(GenericResponse):
 
 213     def __init__(self, page, fmt='json', errorcode=200):
 
 216         self.errorcode = errorcode
 
 221             getattr(self, 'parse_' + fmt)()
 
 223     def parse_json(self):
 
 224         self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
 
 227 class StatusResponse(GenericResponse):
 
 229     def __init__(self, page, fmt='text', errorcode=200):
 
 232         self.errorcode = errorcode
 
 234         if errorcode == 200 and fmt != 'text':
 
 235             getattr(self, 'parse_' + fmt)()
 
 237     def parse_json(self):
 
 238         self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
 
 241 def geojson_result_to_json_result(geojson_result):
 
 242     result = geojson_result['properties']
 
 243     result['geojson'] = geojson_result['geometry']
 
 244     if 'bbox' in geojson_result:
 
 245         # bbox is  minlon, minlat, maxlon, maxlat
 
 246         # boundingbox is minlat, maxlat, minlon, maxlon
 
 247         result['boundingbox'] = [
 
 248                                     geojson_result['bbox'][1],
 
 249                                     geojson_result['bbox'][3],
 
 250                                     geojson_result['bbox'][0],
 
 251                                     geojson_result['bbox'][2]
 
 256 def geojson_results_to_json_results(geojson_results):
 
 257     if 'error' in geojson_results:
 
 259     return list(map(geojson_result_to_json_result, geojson_results['features']))
 
 262 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
 
 263 def query_cmd(context, query, dups):
 
 264     """ Query directly via PHP script.
 
 266     cmd = ['/usr/bin/env', 'php']
 
 267     cmd.append(os.path.join(context.nominatim.build_dir, 'utils', 'query.php'))
 
 269         cmd.extend(['--search', query])
 
 270     # add more parameters in table form
 
 272         for h in context.table.headings:
 
 273             value = context.table[0][h].strip()
 
 275                 cmd.extend(('--' + h, value))
 
 278         cmd.extend(('--dedupe', '0'))
 
 280     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
 
 281                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
 282     (outp, err) = proc.communicate()
 
 284     assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
 
 286     context.response = SearchResponse(outp.decode('utf-8'), 'json')
 
 288 def send_api_query(endpoint, params, fmt, context):
 
 290         params['format'] = fmt.strip()
 
 292         if context.table.headings[0] == 'param':
 
 293             for line in context.table:
 
 294                 params[line['param']] = line['value']
 
 296             for h in context.table.headings:
 
 297                 params[h] = context.table[0][h]
 
 299     env = dict(BASE_SERVER_ENV)
 
 300     env['QUERY_STRING'] = urlencode(params)
 
 302     env['SCRIPT_NAME'] = '/%s.php' % endpoint
 
 303     env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
 
 304     env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
 
 305     env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
 
 307     env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
 
 309     logger.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
 
 311     if hasattr(context, 'http_headers'):
 
 312         env.update(context.http_headers)
 
 314     cmd = ['/usr/bin/env', 'php-cgi', '-f']
 
 315     if context.nominatim.code_coverage_path:
 
 316         env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
 
 317         env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
 
 318         env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
 
 319         env['SCRIPT_FILENAME'] = \
 
 320                 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
 
 321         cmd.append(env['SCRIPT_FILENAME'])
 
 322         env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
 
 324         cmd.append(env['SCRIPT_FILENAME'])
 
 326     for k,v in params.items():
 
 327         cmd.append("%s=%s" % (k, v))
 
 329     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
 
 330                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
 332     (outp, err) = proc.communicate()
 
 333     outp = outp.decode('utf-8')
 
 334     err = err.decode("utf-8")
 
 336     logger.debug("Result: \n===============================\n"
 
 337                  + outp + "\n===============================\n")
 
 339     assert_equals(0, proc.returncode,
 
 340                   "%s failed with message: %s" % (
 
 341                       os.path.basename(env['SCRIPT_FILENAME']),
 
 344     assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
 
 346     if outp.startswith('Status: '):
 
 347         status = int(outp[8:11])
 
 351     content_start = outp.find('\r\n\r\n')
 
 353     return outp[content_start + 4:], status
 
 355 @given(u'the HTTP header')
 
 356 def add_http_header(context):
 
 357     if not hasattr(context, 'http_headers'):
 
 358         context.http_headers = {}
 
 360     for h in context.table.headings:
 
 361         envvar = 'HTTP_' + h.upper().replace('-', '_')
 
 362         context.http_headers[envvar] = context.table[0][h]
 
 365 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
 
 366 def website_search_request(context, fmt, query, addr):
 
 371         params['addressdetails'] = '1'
 
 373     outp, status = send_api_query('search', params, fmt, context)
 
 375     if fmt is None or fmt == 'jsonv2 ':
 
 380     context.response = SearchResponse(outp, outfmt, status)
 
 382 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
 
 383 def website_reverse_request(context, fmt, lat, lon):
 
 390     outp, status = send_api_query('reverse', params, fmt, context)
 
 394     elif fmt == 'jsonv2 ':
 
 399     context.response = ReverseResponse(outp, outfmt, status)
 
 401 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
 
 402 def website_details_request(context, fmt, query):
 
 404     if query[0] in 'NWR':
 
 405         params['osmtype'] = query[0]
 
 406         params['osmid'] = query[1:]
 
 408         params['place_id'] = query
 
 409     outp, status = send_api_query('details', params, fmt, context)
 
 416     context.response = DetailsResponse(outp, outfmt, status)
 
 418 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
 
 419 def website_lookup_request(context, fmt, query):
 
 420     params = { 'osm_ids' : query }
 
 421     outp, status = send_api_query('lookup', params, fmt, context)
 
 425     elif fmt == 'jsonv2 ':
 
 427     elif fmt == 'geojson ':
 
 429     elif fmt == 'geocodejson ':
 
 430         outfmt = 'geocodejson'
 
 434     context.response = SearchResponse(outp, outfmt, status)
 
 436 @when(u'sending (?P<fmt>\S+ )?status query')
 
 437 def website_status_request(context, fmt):
 
 439     outp, status = send_api_query('status', params, fmt, context)
 
 446     context.response = StatusResponse(outp, outfmt, status)
 
 448 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
 
 449 def validate_result_number(context, operator, number):
 
 450     eq_(context.response.errorcode, 200)
 
 451     numres = len(context.response.result)
 
 452     ok_(compare(operator, numres, int(number)),
 
 453         "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
 
 455 @then(u'a HTTP (?P<status>\d+) is returned')
 
 456 def check_http_return_status(context, status):
 
 457     eq_(context.response.errorcode, int(status))
 
 459 @then(u'the page contents equals "(?P<text>.+)"')
 
 460 def check_page_content_equals(context, text):
 
 461     eq_(context.response.page, text)
 
 463 @then(u'the result is valid (?P<fmt>\w+)')
 
 464 def step_impl(context, fmt):
 
 465     context.execute_steps("Then a HTTP 200 is returned")
 
 466     eq_(context.response.format, fmt)
 
 468 @then(u'a (?P<fmt>\w+) user error is returned')
 
 469 def check_page_error(context, fmt):
 
 470     context.execute_steps("Then a HTTP 400 is returned")
 
 471     eq_(context.response.format, fmt)
 
 474         assert_is_not_none(re.search(r'<error>.+</error>', context.response.page, re.DOTALL))
 
 476         assert_is_not_none(re.search(r'({"error":)', context.response.page, re.DOTALL))
 
 478 @then(u'result header contains')
 
 479 def check_header_attr(context):
 
 480     for line in context.table:
 
 481         assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
 
 482                      "attribute '%s': expected: '%s', got '%s'"
 
 483                        % (line['attr'], line['value'],
 
 484                           context.response.header[line['attr']]))
 
 486 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
 
 487 def check_header_no_attr(context, neg, attrs):
 
 488     for attr in attrs.split(','):
 
 490             assert_not_in(attr, context.response.header)
 
 492             assert_in(attr, context.response.header)
 
 494 @then(u'results contain')
 
 495 def step_impl(context):
 
 496     context.execute_steps("then at least 1 result is returned")
 
 498     for line in context.table:
 
 499         context.response.match_row(line)
 
 501 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
 
 502 def validate_attributes(context, lid, neg, attrs):
 
 504         idx = range(len(context.response.result))
 
 505         context.execute_steps("then at least 1 result is returned")
 
 507         idx = [int(lid.strip())]
 
 508         context.execute_steps("then more than %sresults are returned" % lid)
 
 511         for attr in attrs.split(','):
 
 513                 assert_not_in(attr, context.response.result[i])
 
 515                 assert_in(attr, context.response.result[i])
 
 517 @then(u'result addresses contain')
 
 518 def step_impl(context):
 
 519     context.execute_steps("then at least 1 result is returned")
 
 521     if 'ID' not in context.table.headings:
 
 522         addr_parts = context.response.property_list('address')
 
 524     for line in context.table:
 
 525         if 'ID' in context.table.headings:
 
 526             addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
 
 528         for h in context.table.headings:
 
 532                     assert_equal(p[h], line[h], "Bad address value for %s" % h)
 
 534 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
 
 535 def check_address(context, lid, neg, attrs):
 
 536     context.execute_steps("then more than %s results are returned" % lid)
 
 538     addr_parts = context.response.result[int(lid)]['address']
 
 540     for attr in attrs.split(','):
 
 542             assert_not_in(attr, addr_parts)
 
 544             assert_in(attr, addr_parts)
 
 546 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
 
 547 def check_address(context, lid, complete):
 
 548     context.execute_steps("then more than %s results are returned" % lid)
 
 550     addr_parts = dict(context.response.result[int(lid)]['address'])
 
 552     for line in context.table:
 
 553         assert_in(line['type'], addr_parts)
 
 554         assert_equal(addr_parts[line['type']], line['value'],
 
 555                      "Bad address value for %s" % line['type'])
 
 556         del addr_parts[line['type']]
 
 559         eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
 
 561 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
 
 562 def step_impl(context, lid, coords):
 
 564         context.execute_steps("then at least 1 result is returned")
 
 565         bboxes = context.response.property_list('boundingbox')
 
 567         context.execute_steps("then more than %sresults are returned" % lid)
 
 568         bboxes = [ context.response.result[int(lid)]['boundingbox']]
 
 570     coord = [ float(x) for x in coords.split(',') ]
 
 573         if isinstance(bbox, str):
 
 574             bbox = bbox.split(',')
 
 575         bbox = [ float(x) for x in bbox ]
 
 577         assert_greater_equal(bbox[0], coord[0])
 
 578         assert_less_equal(bbox[1], coord[1])
 
 579         assert_greater_equal(bbox[2], coord[2])
 
 580         assert_less_equal(bbox[3], coord[3])
 
 582 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
 
 583 def step_impl(context, lid, coords):
 
 585         context.execute_steps("then at least 1 result is returned")
 
 586         bboxes = zip(context.response.property_list('lat'),
 
 587                      context.response.property_list('lon'))
 
 589         context.execute_steps("then more than %sresults are returned" % lid)
 
 590         res = context.response.result[int(lid)]
 
 591         bboxes = [ (res['lat'], res['lon']) ]
 
 593     coord = [ float(x) for x in coords.split(',') ]
 
 595     for lat, lon in bboxes:
 
 598         assert_greater_equal(lat, coord[0])
 
 599         assert_less_equal(lat, coord[1])
 
 600         assert_greater_equal(lon, coord[2])
 
 601         assert_less_equal(lon, coord[3])
 
 603 @then(u'there are(?P<neg> no)? duplicates')
 
 604 def check_for_duplicates(context, neg):
 
 605     context.execute_steps("then at least 1 result is returned")
 
 610     for res in context.response.result:
 
 611         dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
 
 618         assert not has_dupe, "Found duplicate for %s" % (dup, )
 
 620         assert has_dupe, "No duplicates found"