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+ )?details query for (?P<query>.*)')
157 def website_details_request(context, fmt, query):
159 if query[0] in 'NWR':
160 nid = NominatimID(query)
161 params['osmtype'] = nid.typ
162 params['osmid'] = nid.oid
164 params['class'] = nid.cls
166 params['place_id'] = query
167 outp, status = send_api_query('details', params, fmt, context)
169 context.response = GenericResponse(outp, fmt or 'json', status)
171 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
172 def website_lookup_request(context, fmt, query):
173 params = { 'osm_ids' : query }
174 outp, status = send_api_query('lookup', params, fmt, context)
176 context.response = SearchResponse(outp, fmt or 'xml', status)
178 @when(u'sending (?P<fmt>\S+ )?status query')
179 def website_status_request(context, fmt):
181 outp, status = send_api_query('status', params, fmt, context)
183 context.response = StatusResponse(outp, fmt or 'text', status)
185 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
186 def validate_result_number(context, operator, number):
187 assert context.response.errorcode == 200
188 numres = len(context.response.result)
189 assert compare(operator, numres, int(number)), \
190 "Bad number of results: expected {} {}, got {}.".format(operator, number, numres)
192 @then(u'a HTTP (?P<status>\d+) is returned')
193 def check_http_return_status(context, status):
194 assert context.response.errorcode == int(status), \
195 "Return HTTP status is {}.".format(context.response.errorcode)
197 @then(u'the page contents equals "(?P<text>.+)"')
198 def check_page_content_equals(context, text):
199 assert context.response.page == text
201 @then(u'the result is valid (?P<fmt>\w+)')
202 def step_impl(context, fmt):
203 context.execute_steps("Then a HTTP 200 is returned")
204 assert context.response.format == fmt
206 @then(u'a (?P<fmt>\w+) user error is returned')
207 def check_page_error(context, fmt):
208 context.execute_steps("Then a HTTP 400 is returned")
209 assert context.response.format == fmt
212 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
214 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
216 @then(u'result header contains')
217 def check_header_attr(context):
218 for line in context.table:
219 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
220 "attribute '%s': expected: '%s', got '%s'" % (
221 line['attr'], line['value'],
222 context.response.header[line['attr']])
224 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
225 def check_header_no_attr(context, neg, attrs):
226 for attr in attrs.split(','):
228 assert attr not in context.response.header, \
229 "Unexpected attribute {}. Full response:\n{}".format(
230 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
232 assert attr in context.response.header, \
233 "No attribute {}. Full response:\n{}".format(
234 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
236 @then(u'results contain')
237 def step_impl(context):
238 context.execute_steps("then at least 1 result is returned")
240 for line in context.table:
241 context.response.match_row(line)
243 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
244 def validate_attributes(context, lid, neg, attrs):
246 idx = range(len(context.response.result))
247 context.execute_steps("then at least 1 result is returned")
249 idx = [int(lid.strip())]
250 context.execute_steps("then more than %sresults are returned" % lid)
253 for attr in attrs.split(','):
255 assert attr not in context.response.result[i],\
256 "Unexpected attribute {}. Full response:\n{}".format(
257 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
259 assert attr in context.response.result[i], \
260 "No attribute {}. Full response:\n{}".format(
261 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
263 @then(u'result addresses contain')
264 def step_impl(context):
265 context.execute_steps("then at least 1 result is returned")
267 for line in context.table:
268 idx = int(line['ID']) if 'ID' in line.headings else None
270 for name, value in zip(line.headings, line.cells):
272 context.response.assert_address_field(idx, name, value)
274 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
275 def check_address(context, lid, neg, attrs):
276 context.execute_steps("then more than %s results are returned" % lid)
278 addr_parts = context.response.result[int(lid)]['address']
280 for attr in attrs.split(','):
282 assert attr not in addr_parts
284 assert attr in addr_parts
286 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
287 def check_address(context, lid, complete):
288 context.execute_steps("then more than %s results are returned" % lid)
291 addr_parts = dict(context.response.result[lid]['address'])
293 for line in context.table:
294 context.response.assert_address_field(lid, line['type'], line['value'])
295 del addr_parts[line['type']]
298 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
300 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
301 def step_impl(context, lid, coords):
303 context.execute_steps("then at least 1 result is returned")
304 bboxes = context.response.property_list('boundingbox')
306 context.execute_steps("then more than {}results are returned".format(lid))
307 bboxes = [context.response.result[int(lid)]['boundingbox']]
309 expected = Bbox(coords)
312 assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
314 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
315 def step_impl(context, lid, coords):
317 context.execute_steps("then at least 1 result is returned")
318 centroids = zip(context.response.property_list('lon'),
319 context.response.property_list('lat'))
321 context.execute_steps("then more than %sresults are returned".format(lid))
322 res = context.response.result[int(lid)]
323 centroids = [(res['lon'], res['lat'])]
325 expected = Bbox(coords)
327 for centroid in centroids:
328 assert centroid in expected,\
329 "Centroid {} is not inside {}.".format(centroid, expected)
331 @then(u'there are(?P<neg> no)? duplicates')
332 def check_for_duplicates(context, neg):
333 context.execute_steps("then at least 1 result is returned")
338 for res in context.response.result:
339 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
346 assert not has_dupe, "Found duplicate for %s" % (dup, )
348 assert has_dupe, "No duplicates found"