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.
12 from pathlib import Path
18 from urllib.parse import urlencode
20 from utils import run_script
21 from http_responses import GenericResponse, SearchResponse, ReverseResponse, StatusResponse
22 from check_functions import Bbox
23 from table_compare import NominatimID
25 LOG = logging.getLogger(__name__)
28 'HTTP_HOST' : 'localhost',
29 'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
30 'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
31 'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
32 'HTTP_CONNECTION' : 'keep-alive',
33 'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
34 'SERVER_SOFTWARE' : 'Nominatim test',
35 'SERVER_NAME' : 'localhost',
36 'SERVER_ADDR' : '127.0.1.1',
38 'REMOTE_ADDR' : '127.0.0.1',
39 'DOCUMENT_ROOT' : '/var/www',
40 'REQUEST_SCHEME' : 'http',
41 'CONTEXT_PREFIX' : '/',
42 'SERVER_ADMIN' : 'webmaster@localhost',
43 'REMOTE_PORT' : '49319',
44 'GATEWAY_INTERFACE' : 'CGI/1.1',
45 'SERVER_PROTOCOL' : 'HTTP/1.1',
46 'REQUEST_METHOD' : 'GET',
47 'REDIRECT_STATUS' : 'CGI'
51 def compare(operator, op1, op2):
52 if operator == 'less than':
54 elif operator == 'more than':
56 elif operator == 'exactly':
58 elif operator == 'at least':
60 elif operator == 'at most':
63 raise Exception("unknown operator '%s'" % operator)
66 def send_api_query(endpoint, params, fmt, context):
67 if fmt is not None and fmt.strip() != 'debug':
68 params['format'] = fmt.strip()
70 if context.table.headings[0] == 'param':
71 for line in context.table:
72 params[line['param']] = line['value']
74 for h in context.table.headings:
75 params[h] = context.table[0][h]
77 if context.nominatim.api_engine is None:
78 return send_api_query_php(endpoint, params, context)
80 return asyncio.run(context.nominatim.api_engine(endpoint, params,
81 Path(context.nominatim.website_dir.name),
82 context.nominatim.test_env,
83 getattr(context, 'http_headers', {})))
87 def send_api_query_php(endpoint, params, context):
88 env = dict(BASE_SERVER_ENV)
89 env['QUERY_STRING'] = urlencode(params)
91 env['SCRIPT_NAME'] = '/%s.php' % endpoint
92 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
93 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.website_dir.name, 'website')
94 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
97 LOG.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
99 if hasattr(context, 'http_headers'):
100 env.update(context.http_headers)
102 cmd = ['/usr/bin/env', 'php-cgi', '-f']
103 if context.nominatim.code_coverage_path:
104 env['XDEBUG_MODE'] = 'coverage'
105 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
106 env['COV_PHP_DIR'] = context.nominatim.src_dir
107 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
108 env['SCRIPT_FILENAME'] = \
109 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
110 cmd.append(env['SCRIPT_FILENAME'])
111 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
113 cmd.append(env['SCRIPT_FILENAME'])
115 for k,v in params.items():
116 cmd.append("%s=%s" % (k, v))
118 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
120 assert len(err) == 0, "Unexpected PHP error: %s" % (err)
122 if outp.startswith('Status: '):
123 status = int(outp[8:11])
127 content_start = outp.find('\r\n\r\n')
129 return outp[content_start + 4:], status
131 @given(u'the HTTP header')
132 def add_http_header(context):
133 if not hasattr(context, 'http_headers'):
134 context.http_headers = {}
136 for h in context.table.headings:
137 envvar = 'HTTP_' + h.upper().replace('-', '_')
138 context.http_headers[envvar] = context.table[0][h]
141 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
142 def website_search_request(context, fmt, query, addr):
147 params['addressdetails'] = '1'
148 if fmt and fmt.strip() == 'debug':
149 params['debug'] = '1'
151 outp, status = send_api_query('search', params, fmt, context)
153 context.response = SearchResponse(outp, fmt or 'json', status)
155 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
156 def website_reverse_request(context, fmt, lat, lon):
162 if fmt and fmt.strip() == 'debug':
163 params['debug'] = '1'
165 outp, status = send_api_query('reverse', params, fmt, context)
167 context.response = ReverseResponse(outp, fmt or 'xml', status)
169 @when(u'sending (?P<fmt>\S+ )?reverse point (?P<nodeid>.+)')
170 def website_reverse_request(context, fmt, nodeid):
172 if fmt and fmt.strip() == 'debug':
173 params['debug'] = '1'
174 params['lon'], params['lat'] = (f'{c:f}' for c in context.osm.grid_node(int(nodeid)))
177 outp, status = send_api_query('reverse', params, fmt, context)
179 context.response = ReverseResponse(outp, fmt or 'xml', status)
183 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
184 def website_details_request(context, fmt, query):
186 if query[0] in 'NWR':
187 nid = NominatimID(query)
188 params['osmtype'] = nid.typ
189 params['osmid'] = nid.oid
191 params['class'] = nid.cls
193 params['place_id'] = query
194 outp, status = send_api_query('details', params, fmt, context)
196 context.response = GenericResponse(outp, fmt or 'json', status)
198 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
199 def website_lookup_request(context, fmt, query):
200 params = { 'osm_ids' : query }
201 outp, status = send_api_query('lookup', params, fmt, context)
203 context.response = SearchResponse(outp, fmt or 'xml', status)
205 @when(u'sending (?P<fmt>\S+ )?status query')
206 def website_status_request(context, fmt):
208 outp, status = send_api_query('status', params, fmt, context)
210 context.response = StatusResponse(outp, fmt or 'text', status)
212 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
213 def validate_result_number(context, operator, number):
214 assert context.response.errorcode == 200
215 numres = len(context.response.result)
216 assert compare(operator, numres, int(number)), \
217 "Bad number of results: expected {} {}, got {}.".format(operator, number, numres)
219 @then(u'a HTTP (?P<status>\d+) is returned')
220 def check_http_return_status(context, status):
221 assert context.response.errorcode == int(status), \
222 "Return HTTP status is {}.".format(context.response.errorcode)
224 @then(u'the page contents equals "(?P<text>.+)"')
225 def check_page_content_equals(context, text):
226 assert context.response.page == text
228 @then(u'the result is valid (?P<fmt>\w+)')
229 def step_impl(context, fmt):
230 context.execute_steps("Then a HTTP 200 is returned")
231 assert context.response.format == fmt
233 @then(u'a (?P<fmt>\w+) user error is returned')
234 def check_page_error(context, fmt):
235 context.execute_steps("Then a HTTP 400 is returned")
236 assert context.response.format == fmt
239 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
241 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
243 @then(u'result header contains')
244 def check_header_attr(context):
245 for line in context.table:
246 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
247 "attribute '%s': expected: '%s', got '%s'" % (
248 line['attr'], line['value'],
249 context.response.header[line['attr']])
251 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
252 def check_header_no_attr(context, neg, attrs):
253 for attr in attrs.split(','):
255 assert attr not in context.response.header, \
256 "Unexpected attribute {}. Full response:\n{}".format(
257 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
259 assert attr in context.response.header, \
260 "No attribute {}. Full response:\n{}".format(
261 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
263 @then(u'results contain')
264 def step_impl(context):
265 context.execute_steps("then at least 1 result is returned")
267 for line in context.table:
268 context.response.match_row(line, context=context)
270 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
271 def validate_attributes(context, lid, neg, attrs):
273 idx = range(len(context.response.result))
274 context.execute_steps("then at least 1 result is returned")
276 idx = [int(lid.strip())]
277 context.execute_steps("then more than %sresults are returned" % lid)
280 for attr in attrs.split(','):
282 assert attr not in context.response.result[i],\
283 "Unexpected attribute {}. Full response:\n{}".format(
284 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
286 assert attr in context.response.result[i], \
287 "No attribute {}. Full response:\n{}".format(
288 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
290 @then(u'result addresses contain')
291 def step_impl(context):
292 context.execute_steps("then at least 1 result is returned")
294 for line in context.table:
295 idx = int(line['ID']) if 'ID' in line.headings else None
297 for name, value in zip(line.headings, line.cells):
299 context.response.assert_address_field(idx, name, value)
301 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
302 def check_address(context, lid, neg, attrs):
303 context.execute_steps("then more than %s results are returned" % lid)
305 addr_parts = context.response.result[int(lid)]['address']
307 for attr in attrs.split(','):
309 assert attr not in addr_parts
311 assert attr in addr_parts
313 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
314 def check_address(context, lid, complete):
315 context.execute_steps("then more than %s results are returned" % lid)
318 addr_parts = dict(context.response.result[lid]['address'])
320 for line in context.table:
321 context.response.assert_address_field(lid, line['type'], line['value'])
322 del addr_parts[line['type']]
325 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
327 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
328 def step_impl(context, lid, coords):
330 context.execute_steps("then at least 1 result is returned")
331 bboxes = context.response.property_list('boundingbox')
333 context.execute_steps("then more than {}results are returned".format(lid))
334 bboxes = [context.response.result[int(lid)]['boundingbox']]
336 expected = Bbox(coords)
339 assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
341 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
342 def step_impl(context, lid, coords):
344 context.execute_steps("then at least 1 result is returned")
345 centroids = zip(context.response.property_list('lon'),
346 context.response.property_list('lat'))
348 context.execute_steps("then more than %sresults are returned".format(lid))
349 res = context.response.result[int(lid)]
350 centroids = [(res['lon'], res['lat'])]
352 expected = Bbox(coords)
354 for centroid in centroids:
355 assert centroid in expected,\
356 "Centroid {} is not inside {}.".format(centroid, expected)
358 @then(u'there are(?P<neg> no)? duplicates')
359 def check_for_duplicates(context, neg):
360 context.execute_steps("then at least 1 result is returned")
365 for res in context.response.result:
366 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
373 assert not has_dupe, "Found duplicate for %s" % (dup, )
375 assert has_dupe, "No duplicates found"