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
16 from nose.tools import * # for assert functions
18 logger = logging.getLogger(__name__)
21 'HTTP_HOST' : 'localhost',
22 'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
23 'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
24 'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
25 'HTTP_CONNECTION' : 'keep-alive',
26 'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
27 'SERVER_SOFTWARE' : 'Nominatim test',
28 'SERVER_NAME' : 'localhost',
29 'SERVER_ADDR' : '127.0.1.1',
31 'REMOTE_ADDR' : '127.0.0.1',
32 'DOCUMENT_ROOT' : '/var/www',
33 'REQUEST_SCHEME' : 'http',
34 'CONTEXT_PREFIX' : '/',
35 'SERVER_ADMIN' : 'webmaster@localhost',
36 'REMOTE_PORT' : '49319',
37 'GATEWAY_INTERFACE' : 'CGI/1.1',
38 'SERVER_PROTOCOL' : 'HTTP/1.1',
39 'REQUEST_METHOD' : 'GET',
40 'REDIRECT_STATUS' : 'CGI'
44 def compare(operator, op1, op2):
45 if operator == 'less than':
47 elif operator == 'more than':
49 elif operator == 'exactly':
51 elif operator == 'at least':
53 elif operator == 'at most':
56 raise Exception("unknown operator '%s'" % operator)
58 class GenericResponse(object):
60 def match_row(self, row):
61 if 'ID' in row.headings:
62 todo = [int(row['ID'])]
64 todo = range(len(self.result))
68 for h in row.headings:
72 assert_equal(res['osm_type'], row[h][0])
73 assert_equal(res['osm_id'], int(row[h][1:]))
75 x, y = row[h].split(' ')
76 assert_almost_equal(float(y), float(res['lat']))
77 assert_almost_equal(float(x), float(res['lon']))
78 elif row[h].startswith("^"):
80 assert_is_not_none(re.fullmatch(row[h], res[h]),
81 "attribute '%s': expected: '%s', got '%s'"
82 % (h, row[h], res[h]))
85 assert_equal(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_equal(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 eq_(0, len(self.result), "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_equals (0, proc.returncode, "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_equals(0, proc.returncode,
341 "%s failed with message: %s" % (
342 os.path.basename(env['SCRIPT_FILENAME']),
345 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
347 if outp.startswith('Status: '):
348 status = int(outp[8:11])
352 content_start = outp.find('\r\n\r\n')
354 return outp[content_start + 4:], status
356 @given(u'the HTTP header')
357 def add_http_header(context):
358 if not hasattr(context, 'http_headers'):
359 context.http_headers = {}
361 for h in context.table.headings:
362 envvar = 'HTTP_' + h.upper().replace('-', '_')
363 context.http_headers[envvar] = context.table[0][h]
366 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
367 def website_search_request(context, fmt, query, addr):
372 params['addressdetails'] = '1'
374 outp, status = send_api_query('search', params, fmt, context)
376 if fmt is None or fmt == 'jsonv2 ':
381 context.response = SearchResponse(outp, outfmt, status)
383 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
384 def website_reverse_request(context, fmt, lat, lon):
391 outp, status = send_api_query('reverse', params, fmt, context)
395 elif fmt == 'jsonv2 ':
400 context.response = ReverseResponse(outp, outfmt, status)
402 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
403 def website_details_request(context, fmt, query):
405 if query[0] in 'NWR':
406 params['osmtype'] = query[0]
407 params['osmid'] = query[1:]
409 params['place_id'] = query
410 outp, status = send_api_query('details', params, fmt, context)
417 context.response = DetailsResponse(outp, outfmt, status)
419 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
420 def website_lookup_request(context, fmt, query):
421 params = { 'osm_ids' : query }
422 outp, status = send_api_query('lookup', params, fmt, context)
426 elif fmt == 'jsonv2 ':
428 elif fmt == 'geojson ':
430 elif fmt == 'geocodejson ':
431 outfmt = 'geocodejson'
435 context.response = SearchResponse(outp, outfmt, status)
437 @when(u'sending (?P<fmt>\S+ )?status query')
438 def website_status_request(context, fmt):
440 outp, status = send_api_query('status', params, fmt, context)
447 context.response = StatusResponse(outp, outfmt, status)
449 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
450 def validate_result_number(context, operator, number):
451 eq_(context.response.errorcode, 200)
452 numres = len(context.response.result)
453 ok_(compare(operator, numres, int(number)),
454 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
456 @then(u'a HTTP (?P<status>\d+) is returned')
457 def check_http_return_status(context, status):
458 eq_(context.response.errorcode, int(status))
460 @then(u'the page contents equals "(?P<text>.+)"')
461 def check_page_content_equals(context, text):
462 eq_(context.response.page, text)
464 @then(u'the result is valid (?P<fmt>\w+)')
465 def step_impl(context, fmt):
466 context.execute_steps("Then a HTTP 200 is returned")
467 eq_(context.response.format, fmt)
469 @then(u'a (?P<fmt>\w+) user error is returned')
470 def check_page_error(context, fmt):
471 context.execute_steps("Then a HTTP 400 is returned")
472 eq_(context.response.format, fmt)
475 assert_is_not_none(re.search(r'<error>.+</error>', context.response.page, re.DOTALL))
477 assert_is_not_none(re.search(r'({"error":)', context.response.page, re.DOTALL))
479 @then(u'result header contains')
480 def check_header_attr(context):
481 for line in context.table:
482 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
483 "attribute '%s': expected: '%s', got '%s'"
484 % (line['attr'], line['value'],
485 context.response.header[line['attr']]))
487 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
488 def check_header_no_attr(context, neg, attrs):
489 for attr in attrs.split(','):
491 assert_not_in(attr, context.response.header)
493 assert_in(attr, context.response.header)
495 @then(u'results contain')
496 def step_impl(context):
497 context.execute_steps("then at least 1 result is returned")
499 for line in context.table:
500 context.response.match_row(line)
502 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
503 def validate_attributes(context, lid, neg, attrs):
505 idx = range(len(context.response.result))
506 context.execute_steps("then at least 1 result is returned")
508 idx = [int(lid.strip())]
509 context.execute_steps("then more than %sresults are returned" % lid)
512 for attr in attrs.split(','):
514 assert_not_in(attr, context.response.result[i])
516 assert_in(attr, context.response.result[i])
518 @then(u'result addresses contain')
519 def step_impl(context):
520 context.execute_steps("then at least 1 result is returned")
522 if 'ID' not in context.table.headings:
523 addr_parts = context.response.property_list('address')
525 for line in context.table:
526 if 'ID' in context.table.headings:
527 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
529 for h in context.table.headings:
533 assert_equal(p[h], line[h], "Bad address value for %s" % h)
535 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
536 def check_address(context, lid, neg, attrs):
537 context.execute_steps("then more than %s results are returned" % lid)
539 addr_parts = context.response.result[int(lid)]['address']
541 for attr in attrs.split(','):
543 assert_not_in(attr, addr_parts)
545 assert_in(attr, addr_parts)
547 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
548 def check_address(context, lid, complete):
549 context.execute_steps("then more than %s results are returned" % lid)
551 addr_parts = dict(context.response.result[int(lid)]['address'])
553 for line in context.table:
554 assert_in(line['type'], addr_parts)
555 assert_equal(addr_parts[line['type']], line['value'],
556 "Bad address value for %s" % line['type'])
557 del addr_parts[line['type']]
560 eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
562 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
563 def step_impl(context, lid, coords):
565 context.execute_steps("then at least 1 result is returned")
566 bboxes = context.response.property_list('boundingbox')
568 context.execute_steps("then more than %sresults are returned" % lid)
569 bboxes = [ context.response.result[int(lid)]['boundingbox']]
571 coord = [ float(x) for x in coords.split(',') ]
574 if isinstance(bbox, str):
575 bbox = bbox.split(',')
576 bbox = [ float(x) for x in bbox ]
578 assert_greater_equal(bbox[0], coord[0])
579 assert_less_equal(bbox[1], coord[1])
580 assert_greater_equal(bbox[2], coord[2])
581 assert_less_equal(bbox[3], coord[3])
583 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
584 def step_impl(context, lid, coords):
586 context.execute_steps("then at least 1 result is returned")
587 bboxes = zip(context.response.property_list('lat'),
588 context.response.property_list('lon'))
590 context.execute_steps("then more than %sresults are returned" % lid)
591 res = context.response.result[int(lid)]
592 bboxes = [ (res['lat'], res['lon']) ]
594 coord = [ float(x) for x in coords.split(',') ]
596 for lat, lon in bboxes:
599 assert_greater_equal(lat, coord[0])
600 assert_less_equal(lat, coord[1])
601 assert_greater_equal(lon, coord[2])
602 assert_less_equal(lon, coord[3])
604 @then(u'there are(?P<neg> no)? duplicates')
605 def check_for_duplicates(context, neg):
606 context.execute_steps("then at least 1 result is returned")
611 for res in context.response.result:
612 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
619 assert not has_dupe, "Found duplicate for %s" % (dup, )
621 assert has_dupe, "No duplicates found"