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 from tidylib import tidy_document
13 import xml.etree.ElementTree as ET
15 from urllib.parse import urlencode
16 from collections import OrderedDict
17 from nose.tools import * # for assert functions
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_equal(res['osm_type'], row[h][0])
74 assert_equal(res['osm_id'], row[h][1:])
76 x, y = row[h].split(' ')
77 assert_almost_equal(float(y), float(res['lat']))
78 assert_almost_equal(float(x), float(res['lon']))
79 elif row[h].startswith("^"):
81 assert_is_not_none(re.fullmatch(row[h], res[h]),
82 "attribute '%s': expected: '%s', got '%s'"
83 % (h, row[h], res[h]))
86 assert_equal(str(res[h]), str(row[h]))
88 def property_list(self, prop):
89 return [ x[prop] for x in self.result ]
92 class SearchResponse(GenericResponse):
94 def __init__(self, page, fmt='json', errorcode=200):
97 self.errorcode = errorcode
102 getattr(self, 'parse_' + fmt)()
104 def parse_json(self):
105 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
110 self.header['json_func'] = m.group(1)
111 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
113 def parse_geojson(self):
115 self.result = geojson_results_to_json_results(self.result)
117 def parse_html(self):
118 content, errors = tidy_document(self.page,
119 options={'char-encoding' : 'utf8'})
120 #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
122 b = content.find('nominatim_results =')
123 e = content.find('</script>')
124 content = content[b:e]
125 b = content.find('[')
126 e = content.rfind(']')
128 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
131 et = ET.fromstring(self.page)
133 self.header = dict(et.attrib)
136 assert_equal(child.tag, "place")
137 self.result.append(dict(child.attrib))
141 if sub.tag == 'extratags':
142 self.result[-1]['extratags'] = {}
144 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
145 elif sub.tag == 'namedetails':
146 self.result[-1]['namedetails'] = {}
148 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
149 elif sub.tag in ('geokml'):
150 self.result[-1][sub.tag] = True
152 address[sub.tag] = sub.text
155 self.result[-1]['address'] = address
158 class ReverseResponse(GenericResponse):
160 def __init__(self, page, fmt='json', errorcode=200):
163 self.errorcode = errorcode
168 getattr(self, 'parse_' + fmt)()
170 def parse_html(self):
171 content, errors = tidy_document(self.page,
172 options={'char-encoding' : 'utf8'})
173 #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
175 b = content.find('nominatim_results =')
176 e = content.find('</script>')
177 content = content[b:e]
178 b = content.find('[')
179 e = content.rfind(']')
181 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
183 def parse_json(self):
184 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
189 self.header['json_func'] = m.group(1)
190 self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)]
192 def parse_geojson(self):
194 if 'error' in self.result:
196 self.result = geojson_results_to_json_results(self.result[0])
199 et = ET.fromstring(self.page)
201 self.header = dict(et.attrib)
205 if child.tag == 'result':
206 eq_(0, len(self.result), "More than one result in reverse result")
207 self.result.append(dict(child.attrib))
208 elif child.tag == 'addressparts':
211 address[sub.tag] = sub.text
212 self.result[0]['address'] = address
213 elif child.tag == 'extratags':
214 self.result[0]['extratags'] = {}
216 self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
217 elif child.tag == 'namedetails':
218 self.result[0]['namedetails'] = {}
220 self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
221 elif child.tag in ('geokml'):
222 self.result[0][child.tag] = True
224 assert child.tag == 'error', \
225 "Unknown XML tag %s on page: %s" % (child.tag, self.page)
228 class DetailsResponse(GenericResponse):
230 def __init__(self, page, fmt='json', errorcode=200):
233 self.errorcode = errorcode
238 getattr(self, 'parse_' + fmt)()
240 def parse_html(self):
241 content, errors = tidy_document(self.page,
242 options={'char-encoding' : 'utf8'})
245 def parse_json(self):
246 self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
249 class StatusResponse(GenericResponse):
251 def __init__(self, page, fmt='text', errorcode=200):
254 self.errorcode = errorcode
256 if errorcode == 200 and fmt != 'text':
257 getattr(self, 'parse_' + fmt)()
259 def parse_json(self):
260 self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
263 def geojson_result_to_json_result(geojson_result):
264 result = geojson_result['properties']
265 result['geojson'] = geojson_result['geometry']
266 if 'bbox' in geojson_result:
267 # bbox is minlon, minlat, maxlon, maxlat
268 # boundingbox is minlat, maxlat, minlon, maxlon
269 result['boundingbox'] = [
270 geojson_result['bbox'][1],
271 geojson_result['bbox'][3],
272 geojson_result['bbox'][0],
273 geojson_result['bbox'][2]
278 def geojson_results_to_json_results(geojson_results):
279 if 'error' in geojson_results:
281 return list(map(geojson_result_to_json_result, geojson_results['features']))
284 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
285 def query_cmd(context, query, dups):
286 """ Query directly via PHP script.
288 cmd = ['/usr/bin/env', 'php']
289 cmd.append(os.path.join(context.nominatim.build_dir, 'utils', 'query.php'))
290 cmd.extend(['--search', query])
291 # add more parameters in table form
293 for h in context.table.headings:
294 value = context.table[0][h].strip()
296 cmd.extend(('--' + h, value))
299 cmd.extend(('--dedupe', '0'))
301 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
302 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
303 (outp, err) = proc.communicate()
305 assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
307 context.response = SearchResponse(outp.decode('utf-8'), 'json')
309 def send_api_query(endpoint, params, fmt, context):
311 params['format'] = fmt.strip()
313 if context.table.headings[0] == 'param':
314 for line in context.table:
315 params[line['param']] = line['value']
317 for h in context.table.headings:
318 params[h] = context.table[0][h]
320 env = dict(BASE_SERVER_ENV)
321 env['QUERY_STRING'] = urlencode(params)
323 env['SCRIPT_NAME'] = '/%s.php' % endpoint
324 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
325 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
326 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
328 env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
330 logger.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
332 if hasattr(context, 'http_headers'):
333 env.update(context.http_headers)
335 cmd = ['/usr/bin/env', 'php-cgi', '-f']
336 if context.nominatim.code_coverage_path:
337 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
338 env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
339 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
340 env['SCRIPT_FILENAME'] = \
341 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
342 cmd.append(env['SCRIPT_FILENAME'])
343 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
345 cmd.append(env['SCRIPT_FILENAME'])
347 for k,v in params.items():
348 cmd.append("%s=%s" % (k, v))
350 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
351 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
353 (outp, err) = proc.communicate()
354 outp = outp.decode('utf-8')
355 err = err.decode("utf-8")
357 logger.debug("Result: \n===============================\n"
358 + outp + "\n===============================\n")
360 assert_equals(0, proc.returncode,
361 "%s failed with message: %s" % (
362 os.path.basename(env['SCRIPT_FILENAME']),
365 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
367 if outp.startswith('Status: '):
368 status = int(outp[8:11])
372 content_start = outp.find('\r\n\r\n')
374 return outp[content_start + 4:], status
376 @given(u'the HTTP header')
377 def add_http_header(context):
378 if not hasattr(context, 'http_headers'):
379 context.http_headers = {}
381 for h in context.table.headings:
382 envvar = 'HTTP_' + h.upper().replace('-', '_')
383 context.http_headers[envvar] = context.table[0][h]
386 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
387 def website_search_request(context, fmt, query, addr):
392 params['addressdetails'] = '1'
394 outp, status = send_api_query('search', params, fmt, context)
398 elif fmt == 'jsonv2 ':
403 context.response = SearchResponse(outp, outfmt, status)
405 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
406 def website_reverse_request(context, fmt, lat, lon):
413 outp, status = send_api_query('reverse', params, fmt, context)
417 elif fmt == 'jsonv2 ':
422 context.response = ReverseResponse(outp, outfmt, status)
424 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
425 def website_details_request(context, fmt, query):
427 if query[0] in 'NWR':
428 params['osmtype'] = query[0]
429 params['osmid'] = query[1:]
431 params['place_id'] = query
432 outp, status = send_api_query('details', params, fmt, context)
439 context.response = DetailsResponse(outp, outfmt, status)
441 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
442 def website_lookup_request(context, fmt, query):
443 params = { 'osm_ids' : query }
444 outp, status = send_api_query('lookup', params, fmt, context)
448 elif fmt == 'geojson ':
453 context.response = SearchResponse(outp, outfmt, status)
455 @when(u'sending (?P<fmt>\S+ )?status query')
456 def website_status_request(context, fmt):
458 outp, status = send_api_query('status', params, fmt, context)
465 context.response = StatusResponse(outp, outfmt, status)
467 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
468 def validate_result_number(context, operator, number):
469 eq_(context.response.errorcode, 200)
470 numres = len(context.response.result)
471 ok_(compare(operator, numres, int(number)),
472 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
474 @then(u'a HTTP (?P<status>\d+) is returned')
475 def check_http_return_status(context, status):
476 eq_(context.response.errorcode, int(status))
478 @then(u'the page contents equals "(?P<text>.+)"')
479 def check_page_content_equals(context, text):
480 eq_(context.response.page, text)
482 @then(u'the result is valid (?P<fmt>\w+)')
483 def step_impl(context, fmt):
484 context.execute_steps("Then a HTTP 200 is returned")
485 eq_(context.response.format, fmt)
487 @then(u'result header contains')
488 def check_header_attr(context):
489 for line in context.table:
490 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
491 "attribute '%s': expected: '%s', got '%s'"
492 % (line['attr'], line['value'],
493 context.response.header[line['attr']]))
495 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
496 def check_header_no_attr(context, neg, attrs):
497 for attr in attrs.split(','):
499 assert_not_in(attr, context.response.header)
501 assert_in(attr, context.response.header)
503 @then(u'results contain')
504 def step_impl(context):
505 context.execute_steps("then at least 1 result is returned")
507 for line in context.table:
508 context.response.match_row(line)
510 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
511 def validate_attributes(context, lid, neg, attrs):
513 idx = range(len(context.response.result))
514 context.execute_steps("then at least 1 result is returned")
516 idx = [int(lid.strip())]
517 context.execute_steps("then more than %sresults are returned" % lid)
520 for attr in attrs.split(','):
522 assert_not_in(attr, context.response.result[i])
524 assert_in(attr, context.response.result[i])
526 @then(u'result addresses contain')
527 def step_impl(context):
528 context.execute_steps("then at least 1 result is returned")
530 if 'ID' not in context.table.headings:
531 addr_parts = context.response.property_list('address')
533 for line in context.table:
534 if 'ID' in context.table.headings:
535 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
537 for h in context.table.headings:
541 assert_equal(p[h], line[h], "Bad address value for %s" % h)
543 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
544 def check_address(context, lid, neg, attrs):
545 context.execute_steps("then more than %s results are returned" % lid)
547 addr_parts = context.response.result[int(lid)]['address']
549 for attr in attrs.split(','):
551 assert_not_in(attr, addr_parts)
553 assert_in(attr, addr_parts)
555 @then(u'address of result (?P<lid>\d+) is')
556 def check_address(context, lid):
557 context.execute_steps("then more than %s results are returned" % lid)
559 addr_parts = dict(context.response.result[int(lid)]['address'])
561 for line in context.table:
562 assert_in(line['type'], addr_parts)
563 assert_equal(addr_parts[line['type']], line['value'],
564 "Bad address value for %s" % line['type'])
565 del addr_parts[line['type']]
567 eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
569 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
570 def step_impl(context, lid, coords):
572 context.execute_steps("then at least 1 result is returned")
573 bboxes = context.response.property_list('boundingbox')
575 context.execute_steps("then more than %sresults are returned" % lid)
576 bboxes = [ context.response.result[int(lid)]['boundingbox']]
578 coord = [ float(x) for x in coords.split(',') ]
581 if isinstance(bbox, str):
582 bbox = bbox.split(',')
583 bbox = [ float(x) for x in bbox ]
585 assert_greater_equal(bbox[0], coord[0])
586 assert_less_equal(bbox[1], coord[1])
587 assert_greater_equal(bbox[2], coord[2])
588 assert_less_equal(bbox[3], coord[3])
590 @then(u'there are(?P<neg> no)? duplicates')
591 def check_for_duplicates(context, neg):
592 context.execute_steps("then at least 1 result is returned")
597 for res in context.response.result:
598 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
605 assert not has_dupe, "Found duplicate for %s" % (dup, )
607 assert has_dupe, "No duplicates found"