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.website_dir.name, 'website')
306 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
309 logger.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
311 if hasattr(context, 'http_headers'):
312 env.update(context.http_headers)
314 cmd = ['/usr/bin/env', 'php-cgi', '-f']
315 if context.nominatim.code_coverage_path:
316 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
317 env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
318 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
319 env['SCRIPT_FILENAME'] = \
320 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
321 cmd.append(env['SCRIPT_FILENAME'])
322 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
324 cmd.append(env['SCRIPT_FILENAME'])
326 for k,v in params.items():
327 cmd.append("%s=%s" % (k, v))
329 proc = subprocess.Popen(cmd, cwd=context.nominatim.website_dir.name, env=env,
330 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
332 (outp, err) = proc.communicate()
333 outp = outp.decode('utf-8')
334 err = err.decode("utf-8")
336 logger.debug("Result: \n===============================\n"
337 + outp + "\n===============================\n")
339 assert proc.returncode == 0, \
340 "%s failed with message: %s" % (
341 os.path.basename(env['SCRIPT_FILENAME']), err)
343 assert len(err) == 0, "Unexpected PHP error: %s" % (err)
345 if outp.startswith('Status: '):
346 status = int(outp[8:11])
350 content_start = outp.find('\r\n\r\n')
352 return outp[content_start + 4:], status
354 @given(u'the HTTP header')
355 def add_http_header(context):
356 if not hasattr(context, 'http_headers'):
357 context.http_headers = {}
359 for h in context.table.headings:
360 envvar = 'HTTP_' + h.upper().replace('-', '_')
361 context.http_headers[envvar] = context.table[0][h]
364 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
365 def website_search_request(context, fmt, query, addr):
370 params['addressdetails'] = '1'
372 outp, status = send_api_query('search', params, fmt, context)
374 if fmt is None or fmt == 'jsonv2 ':
379 context.response = SearchResponse(outp, outfmt, status)
381 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
382 def website_reverse_request(context, fmt, lat, lon):
389 outp, status = send_api_query('reverse', params, fmt, context)
393 elif fmt == 'jsonv2 ':
398 context.response = ReverseResponse(outp, outfmt, status)
400 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
401 def website_details_request(context, fmt, query):
403 if query[0] in 'NWR':
404 params['osmtype'] = query[0]
405 params['osmid'] = query[1:]
407 params['place_id'] = query
408 outp, status = send_api_query('details', params, fmt, context)
415 context.response = DetailsResponse(outp, outfmt, status)
417 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
418 def website_lookup_request(context, fmt, query):
419 params = { 'osm_ids' : query }
420 outp, status = send_api_query('lookup', params, fmt, context)
424 elif fmt == 'jsonv2 ':
426 elif fmt == 'geojson ':
428 elif fmt == 'geocodejson ':
429 outfmt = 'geocodejson'
433 context.response = SearchResponse(outp, outfmt, status)
435 @when(u'sending (?P<fmt>\S+ )?status query')
436 def website_status_request(context, fmt):
438 outp, status = send_api_query('status', params, fmt, context)
445 context.response = StatusResponse(outp, outfmt, status)
447 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
448 def validate_result_number(context, operator, number):
449 assert context.response.errorcode == 200
450 numres = len(context.response.result)
451 assert compare(operator, numres, int(number)), \
452 "Bad number of results: expected %s %s, got %d." % (operator, number, numres)
454 @then(u'a HTTP (?P<status>\d+) is returned')
455 def check_http_return_status(context, status):
456 assert context.response.errorcode == int(status)
458 @then(u'the page contents equals "(?P<text>.+)"')
459 def check_page_content_equals(context, text):
460 assert context.response.page == text
462 @then(u'the result is valid (?P<fmt>\w+)')
463 def step_impl(context, fmt):
464 context.execute_steps("Then a HTTP 200 is returned")
465 assert context.response.format == fmt
467 @then(u'a (?P<fmt>\w+) user error is returned')
468 def check_page_error(context, fmt):
469 context.execute_steps("Then a HTTP 400 is returned")
470 assert context.response.format == fmt
473 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
475 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
477 @then(u'result header contains')
478 def check_header_attr(context):
479 for line in context.table:
480 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
481 "attribute '%s': expected: '%s', got '%s'" % (
482 line['attr'], line['value'],
483 context.response.header[line['attr']])
485 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
486 def check_header_no_attr(context, neg, attrs):
487 for attr in attrs.split(','):
489 assert attr not in context.response.header
491 assert attr in context.response.header
493 @then(u'results contain')
494 def step_impl(context):
495 context.execute_steps("then at least 1 result is returned")
497 for line in context.table:
498 context.response.match_row(line)
500 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
501 def validate_attributes(context, lid, neg, attrs):
503 idx = range(len(context.response.result))
504 context.execute_steps("then at least 1 result is returned")
506 idx = [int(lid.strip())]
507 context.execute_steps("then more than %sresults are returned" % lid)
510 for attr in attrs.split(','):
512 assert attr not in context.response.result[i]
514 assert attr in context.response.result[i]
516 @then(u'result addresses contain')
517 def step_impl(context):
518 context.execute_steps("then at least 1 result is returned")
520 if 'ID' not in context.table.headings:
521 addr_parts = context.response.property_list('address')
523 for line in context.table:
524 if 'ID' in context.table.headings:
525 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
527 for h in context.table.headings:
531 assert p[h] == line[h], "Bad address value for %s" % h
533 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
534 def check_address(context, lid, neg, attrs):
535 context.execute_steps("then more than %s results are returned" % lid)
537 addr_parts = context.response.result[int(lid)]['address']
539 for attr in attrs.split(','):
541 assert attr not in addr_parts
543 assert attr in addr_parts
545 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
546 def check_address(context, lid, complete):
547 context.execute_steps("then more than %s results are returned" % lid)
549 addr_parts = dict(context.response.result[int(lid)]['address'])
551 for line in context.table:
552 assert line['type'] in addr_parts
553 assert addr_parts[line['type']] == line['value'], \
554 "Bad address value for %s" % line['type']
555 del addr_parts[line['type']]
558 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
560 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
561 def step_impl(context, lid, coords):
563 context.execute_steps("then at least 1 result is returned")
564 bboxes = context.response.property_list('boundingbox')
566 context.execute_steps("then more than %sresults are returned" % lid)
567 bboxes = [ context.response.result[int(lid)]['boundingbox']]
569 coord = [ float(x) for x in coords.split(',') ]
572 if isinstance(bbox, str):
573 bbox = bbox.split(',')
574 bbox = [ float(x) for x in bbox ]
576 assert bbox[0] >= coord[0]
577 assert bbox[1] <= coord[1]
578 assert bbox[2] >= coord[2]
579 assert bbox[3] <= coord[3]
581 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
582 def step_impl(context, lid, coords):
584 context.execute_steps("then at least 1 result is returned")
585 bboxes = zip(context.response.property_list('lat'),
586 context.response.property_list('lon'))
588 context.execute_steps("then more than %sresults are returned" % lid)
589 res = context.response.result[int(lid)]
590 bboxes = [ (res['lat'], res['lon']) ]
592 coord = [ float(x) for x in coords.split(',') ]
594 for lat, lon in bboxes:
597 assert lat >= coord[0]
598 assert lat <= coord[1]
599 assert lon >= coord[2]
600 assert lon <= coord[3]
602 @then(u'there are(?P<neg> no)? duplicates')
603 def check_for_duplicates(context, neg):
604 context.execute_steps("then at least 1 result is returned")
609 for res in context.response.result:
610 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
617 assert not has_dupe, "Found duplicate for %s" % (dup, )
619 assert has_dupe, "No duplicates found"