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_html(self):
114 content, errors = tidy_document(self.page,
115 options={'char-encoding' : 'utf8'})
116 #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
118 b = content.find('nominatim_results =')
119 e = content.find('</script>')
120 content = content[b:e]
121 b = content.find('[')
122 e = content.rfind(']')
124 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
127 et = ET.fromstring(self.page)
129 self.header = dict(et.attrib)
132 assert_equal(child.tag, "place")
133 self.result.append(dict(child.attrib))
137 if sub.tag == 'extratags':
138 self.result[-1]['extratags'] = {}
140 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
141 elif sub.tag == 'namedetails':
142 self.result[-1]['namedetails'] = {}
144 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
145 elif sub.tag in ('geokml'):
146 self.result[-1][sub.tag] = True
148 address[sub.tag] = sub.text
151 self.result[-1]['address'] = address
154 class ReverseResponse(GenericResponse):
156 def __init__(self, page, fmt='json', errorcode=200):
159 self.errorcode = errorcode
164 getattr(self, 'parse_' + fmt)()
166 def parse_html(self):
167 content, errors = tidy_document(self.page,
168 options={'char-encoding' : 'utf8'})
169 #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
171 b = content.find('nominatim_results =')
172 e = content.find('</script>')
173 content = content[b:e]
174 b = content.find('[')
175 e = content.rfind(']')
177 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
179 def parse_json(self):
180 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
185 self.header['json_func'] = m.group(1)
186 self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)]
189 et = ET.fromstring(self.page)
191 self.header = dict(et.attrib)
195 if child.tag == 'result':
196 eq_(0, len(self.result), "More than one result in reverse result")
197 self.result.append(dict(child.attrib))
198 elif child.tag == 'addressparts':
201 address[sub.tag] = sub.text
202 self.result[0]['address'] = address
203 elif child.tag == 'extratags':
204 self.result[0]['extratags'] = {}
206 self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
207 elif child.tag == 'namedetails':
208 self.result[0]['namedetails'] = {}
210 self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
211 elif child.tag in ('geokml'):
212 self.result[0][child.tag] = True
214 assert child.tag == 'error', \
215 "Unknown XML tag %s on page: %s" % (child.tag, self.page)
218 class DetailsResponse(GenericResponse):
220 def __init__(self, page, fmt='json', errorcode=200):
223 self.errorcode = errorcode
228 getattr(self, 'parse_' + fmt)()
230 def parse_html(self):
231 content, errors = tidy_document(self.page,
232 options={'char-encoding' : 'utf8'})
235 def parse_json(self):
236 self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
239 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
240 def query_cmd(context, query, dups):
241 """ Query directly via PHP script.
243 cmd = ['/usr/bin/env', 'php']
244 cmd.append(os.path.join(context.nominatim.build_dir, 'utils', 'query.php'))
245 cmd.extend(['--search', query])
246 # add more parameters in table form
248 for h in context.table.headings:
249 value = context.table[0][h].strip()
251 cmd.extend(('--' + h, value))
254 cmd.extend(('--dedupe', '0'))
256 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
257 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
258 (outp, err) = proc.communicate()
260 assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
262 context.response = SearchResponse(outp.decode('utf-8'), 'json')
264 def send_api_query(endpoint, params, fmt, context):
266 params['format'] = fmt.strip()
268 if context.table.headings[0] == 'param':
269 for line in context.table:
270 params[line['param']] = line['value']
272 for h in context.table.headings:
273 params[h] = context.table[0][h]
275 env = dict(BASE_SERVER_ENV)
276 env['QUERY_STRING'] = urlencode(params)
278 env['SCRIPT_NAME'] = '/%s.php' % endpoint
279 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
280 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
281 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
283 env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
285 logger.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
287 if hasattr(context, 'http_headers'):
288 env.update(context.http_headers)
290 cmd = ['/usr/bin/env', 'php-cgi', '-f']
291 if context.nominatim.code_coverage_path:
292 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
293 env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
294 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
295 env['SCRIPT_FILENAME'] = \
296 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
297 cmd.append(env['SCRIPT_FILENAME'])
298 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
300 cmd.append(env['SCRIPT_FILENAME'])
302 for k,v in params.items():
303 cmd.append("%s=%s" % (k, v))
305 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
306 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
308 (outp, err) = proc.communicate()
309 outp = outp.decode('utf-8')
311 logger.debug("Result: \n===============================\n"
312 + outp + "\n===============================\n")
314 assert_equals(0, proc.returncode,
315 "%s failed with message: %s\noutput: %s" % (env['SCRIPT_FILENAME'], err, outp))
317 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
319 if outp.startswith('Status: '):
320 status = int(outp[8:11])
324 content_start = outp.find('\r\n\r\n')
326 return outp[content_start + 4:], status
328 @given(u'the HTTP header')
329 def add_http_header(context):
330 if not hasattr(context, 'http_headers'):
331 context.http_headers = {}
333 for h in context.table.headings:
334 envvar = 'HTTP_' + h.upper().replace('-', '_')
335 context.http_headers[envvar] = context.table[0][h]
338 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
339 def website_search_request(context, fmt, query, addr):
344 params['addressdetails'] = '1'
346 outp, status = send_api_query('search', params, fmt, context)
350 elif fmt == 'jsonv2 ':
355 context.response = SearchResponse(outp, outfmt, status)
357 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
358 def website_reverse_request(context, fmt, lat, lon):
365 outp, status = send_api_query('reverse', params, fmt, context)
369 elif fmt == 'jsonv2 ':
374 context.response = ReverseResponse(outp, outfmt, status)
376 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
377 def website_details_request(context, fmt, query):
379 if query[0] in 'NWR':
380 params['osmtype'] = query[0]
381 params['osmid'] = query[1:]
383 params['place_id'] = query
384 outp, status = send_api_query('details', params, fmt, context)
391 context.response = DetailsResponse(outp, outfmt, status)
393 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
394 def website_lookup_request(context, fmt, query):
395 params = { 'osm_ids' : query }
396 outp, status = send_api_query('lookup', params, fmt, context)
403 context.response = SearchResponse(outp, outfmt, status)
405 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
406 def validate_result_number(context, operator, number):
407 eq_(context.response.errorcode, 200)
408 numres = len(context.response.result)
409 ok_(compare(operator, numres, int(number)),
410 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
412 @then(u'a HTTP (?P<status>\d+) is returned')
413 def check_http_return_status(context, status):
414 eq_(context.response.errorcode, int(status))
416 @then(u'the result is valid (?P<fmt>\w+)')
417 def step_impl(context, fmt):
418 context.execute_steps("Then a HTTP 200 is returned")
419 eq_(context.response.format, fmt)
421 @then(u'result header contains')
422 def check_header_attr(context):
423 for line in context.table:
424 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
425 "attribute '%s': expected: '%s', got '%s'"
426 % (line['attr'], line['value'],
427 context.response.header[line['attr']]))
429 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
430 def check_header_no_attr(context, neg, attrs):
431 for attr in attrs.split(','):
433 assert_not_in(attr, context.response.header)
435 assert_in(attr, context.response.header)
437 @then(u'results contain')
438 def step_impl(context):
439 context.execute_steps("then at least 1 result is returned")
441 for line in context.table:
442 context.response.match_row(line)
444 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
445 def validate_attributes(context, lid, neg, attrs):
447 idx = range(len(context.response.result))
448 context.execute_steps("then at least 1 result is returned")
450 idx = [int(lid.strip())]
451 context.execute_steps("then more than %sresults are returned" % lid)
454 for attr in attrs.split(','):
456 assert_not_in(attr, context.response.result[i])
458 assert_in(attr, context.response.result[i])
460 @then(u'result addresses contain')
461 def step_impl(context):
462 context.execute_steps("then at least 1 result is returned")
464 if 'ID' not in context.table.headings:
465 addr_parts = context.response.property_list('address')
467 for line in context.table:
468 if 'ID' in context.table.headings:
469 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
471 for h in context.table.headings:
475 assert_equal(p[h], line[h], "Bad address value for %s" % h)
477 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
478 def check_address(context, lid, neg, attrs):
479 context.execute_steps("then more than %s results are returned" % lid)
481 addr_parts = context.response.result[int(lid)]['address']
483 for attr in attrs.split(','):
485 assert_not_in(attr, addr_parts)
487 assert_in(attr, addr_parts)
489 @then(u'address of result (?P<lid>\d+) is')
490 def check_address(context, lid):
491 context.execute_steps("then more than %s results are returned" % lid)
493 addr_parts = dict(context.response.result[int(lid)]['address'])
495 for line in context.table:
496 assert_in(line['type'], addr_parts)
497 assert_equal(addr_parts[line['type']], line['value'],
498 "Bad address value for %s" % line['type'])
499 del addr_parts[line['type']]
501 eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
503 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
504 def step_impl(context, lid, coords):
506 context.execute_steps("then at least 1 result is returned")
507 bboxes = context.response.property_list('boundingbox')
509 context.execute_steps("then more than %sresults are returned" % lid)
510 bboxes = [ context.response.result[int(lid)]['boundingbox']]
512 coord = [ float(x) for x in coords.split(',') ]
515 if isinstance(bbox, str):
516 bbox = bbox.split(',')
517 bbox = [ float(x) for x in bbox ]
519 assert_greater_equal(bbox[0], coord[0])
520 assert_less_equal(bbox[1], coord[1])
521 assert_greater_equal(bbox[2], coord[2])
522 assert_less_equal(bbox[3], coord[3])
524 @then(u'there are(?P<neg> no)? duplicates')
525 def check_for_duplicates(context, neg):
526 context.execute_steps("then at least 1 result is returned")
531 for res in context.response.result:
532 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
539 assert not has_dupe, "Found duplicate for %s" % (dup, )
541 assert has_dupe, "No duplicates found"