1 # SPDX-License-Identifier: GPL-2.0-only
 
   3 # This file is part of Nominatim. (https://nominatim.org)
 
   5 # Copyright (C) 2022 by the Nominatim developer community.
 
   6 # For a full list of authors see the git log.
 
   7 """ Steps that run queries against the API.
 
   9     Queries may either be run directly via PHP using the query script
 
  10     or via the HTTP interface using php-cgi.
 
  16 from urllib.parse import urlencode
 
  18 from utils import run_script
 
  19 from http_responses import GenericResponse, SearchResponse, ReverseResponse, StatusResponse
 
  20 from check_functions import Bbox
 
  21 from table_compare import NominatimID
 
  23 LOG = logging.getLogger(__name__)
 
  26     'HTTP_HOST' : 'localhost',
 
  27     'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
 
  28     'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
 
  29     'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
 
  30     'HTTP_CONNECTION' : 'keep-alive',
 
  31     'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
 
  32     'SERVER_SOFTWARE' : 'Nominatim test',
 
  33     'SERVER_NAME' : 'localhost',
 
  34     'SERVER_ADDR' : '127.0.1.1',
 
  36     'REMOTE_ADDR' : '127.0.0.1',
 
  37     'DOCUMENT_ROOT' : '/var/www',
 
  38     'REQUEST_SCHEME' : 'http',
 
  39     'CONTEXT_PREFIX' : '/',
 
  40     'SERVER_ADMIN' : 'webmaster@localhost',
 
  41     'REMOTE_PORT' : '49319',
 
  42     'GATEWAY_INTERFACE' : 'CGI/1.1',
 
  43     'SERVER_PROTOCOL' : 'HTTP/1.1',
 
  44     'REQUEST_METHOD' : 'GET',
 
  45     'REDIRECT_STATUS' : 'CGI'
 
  49 def compare(operator, op1, op2):
 
  50     if operator == 'less than':
 
  52     elif operator == 'more than':
 
  54     elif operator == 'exactly':
 
  56     elif operator == 'at least':
 
  58     elif operator == 'at most':
 
  61         raise Exception("unknown operator '%s'" % operator)
 
  64 def send_api_query(endpoint, params, fmt, context):
 
  65     if fmt is not None and fmt.strip() != 'debug':
 
  66         params['format'] = fmt.strip()
 
  68         if context.table.headings[0] == 'param':
 
  69             for line in context.table:
 
  70                 params[line['param']] = line['value']
 
  72             for h in context.table.headings:
 
  73                 params[h] = context.table[0][h]
 
  75     env = dict(BASE_SERVER_ENV)
 
  76     env['QUERY_STRING'] = urlencode(params)
 
  78     env['SCRIPT_NAME'] = '/%s.php' % endpoint
 
  79     env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
 
  80     env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.website_dir.name, 'website')
 
  81     env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
 
  84     LOG.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
 
  86     if hasattr(context, 'http_headers'):
 
  87         env.update(context.http_headers)
 
  89     cmd = ['/usr/bin/env', 'php-cgi', '-f']
 
  90     if context.nominatim.code_coverage_path:
 
  91         env['XDEBUG_MODE'] = 'coverage'
 
  92         env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
 
  93         env['COV_PHP_DIR'] = context.nominatim.src_dir
 
  94         env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
 
  95         env['SCRIPT_FILENAME'] = \
 
  96                 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
 
  97         cmd.append(env['SCRIPT_FILENAME'])
 
  98         env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
 
 100         cmd.append(env['SCRIPT_FILENAME'])
 
 102     for k,v in params.items():
 
 103         cmd.append("%s=%s" % (k, v))
 
 105     outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
 
 107     assert len(err) == 0, "Unexpected PHP error: %s" % (err)
 
 109     if outp.startswith('Status: '):
 
 110         status = int(outp[8:11])
 
 114     content_start = outp.find('\r\n\r\n')
 
 116     return outp[content_start + 4:], status
 
 118 @given(u'the HTTP header')
 
 119 def add_http_header(context):
 
 120     if not hasattr(context, 'http_headers'):
 
 121         context.http_headers = {}
 
 123     for h in context.table.headings:
 
 124         envvar = 'HTTP_' + h.upper().replace('-', '_')
 
 125         context.http_headers[envvar] = context.table[0][h]
 
 128 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
 
 129 def website_search_request(context, fmt, query, addr):
 
 134         params['addressdetails'] = '1'
 
 135     if fmt and fmt.strip() == 'debug':
 
 136         params['debug'] = '1'
 
 138     outp, status = send_api_query('search', params, fmt, context)
 
 140     context.response = SearchResponse(outp, fmt or 'json', status)
 
 142 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
 
 143 def website_reverse_request(context, fmt, lat, lon):
 
 149     if fmt and fmt.strip() == 'debug':
 
 150         params['debug'] = '1'
 
 152     outp, status = send_api_query('reverse', params, fmt, context)
 
 154     context.response = ReverseResponse(outp, fmt or 'xml', status)
 
 156 @when(u'sending (?P<fmt>\S+ )?reverse point (?P<nodeid>.+)')
 
 157 def website_reverse_request(context, fmt, nodeid):
 
 159     if fmt and fmt.strip() == 'debug':
 
 160         params['debug'] = '1'
 
 161     params['lon'], params['lat'] = (f'{c:f}' for c in context.osm.grid_node(int(nodeid)))
 
 164     outp, status = send_api_query('reverse', params, fmt, context)
 
 166     context.response = ReverseResponse(outp, fmt or 'xml', status)
 
 170 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
 
 171 def website_details_request(context, fmt, query):
 
 173     if query[0] in 'NWR':
 
 174         nid = NominatimID(query)
 
 175         params['osmtype'] = nid.typ
 
 176         params['osmid'] = nid.oid
 
 178             params['class'] = nid.cls
 
 180         params['place_id'] = query
 
 181     outp, status = send_api_query('details', params, fmt, context)
 
 183     context.response = GenericResponse(outp, fmt or 'json', status)
 
 185 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
 
 186 def website_lookup_request(context, fmt, query):
 
 187     params = { 'osm_ids' : query }
 
 188     outp, status = send_api_query('lookup', params, fmt, context)
 
 190     context.response = SearchResponse(outp, fmt or 'xml', status)
 
 192 @when(u'sending (?P<fmt>\S+ )?status query')
 
 193 def website_status_request(context, fmt):
 
 195     outp, status = send_api_query('status', params, fmt, context)
 
 197     context.response = StatusResponse(outp, fmt or 'text', status)
 
 199 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
 
 200 def validate_result_number(context, operator, number):
 
 201     assert context.response.errorcode == 200
 
 202     numres = len(context.response.result)
 
 203     assert compare(operator, numres, int(number)), \
 
 204         "Bad number of results: expected {} {}, got {}.".format(operator, number, numres)
 
 206 @then(u'a HTTP (?P<status>\d+) is returned')
 
 207 def check_http_return_status(context, status):
 
 208     assert context.response.errorcode == int(status), \
 
 209            "Return HTTP status is {}.".format(context.response.errorcode)
 
 211 @then(u'the page contents equals "(?P<text>.+)"')
 
 212 def check_page_content_equals(context, text):
 
 213     assert context.response.page == text
 
 215 @then(u'the result is valid (?P<fmt>\w+)')
 
 216 def step_impl(context, fmt):
 
 217     context.execute_steps("Then a HTTP 200 is returned")
 
 218     assert context.response.format == fmt
 
 220 @then(u'a (?P<fmt>\w+) user error is returned')
 
 221 def check_page_error(context, fmt):
 
 222     context.execute_steps("Then a HTTP 400 is returned")
 
 223     assert context.response.format == fmt
 
 226         assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
 
 228         assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
 
 230 @then(u'result header contains')
 
 231 def check_header_attr(context):
 
 232     for line in context.table:
 
 233         assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
 
 234                "attribute '%s': expected: '%s', got '%s'" % (
 
 235                     line['attr'], line['value'],
 
 236                     context.response.header[line['attr']])
 
 238 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
 
 239 def check_header_no_attr(context, neg, attrs):
 
 240     for attr in attrs.split(','):
 
 242             assert attr not in context.response.header, \
 
 243                    "Unexpected attribute {}. Full response:\n{}".format(
 
 244                        attr, json.dumps(context.response.header, sort_keys=True, indent=2))
 
 246             assert attr in context.response.header, \
 
 247                    "No attribute {}. Full response:\n{}".format(
 
 248                        attr, json.dumps(context.response.header, sort_keys=True, indent=2))
 
 250 @then(u'results contain')
 
 251 def step_impl(context):
 
 252     context.execute_steps("then at least 1 result is returned")
 
 254     for line in context.table:
 
 255         context.response.match_row(line, context=context)
 
 257 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
 
 258 def validate_attributes(context, lid, neg, attrs):
 
 260         idx = range(len(context.response.result))
 
 261         context.execute_steps("then at least 1 result is returned")
 
 263         idx = [int(lid.strip())]
 
 264         context.execute_steps("then more than %sresults are returned" % lid)
 
 267         for attr in attrs.split(','):
 
 269                 assert attr not in context.response.result[i],\
 
 270                        "Unexpected attribute {}. Full response:\n{}".format(
 
 271                            attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
 
 273                 assert attr in context.response.result[i], \
 
 274                        "No attribute {}. Full response:\n{}".format(
 
 275                            attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
 
 277 @then(u'result addresses contain')
 
 278 def step_impl(context):
 
 279     context.execute_steps("then at least 1 result is returned")
 
 281     for line in context.table:
 
 282         idx = int(line['ID']) if 'ID' in line.headings else None
 
 284         for name, value in zip(line.headings, line.cells):
 
 286                 context.response.assert_address_field(idx, name, value)
 
 288 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
 
 289 def check_address(context, lid, neg, attrs):
 
 290     context.execute_steps("then more than %s results are returned" % lid)
 
 292     addr_parts = context.response.result[int(lid)]['address']
 
 294     for attr in attrs.split(','):
 
 296             assert attr not in addr_parts
 
 298             assert attr in addr_parts
 
 300 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
 
 301 def check_address(context, lid, complete):
 
 302     context.execute_steps("then more than %s results are returned" % lid)
 
 305     addr_parts = dict(context.response.result[lid]['address'])
 
 307     for line in context.table:
 
 308         context.response.assert_address_field(lid, line['type'], line['value'])
 
 309         del addr_parts[line['type']]
 
 312         assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
 
 314 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
 
 315 def step_impl(context, lid, coords):
 
 317         context.execute_steps("then at least 1 result is returned")
 
 318         bboxes = context.response.property_list('boundingbox')
 
 320         context.execute_steps("then more than {}results are returned".format(lid))
 
 321         bboxes = [context.response.result[int(lid)]['boundingbox']]
 
 323     expected = Bbox(coords)
 
 326         assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
 
 328 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
 
 329 def step_impl(context, lid, coords):
 
 331         context.execute_steps("then at least 1 result is returned")
 
 332         centroids = zip(context.response.property_list('lon'),
 
 333                         context.response.property_list('lat'))
 
 335         context.execute_steps("then more than %sresults are returned".format(lid))
 
 336         res = context.response.result[int(lid)]
 
 337         centroids = [(res['lon'], res['lat'])]
 
 339     expected = Bbox(coords)
 
 341     for centroid in centroids:
 
 342         assert centroid in expected,\
 
 343                "Centroid {} is not inside {}.".format(centroid, expected)
 
 345 @then(u'there are(?P<neg> no)? duplicates')
 
 346 def check_for_duplicates(context, neg):
 
 347     context.execute_steps("then at least 1 result is returned")
 
 352     for res in context.response.result:
 
 353         dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
 
 360         assert not has_dupe, "Found duplicate for %s" % (dup, )
 
 362         assert has_dupe, "No duplicates found"