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 class StatusResponse(GenericResponse):
241 def __init__(self, page, fmt='text', errorcode=200):
244 self.errorcode = errorcode
246 if errorcode == 200 and fmt != 'text':
247 getattr(self, 'parse_' + fmt)()
249 def parse_json(self):
250 self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
253 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
254 def query_cmd(context, query, dups):
255 """ Query directly via PHP script.
257 cmd = ['/usr/bin/env', 'php']
258 cmd.append(os.path.join(context.nominatim.build_dir, 'utils', 'query.php'))
259 cmd.extend(['--search', query])
260 # add more parameters in table form
262 for h in context.table.headings:
263 value = context.table[0][h].strip()
265 cmd.extend(('--' + h, value))
268 cmd.extend(('--dedupe', '0'))
270 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
271 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
272 (outp, err) = proc.communicate()
274 assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
276 context.response = SearchResponse(outp.decode('utf-8'), 'json')
278 def send_api_query(endpoint, params, fmt, context):
280 params['format'] = fmt.strip()
282 if context.table.headings[0] == 'param':
283 for line in context.table:
284 params[line['param']] = line['value']
286 for h in context.table.headings:
287 params[h] = context.table[0][h]
289 env = dict(BASE_SERVER_ENV)
290 env['QUERY_STRING'] = urlencode(params)
292 env['SCRIPT_NAME'] = '/%s.php' % endpoint
293 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
294 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
295 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
297 env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
299 logger.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
301 if hasattr(context, 'http_headers'):
302 env.update(context.http_headers)
304 cmd = ['/usr/bin/env', 'php-cgi', '-f']
305 if context.nominatim.code_coverage_path:
306 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
307 env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
308 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
309 env['SCRIPT_FILENAME'] = \
310 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
311 cmd.append(env['SCRIPT_FILENAME'])
312 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
314 cmd.append(env['SCRIPT_FILENAME'])
316 for k,v in params.items():
317 cmd.append("%s=%s" % (k, v))
319 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
320 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
322 (outp, err) = proc.communicate()
323 outp = outp.decode('utf-8')
324 err = err.decode("utf-8")
326 logger.debug("Result: \n===============================\n"
327 + outp + "\n===============================\n")
329 assert_equals(0, proc.returncode,
330 "%s failed with message: %s" % (
331 os.path.basename(env['SCRIPT_FILENAME']),
334 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
336 if outp.startswith('Status: '):
337 status = int(outp[8:11])
341 content_start = outp.find('\r\n\r\n')
343 return outp[content_start + 4:], status
345 @given(u'the HTTP header')
346 def add_http_header(context):
347 if not hasattr(context, 'http_headers'):
348 context.http_headers = {}
350 for h in context.table.headings:
351 envvar = 'HTTP_' + h.upper().replace('-', '_')
352 context.http_headers[envvar] = context.table[0][h]
355 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
356 def website_search_request(context, fmt, query, addr):
361 params['addressdetails'] = '1'
363 outp, status = send_api_query('search', params, fmt, context)
367 elif fmt == 'jsonv2 ':
372 context.response = SearchResponse(outp, outfmt, status)
374 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
375 def website_reverse_request(context, fmt, lat, lon):
382 outp, status = send_api_query('reverse', params, fmt, context)
386 elif fmt == 'jsonv2 ':
391 context.response = ReverseResponse(outp, outfmt, status)
393 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
394 def website_details_request(context, fmt, query):
396 if query[0] in 'NWR':
397 params['osmtype'] = query[0]
398 params['osmid'] = query[1:]
400 params['place_id'] = query
401 outp, status = send_api_query('details', params, fmt, context)
408 context.response = DetailsResponse(outp, outfmt, status)
410 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
411 def website_lookup_request(context, fmt, query):
412 params = { 'osm_ids' : query }
413 outp, status = send_api_query('lookup', params, fmt, context)
420 context.response = SearchResponse(outp, outfmt, status)
422 @when(u'sending (?P<fmt>\S+ )?status query')
423 def website_status_request(context, fmt):
425 outp, status = send_api_query('status', params, fmt, context)
432 context.response = StatusResponse(outp, outfmt, status)
434 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
435 def validate_result_number(context, operator, number):
436 eq_(context.response.errorcode, 200)
437 numres = len(context.response.result)
438 ok_(compare(operator, numres, int(number)),
439 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
441 @then(u'a HTTP (?P<status>\d+) is returned')
442 def check_http_return_status(context, status):
443 eq_(context.response.errorcode, int(status))
445 @then(u'the page contents equals "(?P<text>.+)"')
446 def check_page_content_equals(context, text):
447 eq_(context.response.page, text)
449 @then(u'the result is valid (?P<fmt>\w+)')
450 def step_impl(context, fmt):
451 context.execute_steps("Then a HTTP 200 is returned")
452 eq_(context.response.format, fmt)
454 @then(u'result header contains')
455 def check_header_attr(context):
456 for line in context.table:
457 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
458 "attribute '%s': expected: '%s', got '%s'"
459 % (line['attr'], line['value'],
460 context.response.header[line['attr']]))
462 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
463 def check_header_no_attr(context, neg, attrs):
464 for attr in attrs.split(','):
466 assert_not_in(attr, context.response.header)
468 assert_in(attr, context.response.header)
470 @then(u'results contain')
471 def step_impl(context):
472 context.execute_steps("then at least 1 result is returned")
474 for line in context.table:
475 context.response.match_row(line)
477 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
478 def validate_attributes(context, lid, neg, attrs):
480 idx = range(len(context.response.result))
481 context.execute_steps("then at least 1 result is returned")
483 idx = [int(lid.strip())]
484 context.execute_steps("then more than %sresults are returned" % lid)
487 for attr in attrs.split(','):
489 assert_not_in(attr, context.response.result[i])
491 assert_in(attr, context.response.result[i])
493 @then(u'result addresses contain')
494 def step_impl(context):
495 context.execute_steps("then at least 1 result is returned")
497 if 'ID' not in context.table.headings:
498 addr_parts = context.response.property_list('address')
500 for line in context.table:
501 if 'ID' in context.table.headings:
502 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
504 for h in context.table.headings:
508 assert_equal(p[h], line[h], "Bad address value for %s" % h)
510 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
511 def check_address(context, lid, neg, attrs):
512 context.execute_steps("then more than %s results are returned" % lid)
514 addr_parts = context.response.result[int(lid)]['address']
516 for attr in attrs.split(','):
518 assert_not_in(attr, addr_parts)
520 assert_in(attr, addr_parts)
522 @then(u'address of result (?P<lid>\d+) is')
523 def check_address(context, lid):
524 context.execute_steps("then more than %s results are returned" % lid)
526 addr_parts = dict(context.response.result[int(lid)]['address'])
528 for line in context.table:
529 assert_in(line['type'], addr_parts)
530 assert_equal(addr_parts[line['type']], line['value'],
531 "Bad address value for %s" % line['type'])
532 del addr_parts[line['type']]
534 eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
536 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
537 def step_impl(context, lid, coords):
539 context.execute_steps("then at least 1 result is returned")
540 bboxes = context.response.property_list('boundingbox')
542 context.execute_steps("then more than %sresults are returned" % lid)
543 bboxes = [ context.response.result[int(lid)]['boundingbox']]
545 coord = [ float(x) for x in coords.split(',') ]
548 if isinstance(bbox, str):
549 bbox = bbox.split(',')
550 bbox = [ float(x) for x in bbox ]
552 assert_greater_equal(bbox[0], coord[0])
553 assert_less_equal(bbox[1], coord[1])
554 assert_greater_equal(bbox[2], coord[2])
555 assert_less_equal(bbox[3], coord[3])
557 @then(u'there are(?P<neg> no)? duplicates')
558 def check_for_duplicates(context, neg):
559 context.execute_steps("then at least 1 result is returned")
564 for res in context.response.result:
565 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
572 assert not has_dupe, "Found duplicate for %s" % (dup, )
574 assert has_dupe, "No duplicates found"