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
13 from urllib.parse import urlencode
14 from collections import OrderedDict
16 from check_functions import Almost
17 from utils import run_script
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 outp, err = run_script(cmd, cwd=context.nominatim.build_dir)
282 context.response = SearchResponse(outp, 'json')
284 def send_api_query(endpoint, params, fmt, context):
286 params['format'] = fmt.strip()
288 if context.table.headings[0] == 'param':
289 for line in context.table:
290 params[line['param']] = line['value']
292 for h in context.table.headings:
293 params[h] = context.table[0][h]
295 env = dict(BASE_SERVER_ENV)
296 env['QUERY_STRING'] = urlencode(params)
298 env['SCRIPT_NAME'] = '/%s.php' % endpoint
299 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
300 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.website_dir.name, 'website')
301 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
304 logger.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
306 if hasattr(context, 'http_headers'):
307 env.update(context.http_headers)
309 cmd = ['/usr/bin/env', 'php-cgi', '-f']
310 if context.nominatim.code_coverage_path:
311 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
312 env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
313 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
314 env['SCRIPT_FILENAME'] = \
315 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
316 cmd.append(env['SCRIPT_FILENAME'])
317 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
319 cmd.append(env['SCRIPT_FILENAME'])
321 for k,v in params.items():
322 cmd.append("%s=%s" % (k, v))
324 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
326 assert len(err) == 0, "Unexpected PHP error: %s" % (err)
328 if outp.startswith('Status: '):
329 status = int(outp[8:11])
333 content_start = outp.find('\r\n\r\n')
335 return outp[content_start + 4:], status
337 @given(u'the HTTP header')
338 def add_http_header(context):
339 if not hasattr(context, 'http_headers'):
340 context.http_headers = {}
342 for h in context.table.headings:
343 envvar = 'HTTP_' + h.upper().replace('-', '_')
344 context.http_headers[envvar] = context.table[0][h]
347 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
348 def website_search_request(context, fmt, query, addr):
353 params['addressdetails'] = '1'
355 outp, status = send_api_query('search', params, fmt, context)
357 if fmt is None or fmt == 'jsonv2 ':
362 context.response = SearchResponse(outp, outfmt, status)
364 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
365 def website_reverse_request(context, fmt, lat, lon):
372 outp, status = send_api_query('reverse', params, fmt, context)
376 elif fmt == 'jsonv2 ':
381 context.response = ReverseResponse(outp, outfmt, status)
383 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
384 def website_details_request(context, fmt, query):
386 if query[0] in 'NWR':
387 params['osmtype'] = query[0]
388 params['osmid'] = query[1:]
390 params['place_id'] = query
391 outp, status = send_api_query('details', params, fmt, context)
398 context.response = DetailsResponse(outp, outfmt, status)
400 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
401 def website_lookup_request(context, fmt, query):
402 params = { 'osm_ids' : query }
403 outp, status = send_api_query('lookup', params, fmt, context)
407 elif fmt == 'jsonv2 ':
409 elif fmt == 'geojson ':
411 elif fmt == 'geocodejson ':
412 outfmt = 'geocodejson'
416 context.response = SearchResponse(outp, outfmt, status)
418 @when(u'sending (?P<fmt>\S+ )?status query')
419 def website_status_request(context, fmt):
421 outp, status = send_api_query('status', params, fmt, context)
428 context.response = StatusResponse(outp, outfmt, status)
430 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
431 def validate_result_number(context, operator, number):
432 assert context.response.errorcode == 200
433 numres = len(context.response.result)
434 assert compare(operator, numres, int(number)), \
435 "Bad number of results: expected %s %s, got %d." % (operator, number, numres)
437 @then(u'a HTTP (?P<status>\d+) is returned')
438 def check_http_return_status(context, status):
439 assert context.response.errorcode == int(status)
441 @then(u'the page contents equals "(?P<text>.+)"')
442 def check_page_content_equals(context, text):
443 assert context.response.page == text
445 @then(u'the result is valid (?P<fmt>\w+)')
446 def step_impl(context, fmt):
447 context.execute_steps("Then a HTTP 200 is returned")
448 assert context.response.format == fmt
450 @then(u'a (?P<fmt>\w+) user error is returned')
451 def check_page_error(context, fmt):
452 context.execute_steps("Then a HTTP 400 is returned")
453 assert context.response.format == fmt
456 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
458 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
460 @then(u'result header contains')
461 def check_header_attr(context):
462 for line in context.table:
463 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
464 "attribute '%s': expected: '%s', got '%s'" % (
465 line['attr'], line['value'],
466 context.response.header[line['attr']])
468 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
469 def check_header_no_attr(context, neg, attrs):
470 for attr in attrs.split(','):
472 assert attr not in context.response.header
474 assert attr in context.response.header
476 @then(u'results contain')
477 def step_impl(context):
478 context.execute_steps("then at least 1 result is returned")
480 for line in context.table:
481 context.response.match_row(line)
483 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
484 def validate_attributes(context, lid, neg, attrs):
486 idx = range(len(context.response.result))
487 context.execute_steps("then at least 1 result is returned")
489 idx = [int(lid.strip())]
490 context.execute_steps("then more than %sresults are returned" % lid)
493 for attr in attrs.split(','):
495 assert attr not in context.response.result[i]
497 assert attr in context.response.result[i]
499 @then(u'result addresses contain')
500 def step_impl(context):
501 context.execute_steps("then at least 1 result is returned")
503 if 'ID' not in context.table.headings:
504 addr_parts = context.response.property_list('address')
506 for line in context.table:
507 if 'ID' in context.table.headings:
508 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
510 for h in context.table.headings:
514 assert p[h] == line[h], "Bad address value for %s" % h
516 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
517 def check_address(context, lid, neg, attrs):
518 context.execute_steps("then more than %s results are returned" % lid)
520 addr_parts = context.response.result[int(lid)]['address']
522 for attr in attrs.split(','):
524 assert attr not in addr_parts
526 assert attr in addr_parts
528 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
529 def check_address(context, lid, complete):
530 context.execute_steps("then more than %s results are returned" % lid)
532 addr_parts = dict(context.response.result[int(lid)]['address'])
534 for line in context.table:
535 assert line['type'] in addr_parts
536 assert addr_parts[line['type']] == line['value'], \
537 "Bad address value for %s" % line['type']
538 del addr_parts[line['type']]
541 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
543 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
544 def step_impl(context, lid, coords):
546 context.execute_steps("then at least 1 result is returned")
547 bboxes = context.response.property_list('boundingbox')
549 context.execute_steps("then more than %sresults are returned" % lid)
550 bboxes = [ context.response.result[int(lid)]['boundingbox']]
552 coord = [ float(x) for x in coords.split(',') ]
555 if isinstance(bbox, str):
556 bbox = bbox.split(',')
557 bbox = [ float(x) for x in bbox ]
559 assert bbox[0] >= coord[0]
560 assert bbox[1] <= coord[1]
561 assert bbox[2] >= coord[2]
562 assert bbox[3] <= coord[3]
564 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
565 def step_impl(context, lid, coords):
567 context.execute_steps("then at least 1 result is returned")
568 bboxes = zip(context.response.property_list('lat'),
569 context.response.property_list('lon'))
571 context.execute_steps("then more than %sresults are returned" % lid)
572 res = context.response.result[int(lid)]
573 bboxes = [ (res['lat'], res['lon']) ]
575 coord = [ float(x) for x in coords.split(',') ]
577 for lat, lon in bboxes:
580 assert lat >= coord[0]
581 assert lat <= coord[1]
582 assert lon >= coord[2]
583 assert lon <= coord[3]
585 @then(u'there are(?P<neg> no)? duplicates')
586 def check_for_duplicates(context, neg):
587 context.execute_steps("then at least 1 result is returned")
592 for res in context.response.result:
593 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
600 assert not has_dupe, "Found duplicate for %s" % (dup, )
602 assert has_dupe, "No duplicates found"