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 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
236 def query_cmd(context, query, dups):
237 """ Query directly via PHP script.
239 cmd = [os.path.join(context.nominatim.build_dir, 'utils', 'query.php'),
241 # add more parameters in table form
243 for h in context.table.headings:
244 value = context.table[0][h].strip()
246 cmd.extend(('--' + h, value))
249 cmd.extend(('--dedupe', '0'))
251 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
252 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
253 (outp, err) = proc.communicate()
255 assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
257 context.response = SearchResponse(outp.decode('utf-8'), 'json')
259 def send_api_query(endpoint, params, fmt, context):
261 params['format'] = fmt.strip()
263 if context.table.headings[0] == 'param':
264 for line in context.table:
265 params[line['param']] = line['value']
267 for h in context.table.headings:
268 params[h] = context.table[0][h]
270 env = dict(BASE_SERVER_ENV)
271 env['QUERY_STRING'] = urlencode(params)
273 env['SCRIPT_NAME'] = '/%s.php' % endpoint
274 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
275 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
276 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
278 env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
280 logger.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
282 if hasattr(context, 'http_headers'):
283 env.update(context.http_headers)
285 cmd = ['/usr/bin/php-cgi', '-f']
286 if context.nominatim.code_coverage_path:
287 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
288 env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
289 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
290 env['SCRIPT_FILENAME'] = \
291 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
292 cmd.append(env['SCRIPT_FILENAME'])
293 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
295 cmd.append(env['SCRIPT_FILENAME'])
297 for k,v in params.items():
298 cmd.append("%s=%s" % (k, v))
300 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
301 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
303 (outp, err) = proc.communicate()
304 outp = outp.decode('utf-8')
306 logger.debug("Result: \n===============================\n"
307 + outp + "\n===============================\n")
309 assert_equals(0, proc.returncode,
310 "query.php failed with message: %s\noutput: %s" % (err, outp))
312 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
314 if outp.startswith('Status: '):
315 status = int(outp[8:11])
319 content_start = outp.find('\r\n\r\n')
321 return outp[content_start + 4:], status
323 @given(u'the HTTP header')
324 def add_http_header(context):
325 if not hasattr(context, 'http_headers'):
326 context.http_headers = {}
328 for h in context.table.headings:
329 envvar = 'HTTP_' + h.upper().replace('-', '_')
330 context.http_headers[envvar] = context.table[0][h]
333 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
334 def website_search_request(context, fmt, query, addr):
339 params['addressdetails'] = '1'
341 outp, status = send_api_query('search', params, fmt, context)
345 elif fmt == 'jsonv2 ':
350 context.response = SearchResponse(outp, outfmt, status)
352 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
353 def website_reverse_request(context, fmt, lat, lon):
360 outp, status = send_api_query('reverse', params, fmt, context)
364 elif fmt == 'jsonv2 ':
369 context.response = ReverseResponse(outp, outfmt, status)
371 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
372 def website_details_request(context, fmt, query):
374 if query[0] in 'NWR':
375 params['osmtype'] = query[0]
376 params['osmid'] = query[1:]
378 params['place_id'] = query
379 outp, status = send_api_query('details', params, fmt, context)
381 context.response = DetailsResponse(outp, 'html', status)
383 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
384 def website_lookup_request(context, fmt, query):
385 params = { 'osm_ids' : query }
386 outp, status = send_api_query('lookup', params, fmt, context)
393 context.response = SearchResponse(outp, outfmt, status)
396 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
397 def validate_result_number(context, operator, number):
398 eq_(context.response.errorcode, 200)
399 numres = len(context.response.result)
400 ok_(compare(operator, numres, int(number)),
401 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
403 @then(u'a HTTP (?P<status>\d+) is returned')
404 def check_http_return_status(context, status):
405 eq_(context.response.errorcode, int(status))
407 @then(u'the result is valid (?P<fmt>\w+)')
408 def step_impl(context, fmt):
409 context.execute_steps("Then a HTTP 200 is returned")
410 eq_(context.response.format, fmt)
412 @then(u'result header contains')
413 def check_header_attr(context):
414 for line in context.table:
415 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
416 "attribute '%s': expected: '%s', got '%s'"
417 % (line['attr'], line['value'],
418 context.response.header[line['attr']]))
420 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
421 def check_header_no_attr(context, neg, attrs):
422 for attr in attrs.split(','):
424 assert_not_in(attr, context.response.header)
426 assert_in(attr, context.response.header)
428 @then(u'results contain')
429 def step_impl(context):
430 context.execute_steps("then at least 1 result is returned")
432 for line in context.table:
433 context.response.match_row(line)
435 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
436 def validate_attributes(context, lid, neg, attrs):
438 idx = range(len(context.response.result))
439 context.execute_steps("then at least 1 result is returned")
441 idx = [int(lid.strip())]
442 context.execute_steps("then more than %sresults are returned" % lid)
445 for attr in attrs.split(','):
447 assert_not_in(attr, context.response.result[i])
449 assert_in(attr, context.response.result[i])
451 @then(u'result addresses contain')
452 def step_impl(context):
453 context.execute_steps("then at least 1 result is returned")
455 if 'ID' not in context.table.headings:
456 addr_parts = context.response.property_list('address')
458 for line in context.table:
459 if 'ID' in context.table.headings:
460 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
462 for h in context.table.headings:
466 assert_equal(p[h], line[h], "Bad address value for %s" % h)
468 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
469 def check_address(context, lid, neg, attrs):
470 context.execute_steps("then more than %s results are returned" % lid)
472 addr_parts = context.response.result[int(lid)]['address']
474 for attr in attrs.split(','):
476 assert_not_in(attr, addr_parts)
478 assert_in(attr, addr_parts)
480 @then(u'address of result (?P<lid>\d+) is')
481 def check_address(context, lid):
482 context.execute_steps("then more than %s results are returned" % lid)
484 addr_parts = dict(context.response.result[int(lid)]['address'])
486 for line in context.table:
487 assert_in(line['type'], addr_parts)
488 assert_equal(addr_parts[line['type']], line['value'],
489 "Bad address value for %s" % line['type'])
490 del addr_parts[line['type']]
492 eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
494 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
495 def step_impl(context, lid, coords):
497 context.execute_steps("then at least 1 result is returned")
498 bboxes = context.response.property_list('boundingbox')
500 context.execute_steps("then more than %sresults are returned" % lid)
501 bboxes = [ context.response.result[int(lid)]['boundingbox']]
503 coord = [ float(x) for x in coords.split(',') ]
506 if isinstance(bbox, str):
507 bbox = bbox.split(',')
508 bbox = [ float(x) for x in bbox ]
510 assert_greater_equal(bbox[0], coord[0])
511 assert_less_equal(bbox[1], coord[1])
512 assert_greater_equal(bbox[2], coord[2])
513 assert_less_equal(bbox[3], coord[3])
515 @then(u'there are(?P<neg> no)? duplicates')
516 def check_for_duplicates(context, neg):
517 context.execute_steps("then at least 1 result is returned")
522 for res in context.response.result:
523 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
530 assert not has_dupe, "Found duplicate for %s" % (dup, )
532 assert has_dupe, "No duplicates found"