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 import xml.etree.ElementTree as ET
19 from urllib.parse import urlencode
21 from utils import run_script
22 from http_responses import GenericResponse, SearchResponse, ReverseResponse, StatusResponse
23 from check_functions import Bbox, check_for_attributes
24 from table_compare import NominatimID
26 LOG = logging.getLogger(__name__)
29 'HTTP_HOST' : 'localhost',
30 'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
31 'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
32 'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
33 'HTTP_CONNECTION' : 'keep-alive',
34 'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
35 'SERVER_SOFTWARE' : 'Nominatim test',
36 'SERVER_NAME' : 'localhost',
37 'SERVER_ADDR' : '127.0.1.1',
39 'REMOTE_ADDR' : '127.0.0.1',
40 'DOCUMENT_ROOT' : '/var/www',
41 'REQUEST_SCHEME' : 'http',
42 'CONTEXT_PREFIX' : '/',
43 'SERVER_ADMIN' : 'webmaster@localhost',
44 'REMOTE_PORT' : '49319',
45 'GATEWAY_INTERFACE' : 'CGI/1.1',
46 'SERVER_PROTOCOL' : 'HTTP/1.1',
47 'REQUEST_METHOD' : 'GET',
48 'REDIRECT_STATUS' : 'CGI'
52 def make_todo_list(context, result_id):
54 context.execute_steps("then at least 1 result is returned")
55 return range(len(context.response.result))
57 context.execute_steps(f"then more than {result_id}results are returned")
58 return (int(result_id.strip()), )
61 def compare(operator, op1, op2):
62 if operator == 'less than':
64 elif operator == 'more than':
66 elif operator == 'exactly':
68 elif operator == 'at least':
70 elif operator == 'at most':
73 raise ValueError(f"Unknown operator '{operator}'")
76 def send_api_query(endpoint, params, fmt, context):
78 if fmt.strip() == 'debug':
81 params['format'] = fmt.strip()
84 if context.table.headings[0] == 'param':
85 for line in context.table:
86 params[line['param']] = line['value']
88 for h in context.table.headings:
89 params[h] = context.table[0][h]
91 if context.nominatim.api_engine is None:
92 return send_api_query_php(endpoint, params, context)
94 return asyncio.run(context.nominatim.api_engine(endpoint, params,
95 Path(context.nominatim.website_dir.name),
96 context.nominatim.test_env,
97 getattr(context, 'http_headers', {})))
101 def send_api_query_php(endpoint, params, context):
102 env = dict(BASE_SERVER_ENV)
103 env['QUERY_STRING'] = urlencode(params)
105 env['SCRIPT_NAME'] = f'/{endpoint}.php'
106 env['REQUEST_URI'] = f"{env['SCRIPT_NAME']}?{env['QUERY_STRING']}"
107 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.website_dir.name, 'website')
108 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
111 LOG.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
113 if hasattr(context, 'http_headers'):
114 for k, v in context.http_headers.items():
115 env['HTTP_' + k.upper().replace('-', '_')] = v
117 cmd = ['/usr/bin/env', 'php-cgi', '-f', env['SCRIPT_FILENAME']]
119 for k,v in params.items():
120 cmd.append(f"{k}={v}")
122 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
124 assert len(err) == 0, f"Unexpected PHP error: {err}"
126 if outp.startswith('Status: '):
127 status = int(outp[8:11])
131 content_start = outp.find('\r\n\r\n')
133 return outp[content_start + 4:], status
135 @given(u'the HTTP header')
136 def add_http_header(context):
137 if not hasattr(context, 'http_headers'):
138 context.http_headers = {}
140 for h in context.table.headings:
141 context.http_headers[h] = context.table[0][h]
144 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
145 def website_search_request(context, fmt, query, addr):
150 params['addressdetails'] = '1'
152 outp, status = send_api_query('search', params, fmt, context)
154 context.response = SearchResponse(outp, fmt or 'json', status)
157 @when('sending v1/reverse at (?P<lat>[\d.-]*),(?P<lon>[\d.-]*)(?: with format (?P<fmt>.+))?')
158 def api_endpoint_v1_reverse(context, lat, lon, fmt):
169 outp, status = send_api_query('reverse', params, fmt, context)
170 context.response = ReverseResponse(outp, fmt or 'xml', status)
173 @when('sending v1/reverse N(?P<nodeid>\d+)(?: with format (?P<fmt>.+))?')
174 def api_endpoint_v1_reverse_from_node(context, nodeid, fmt):
176 params['lon'], params['lat'] = (f'{c:f}' for c in context.osm.grid_node(int(nodeid)))
178 outp, status = send_api_query('reverse', params, fmt, context)
179 context.response = ReverseResponse(outp, fmt or 'xml', status)
182 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
183 def website_details_request(context, fmt, query):
185 if query[0] in 'NWR':
186 nid = NominatimID(query)
187 params['osmtype'] = nid.typ
188 params['osmid'] = nid.oid
190 params['class'] = nid.cls
192 params['place_id'] = query
193 outp, status = send_api_query('details', params, fmt, context)
195 context.response = GenericResponse(outp, fmt or 'json', status)
197 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
198 def website_lookup_request(context, fmt, query):
199 params = { 'osm_ids' : query }
200 outp, status = send_api_query('lookup', params, fmt, context)
202 context.response = SearchResponse(outp, fmt or 'xml', status)
204 @when(u'sending (?P<fmt>\S+ )?status query')
205 def website_status_request(context, fmt):
207 outp, status = send_api_query('status', params, fmt, context)
209 context.response = StatusResponse(outp, fmt or 'text', status)
211 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
212 def validate_result_number(context, operator, number):
213 context.execute_steps("Then a HTTP 200 is returned")
214 numres = len(context.response.result)
215 assert compare(operator, numres, int(number)), \
216 f"Bad number of results: expected {operator} {number}, got {numres}."
218 @then(u'a HTTP (?P<status>\d+) is returned')
219 def check_http_return_status(context, status):
220 assert context.response.errorcode == int(status), \
221 f"Return HTTP status is {context.response.errorcode}."\
222 f" Full response:\n{context.response.page}"
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 if fmt.strip() == 'html':
233 tree = ET.fromstring(context.response.page)
234 except Exception as ex:
235 assert False, f"Could not parse page: {ex}\n{context.response.page}"
237 assert tree.tag == 'html'
238 body = tree.find('./body')
239 assert body is not None
240 assert body.find('.//script') is None
242 assert context.response.format == fmt
245 @then(u'a (?P<fmt>\w+) user error is returned')
246 def check_page_error(context, fmt):
247 context.execute_steps("Then a HTTP 400 is returned")
248 assert context.response.format == fmt
251 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
253 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
255 @then(u'result header contains')
256 def check_header_attr(context):
257 context.execute_steps("Then a HTTP 200 is returned")
258 for line in context.table:
259 assert line['attr'] in context.response.header, \
260 f"Field '{line['attr']}' missing in header. Full header:\n{context.response.header}"
261 value = context.response.header[line['attr']]
262 assert re.fullmatch(line['value'], value) is not None, \
263 f"Attribute '{line['attr']}': expected: '{line['value']}', got '{value}'"
266 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
267 def check_header_no_attr(context, neg, attrs):
268 check_for_attributes(context.response.header, attrs,
269 'absent' if neg else 'present')
272 @then(u'results contain(?: in field (?P<field>.*))?')
273 def step_impl(context, field):
274 context.execute_steps("then at least 1 result is returned")
276 for line in context.table:
277 context.response.match_row(line, context=context, field=field)
280 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
281 def validate_attributes(context, lid, neg, attrs):
282 for i in make_todo_list(context, lid):
283 check_for_attributes(context.response.result[i], attrs,
284 'absent' if neg else 'present')
287 @then(u'result addresses contain')
288 def step_impl(context):
289 context.execute_steps("then at least 1 result is returned")
291 for line in context.table:
292 idx = int(line['ID']) if 'ID' in line.headings else None
294 for name, value in zip(line.headings, line.cells):
296 context.response.assert_address_field(idx, name, value)
298 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
299 def check_address(context, lid, neg, attrs):
300 context.execute_steps(f"then more than {lid} results are returned")
302 addr_parts = context.response.result[int(lid)]['address']
304 for attr in attrs.split(','):
306 assert attr not in addr_parts
308 assert attr in addr_parts
310 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
311 def check_address(context, lid, complete):
312 context.execute_steps(f"then more than {lid} results are returned")
315 addr_parts = dict(context.response.result[lid]['address'])
317 for line in context.table:
318 context.response.assert_address_field(lid, line['type'], line['value'])
319 del addr_parts[line['type']]
322 assert len(addr_parts) == 0, f"Additional address parts found: {addr_parts!s}"
325 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
326 def check_bounding_box_in_area(context, lid, coords):
327 expected = Bbox(coords)
329 for idx in make_todo_list(context, lid):
330 res = context.response.result[idx]
331 check_for_attributes(res, 'boundingbox')
332 context.response.check_row(idx, res['boundingbox'] in expected,
333 f"Bbox is not contained in {expected}")
336 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
337 def check_centroid_in_area(context, lid, coords):
338 expected = Bbox(coords)
340 for idx in make_todo_list(context, lid):
341 res = context.response.result[idx]
342 check_for_attributes(res, 'lat,lon')
343 context.response.check_row(idx, (res['lon'], res['lat']) in expected,
344 f"Centroid is not inside {expected}")
347 @then(u'there are(?P<neg> no)? duplicates')
348 def check_for_duplicates(context, neg):
349 context.execute_steps("then at least 1 result is returned")
354 for res in context.response.result:
355 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
362 assert not has_dupe, f"Found duplicate for {dup}"
364 assert has_dupe, "No duplicates found"