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))
86 def send_api_query_php(endpoint, params, context):
87 env = dict(BASE_SERVER_ENV)
88 env['QUERY_STRING'] = urlencode(params)
90 env['SCRIPT_NAME'] = '/%s.php' % endpoint
91 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
92 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.website_dir.name, 'website')
93 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
96 LOG.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
98 if hasattr(context, 'http_headers'):
99 env.update(context.http_headers)
101 cmd = ['/usr/bin/env', 'php-cgi', '-f']
102 if context.nominatim.code_coverage_path:
103 env['XDEBUG_MODE'] = 'coverage'
104 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
105 env['COV_PHP_DIR'] = context.nominatim.src_dir
106 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
107 env['SCRIPT_FILENAME'] = \
108 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
109 cmd.append(env['SCRIPT_FILENAME'])
110 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
112 cmd.append(env['SCRIPT_FILENAME'])
114 for k,v in params.items():
115 cmd.append("%s=%s" % (k, v))
117 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
119 assert len(err) == 0, "Unexpected PHP error: %s" % (err)
121 if outp.startswith('Status: '):
122 status = int(outp[8:11])
126 content_start = outp.find('\r\n\r\n')
128 return outp[content_start + 4:], status
130 @given(u'the HTTP header')
131 def add_http_header(context):
132 if not hasattr(context, 'http_headers'):
133 context.http_headers = {}
135 for h in context.table.headings:
136 envvar = 'HTTP_' + h.upper().replace('-', '_')
137 context.http_headers[envvar] = context.table[0][h]
140 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
141 def website_search_request(context, fmt, query, addr):
146 params['addressdetails'] = '1'
147 if fmt and fmt.strip() == 'debug':
148 params['debug'] = '1'
150 outp, status = send_api_query('search', params, fmt, context)
152 context.response = SearchResponse(outp, fmt or 'json', status)
154 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
155 def website_reverse_request(context, fmt, lat, lon):
161 if fmt and fmt.strip() == 'debug':
162 params['debug'] = '1'
164 outp, status = send_api_query('reverse', params, fmt, context)
166 context.response = ReverseResponse(outp, fmt or 'xml', status)
168 @when(u'sending (?P<fmt>\S+ )?reverse point (?P<nodeid>.+)')
169 def website_reverse_request(context, fmt, nodeid):
171 if fmt and fmt.strip() == 'debug':
172 params['debug'] = '1'
173 params['lon'], params['lat'] = (f'{c:f}' for c in context.osm.grid_node(int(nodeid)))
176 outp, status = send_api_query('reverse', params, fmt, context)
178 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 assert context.response.errorcode == 200
214 numres = len(context.response.result)
215 assert compare(operator, numres, int(number)), \
216 "Bad number of results: expected {} {}, got {}.".format(operator, number, 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 "Return HTTP status is {}.".format(context.response.errorcode)
223 @then(u'the page contents equals "(?P<text>.+)"')
224 def check_page_content_equals(context, text):
225 assert context.response.page == text
227 @then(u'the result is valid (?P<fmt>\w+)')
228 def step_impl(context, fmt):
229 context.execute_steps("Then a HTTP 200 is returned")
230 assert context.response.format == fmt
232 @then(u'a (?P<fmt>\w+) user error is returned')
233 def check_page_error(context, fmt):
234 context.execute_steps("Then a HTTP 400 is returned")
235 assert context.response.format == fmt
238 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
240 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
242 @then(u'result header contains')
243 def check_header_attr(context):
244 for line in context.table:
245 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
246 "attribute '%s': expected: '%s', got '%s'" % (
247 line['attr'], line['value'],
248 context.response.header[line['attr']])
250 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
251 def check_header_no_attr(context, neg, attrs):
252 for attr in attrs.split(','):
254 assert attr not in context.response.header, \
255 "Unexpected attribute {}. Full response:\n{}".format(
256 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
258 assert attr in context.response.header, \
259 "No attribute {}. Full response:\n{}".format(
260 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
262 @then(u'results contain')
263 def step_impl(context):
264 context.execute_steps("then at least 1 result is returned")
266 for line in context.table:
267 context.response.match_row(line, context=context)
269 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
270 def validate_attributes(context, lid, neg, attrs):
272 idx = range(len(context.response.result))
273 context.execute_steps("then at least 1 result is returned")
275 idx = [int(lid.strip())]
276 context.execute_steps("then more than %sresults are returned" % lid)
279 for attr in attrs.split(','):
281 assert attr not in context.response.result[i],\
282 "Unexpected attribute {}. Full response:\n{}".format(
283 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
285 assert attr in context.response.result[i], \
286 "No attribute {}. Full response:\n{}".format(
287 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
289 @then(u'result addresses contain')
290 def step_impl(context):
291 context.execute_steps("then at least 1 result is returned")
293 for line in context.table:
294 idx = int(line['ID']) if 'ID' in line.headings else None
296 for name, value in zip(line.headings, line.cells):
298 context.response.assert_address_field(idx, name, value)
300 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
301 def check_address(context, lid, neg, attrs):
302 context.execute_steps("then more than %s results are returned" % lid)
304 addr_parts = context.response.result[int(lid)]['address']
306 for attr in attrs.split(','):
308 assert attr not in addr_parts
310 assert attr in addr_parts
312 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
313 def check_address(context, lid, complete):
314 context.execute_steps("then more than %s results are returned" % lid)
317 addr_parts = dict(context.response.result[lid]['address'])
319 for line in context.table:
320 context.response.assert_address_field(lid, line['type'], line['value'])
321 del addr_parts[line['type']]
324 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
326 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
327 def step_impl(context, lid, coords):
329 context.execute_steps("then at least 1 result is returned")
330 bboxes = context.response.property_list('boundingbox')
332 context.execute_steps("then more than {}results are returned".format(lid))
333 bboxes = [context.response.result[int(lid)]['boundingbox']]
335 expected = Bbox(coords)
338 assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
340 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
341 def step_impl(context, lid, coords):
343 context.execute_steps("then at least 1 result is returned")
344 centroids = zip(context.response.property_list('lon'),
345 context.response.property_list('lat'))
347 context.execute_steps("then more than %sresults are returned".format(lid))
348 res = context.response.result[int(lid)]
349 centroids = [(res['lon'], res['lat'])]
351 expected = Bbox(coords)
353 for centroid in centroids:
354 assert centroid in expected,\
355 "Centroid {} is not inside {}.".format(centroid, expected)
357 @then(u'there are(?P<neg> no)? duplicates')
358 def check_for_duplicates(context, neg):
359 context.execute_steps("then at least 1 result is returned")
364 for res in context.response.result:
365 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
372 assert not has_dupe, "Found duplicate for %s" % (dup, )
374 assert has_dupe, "No duplicates found"