1 """ Steps that run search queries.
3 Queries may either be run directly via PHP using the query script
4 or via the HTTP interface.
12 import xml.etree.ElementTree as ET
14 from urllib.parse import urlencode
15 from collections import OrderedDict
17 from check_functions import Almost
19 logger = logging.getLogger(__name__)
22 'HTTP_HOST' : 'localhost',
23 'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
24 'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
25 'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
26 'HTTP_CONNECTION' : 'keep-alive',
27 'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
28 'SERVER_SOFTWARE' : 'Nominatim test',
29 'SERVER_NAME' : 'localhost',
30 'SERVER_ADDR' : '127.0.1.1',
32 'REMOTE_ADDR' : '127.0.0.1',
33 'DOCUMENT_ROOT' : '/var/www',
34 'REQUEST_SCHEME' : 'http',
35 'CONTEXT_PREFIX' : '/',
36 'SERVER_ADMIN' : 'webmaster@localhost',
37 'REMOTE_PORT' : '49319',
38 'GATEWAY_INTERFACE' : 'CGI/1.1',
39 'SERVER_PROTOCOL' : 'HTTP/1.1',
40 'REQUEST_METHOD' : 'GET',
41 'REDIRECT_STATUS' : 'CGI'
45 def compare(operator, op1, op2):
46 if operator == 'less than':
48 elif operator == 'more than':
50 elif operator == 'exactly':
52 elif operator == 'at least':
54 elif operator == 'at most':
57 raise Exception("unknown operator '%s'" % operator)
59 class GenericResponse(object):
61 def match_row(self, row):
62 if 'ID' in row.headings:
63 todo = [int(row['ID'])]
65 todo = range(len(self.result))
69 for h in row.headings:
73 assert res['osm_type'] == row[h][0]
74 assert res['osm_id'] == int(row[h][1:])
76 x, y = row[h].split(' ')
77 assert Almost(float(y)) == float(res['lat'])
78 assert Almost(float(x)) == float(res['lon'])
79 elif row[h].startswith("^"):
81 assert re.fullmatch(row[h], res[h]) is not None, \
82 "attribute '%s': expected: '%s', got '%s'" % (h, row[h], res[h])
85 assert str(res[h]) == str(row[h])
87 def property_list(self, prop):
88 return [ x[prop] for x in self.result ]
91 class SearchResponse(GenericResponse):
93 def __init__(self, page, fmt='json', errorcode=200):
96 self.errorcode = errorcode
101 getattr(self, 'parse_' + fmt)()
103 def parse_json(self):
104 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
109 self.header['json_func'] = m.group(1)
110 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
112 def parse_geojson(self):
114 self.result = geojson_results_to_json_results(self.result)
116 def parse_geocodejson(self):
118 if self.result is not None:
119 self.result = [r['geocoding'] for r in self.result]
122 et = ET.fromstring(self.page)
124 self.header = dict(et.attrib)
127 assert child.tag == "place"
128 self.result.append(dict(child.attrib))
132 if sub.tag == 'extratags':
133 self.result[-1]['extratags'] = {}
135 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
136 elif sub.tag == 'namedetails':
137 self.result[-1]['namedetails'] = {}
139 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
140 elif sub.tag in ('geokml'):
141 self.result[-1][sub.tag] = True
143 address[sub.tag] = sub.text
146 self.result[-1]['address'] = address
149 class ReverseResponse(GenericResponse):
151 def __init__(self, page, fmt='json', errorcode=200):
154 self.errorcode = errorcode
159 getattr(self, 'parse_' + fmt)()
161 def parse_json(self):
162 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
167 self.header['json_func'] = m.group(1)
168 self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)]
170 def parse_geojson(self):
172 if 'error' in self.result:
174 self.result = geojson_results_to_json_results(self.result[0])
176 def parse_geocodejson(self):
178 if self.result is not None:
179 self.result = [r['geocoding'] for r in self.result]
182 et = ET.fromstring(self.page)
184 self.header = dict(et.attrib)
188 if child.tag == 'result':
189 assert len(self.result) == 0, "More than one result in reverse result"
190 self.result.append(dict(child.attrib))
191 elif child.tag == 'addressparts':
194 address[sub.tag] = sub.text
195 self.result[0]['address'] = address
196 elif child.tag == 'extratags':
197 self.result[0]['extratags'] = {}
199 self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
200 elif child.tag == 'namedetails':
201 self.result[0]['namedetails'] = {}
203 self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
204 elif child.tag in ('geokml'):
205 self.result[0][child.tag] = True
207 assert child.tag == 'error', \
208 "Unknown XML tag %s on page: %s" % (child.tag, self.page)
211 class DetailsResponse(GenericResponse):
213 def __init__(self, page, fmt='json', errorcode=200):
216 self.errorcode = errorcode
221 getattr(self, 'parse_' + fmt)()
223 def parse_json(self):
224 self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
227 class StatusResponse(GenericResponse):
229 def __init__(self, page, fmt='text', errorcode=200):
232 self.errorcode = errorcode
234 if errorcode == 200 and fmt != 'text':
235 getattr(self, 'parse_' + fmt)()
237 def parse_json(self):
238 self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
241 def geojson_result_to_json_result(geojson_result):
242 result = geojson_result['properties']
243 result['geojson'] = geojson_result['geometry']
244 if 'bbox' in geojson_result:
245 # bbox is minlon, minlat, maxlon, maxlat
246 # boundingbox is minlat, maxlat, minlon, maxlon
247 result['boundingbox'] = [
248 geojson_result['bbox'][1],
249 geojson_result['bbox'][3],
250 geojson_result['bbox'][0],
251 geojson_result['bbox'][2]
256 def geojson_results_to_json_results(geojson_results):
257 if 'error' in geojson_results:
259 return list(map(geojson_result_to_json_result, geojson_results['features']))
262 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
263 def query_cmd(context, query, dups):
264 """ Query directly via PHP script.
266 cmd = ['/usr/bin/env', 'php']
267 cmd.append(os.path.join(context.nominatim.build_dir, 'utils', 'query.php'))
269 cmd.extend(['--search', query])
270 # add more parameters in table form
272 for h in context.table.headings:
273 value = context.table[0][h].strip()
275 cmd.extend(('--' + h, value))
278 cmd.extend(('--dedupe', '0'))
280 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
281 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
282 (outp, err) = proc.communicate()
284 assert proc.returncode == 0, "query.php failed with message: %s\noutput: %s" % (err, outp)
285 logger.debug("run_nominatim_script: %s\n%s\n" % (cmd, outp.decode('utf-8').replace('\\n', '\n')))
287 context.response = SearchResponse(outp.decode('utf-8'), 'json')
289 def send_api_query(endpoint, params, fmt, context):
291 params['format'] = fmt.strip()
293 if context.table.headings[0] == 'param':
294 for line in context.table:
295 params[line['param']] = line['value']
297 for h in context.table.headings:
298 params[h] = context.table[0][h]
300 env = dict(BASE_SERVER_ENV)
301 env['QUERY_STRING'] = urlencode(params)
303 env['SCRIPT_NAME'] = '/%s.php' % endpoint
304 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
305 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
306 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
308 env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
310 logger.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
312 if hasattr(context, 'http_headers'):
313 env.update(context.http_headers)
315 cmd = ['/usr/bin/env', 'php-cgi', '-f']
316 if context.nominatim.code_coverage_path:
317 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
318 env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
319 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
320 env['SCRIPT_FILENAME'] = \
321 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
322 cmd.append(env['SCRIPT_FILENAME'])
323 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
325 cmd.append(env['SCRIPT_FILENAME'])
327 for k,v in params.items():
328 cmd.append("%s=%s" % (k, v))
330 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
331 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
333 (outp, err) = proc.communicate()
334 outp = outp.decode('utf-8')
335 err = err.decode("utf-8")
337 logger.debug("Result: \n===============================\n"
338 + outp + "\n===============================\n")
340 assert proc.returncode == 0, \
341 "%s failed with message: %s" % (
342 os.path.basename(env['SCRIPT_FILENAME']), err)
344 assert len(err) == 0, "Unexpected PHP error: %s" % (err)
346 if outp.startswith('Status: '):
347 status = int(outp[8:11])
351 content_start = outp.find('\r\n\r\n')
353 return outp[content_start + 4:], status
355 @given(u'the HTTP header')
356 def add_http_header(context):
357 if not hasattr(context, 'http_headers'):
358 context.http_headers = {}
360 for h in context.table.headings:
361 envvar = 'HTTP_' + h.upper().replace('-', '_')
362 context.http_headers[envvar] = context.table[0][h]
365 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
366 def website_search_request(context, fmt, query, addr):
371 params['addressdetails'] = '1'
373 outp, status = send_api_query('search', params, fmt, context)
375 if fmt is None or fmt == 'jsonv2 ':
380 context.response = SearchResponse(outp, outfmt, status)
382 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
383 def website_reverse_request(context, fmt, lat, lon):
390 outp, status = send_api_query('reverse', params, fmt, context)
394 elif fmt == 'jsonv2 ':
399 context.response = ReverseResponse(outp, outfmt, status)
401 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
402 def website_details_request(context, fmt, query):
404 if query[0] in 'NWR':
405 params['osmtype'] = query[0]
406 params['osmid'] = query[1:]
408 params['place_id'] = query
409 outp, status = send_api_query('details', params, fmt, context)
416 context.response = DetailsResponse(outp, outfmt, status)
418 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
419 def website_lookup_request(context, fmt, query):
420 params = { 'osm_ids' : query }
421 outp, status = send_api_query('lookup', params, fmt, context)
425 elif fmt == 'jsonv2 ':
427 elif fmt == 'geojson ':
429 elif fmt == 'geocodejson ':
430 outfmt = 'geocodejson'
434 context.response = SearchResponse(outp, outfmt, status)
436 @when(u'sending (?P<fmt>\S+ )?status query')
437 def website_status_request(context, fmt):
439 outp, status = send_api_query('status', params, fmt, context)
446 context.response = StatusResponse(outp, outfmt, status)
448 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
449 def validate_result_number(context, operator, number):
450 assert context.response.errorcode == 200
451 numres = len(context.response.result)
452 assert compare(operator, numres, int(number)), \
453 "Bad number of results: expected %s %s, got %d." % (operator, number, numres)
455 @then(u'a HTTP (?P<status>\d+) is returned')
456 def check_http_return_status(context, status):
457 assert context.response.errorcode == int(status)
459 @then(u'the page contents equals "(?P<text>.+)"')
460 def check_page_content_equals(context, text):
461 assert context.response.page == text
463 @then(u'the result is valid (?P<fmt>\w+)')
464 def step_impl(context, fmt):
465 context.execute_steps("Then a HTTP 200 is returned")
466 assert context.response.format == fmt
468 @then(u'a (?P<fmt>\w+) user error is returned')
469 def check_page_error(context, fmt):
470 context.execute_steps("Then a HTTP 400 is returned")
471 assert context.response.format == fmt
474 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
476 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
478 @then(u'result header contains')
479 def check_header_attr(context):
480 for line in context.table:
481 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
482 "attribute '%s': expected: '%s', got '%s'" % (
483 line['attr'], line['value'],
484 context.response.header[line['attr']])
486 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
487 def check_header_no_attr(context, neg, attrs):
488 for attr in attrs.split(','):
490 assert attr not in context.response.header
492 assert attr in context.response.header
494 @then(u'results contain')
495 def step_impl(context):
496 context.execute_steps("then at least 1 result is returned")
498 for line in context.table:
499 context.response.match_row(line)
501 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
502 def validate_attributes(context, lid, neg, attrs):
504 idx = range(len(context.response.result))
505 context.execute_steps("then at least 1 result is returned")
507 idx = [int(lid.strip())]
508 context.execute_steps("then more than %sresults are returned" % lid)
511 for attr in attrs.split(','):
513 assert attr not in context.response.result[i]
515 assert attr in context.response.result[i]
517 @then(u'result addresses contain')
518 def step_impl(context):
519 context.execute_steps("then at least 1 result is returned")
521 if 'ID' not in context.table.headings:
522 addr_parts = context.response.property_list('address')
524 for line in context.table:
525 if 'ID' in context.table.headings:
526 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
528 for h in context.table.headings:
532 assert p[h] == line[h], "Bad address value for %s" % h
534 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
535 def check_address(context, lid, neg, attrs):
536 context.execute_steps("then more than %s results are returned" % lid)
538 addr_parts = context.response.result[int(lid)]['address']
540 for attr in attrs.split(','):
542 assert attr not in addr_parts
544 assert attr in addr_parts
546 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
547 def check_address(context, lid, complete):
548 context.execute_steps("then more than %s results are returned" % lid)
550 addr_parts = dict(context.response.result[int(lid)]['address'])
552 for line in context.table:
553 assert line['type'] in addr_parts
554 assert addr_parts[line['type']] == line['value'], \
555 "Bad address value for %s" % line['type']
556 del addr_parts[line['type']]
559 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
561 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
562 def step_impl(context, lid, coords):
564 context.execute_steps("then at least 1 result is returned")
565 bboxes = context.response.property_list('boundingbox')
567 context.execute_steps("then more than %sresults are returned" % lid)
568 bboxes = [ context.response.result[int(lid)]['boundingbox']]
570 coord = [ float(x) for x in coords.split(',') ]
573 if isinstance(bbox, str):
574 bbox = bbox.split(',')
575 bbox = [ float(x) for x in bbox ]
577 assert bbox[0] >= coord[0]
578 assert bbox[1] <= coord[1]
579 assert bbox[2] >= coord[2]
580 assert bbox[3] <= coord[3]
582 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
583 def step_impl(context, lid, coords):
585 context.execute_steps("then at least 1 result is returned")
586 bboxes = zip(context.response.property_list('lat'),
587 context.response.property_list('lon'))
589 context.execute_steps("then more than %sresults are returned" % lid)
590 res = context.response.result[int(lid)]
591 bboxes = [ (res['lat'], res['lon']) ]
593 coord = [ float(x) for x in coords.split(',') ]
595 for lat, lon in bboxes:
598 assert lat >= coord[0]
599 assert lat <= coord[1]
600 assert lon >= coord[2]
601 assert lon <= coord[3]
603 @then(u'there are(?P<neg> no)? duplicates')
604 def check_for_duplicates(context, neg):
605 context.execute_steps("then at least 1 result is returned")
610 for res in context.response.result:
611 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
618 assert not has_dupe, "Found duplicate for %s" % (dup, )
620 assert has_dupe, "No duplicates found"