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', env['SCRIPT_FILENAME']]
286 for k,v in params.items():
287 cmd.append("%s=%s" % (k, v))
289 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
290 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
292 (outp, err) = proc.communicate()
293 outp = outp.decode('utf-8')
295 logger.debug("Result: \n===============================\n"
296 + outp + "\n===============================\n")
298 assert_equals(0, proc.returncode,
299 "query.php failed with message: %s\noutput: %s" % (err, outp))
301 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
303 if outp.startswith('Status: '):
304 status = int(outp[8:11])
308 content_start = outp.find('\r\n\r\n')
310 return outp[content_start + 4:], status
312 @given(u'the HTTP header')
313 def add_http_header(context):
314 if not hasattr(context, 'http_headers'):
315 context.http_headers = {}
317 for h in context.table.headings:
318 envvar = 'HTTP_' + h.upper().replace('-', '_')
319 context.http_headers[envvar] = context.table[0][h]
322 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
323 def website_search_request(context, fmt, query, addr):
328 params['addressdetails'] = '1'
330 outp, status = send_api_query('search', params, fmt, context)
334 elif fmt == 'jsonv2 ':
339 context.response = SearchResponse(outp, outfmt, status)
341 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>[0-9.-]+)?,(?P<lon>[0-9.-]+)?')
342 def website_reverse_request(context, fmt, lat, lon):
349 outp, status = send_api_query('reverse', params, fmt, context)
353 elif fmt == 'jsonv2 ':
358 context.response = ReverseResponse(outp, outfmt, status)
360 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
361 def website_details_request(context, fmt, query):
363 if query[0] in 'NWR':
364 params['osmtype'] = query[0]
365 params['osmid'] = query[1:]
367 params['place_id'] = query
368 outp, status = send_api_query('details', params, fmt, context)
370 context.response = DetailsResponse(outp, 'html', status)
372 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
373 def website_lookup_request(context, fmt, query):
374 params = { 'osm_ids' : query }
375 outp, status = send_api_query('lookup', params, fmt, context)
382 context.response = SearchResponse(outp, outfmt, status)
385 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
386 def validate_result_number(context, operator, number):
387 eq_(context.response.errorcode, 200)
388 numres = len(context.response.result)
389 ok_(compare(operator, numres, int(number)),
390 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
392 @then(u'a HTTP (?P<status>\d+) is returned')
393 def check_http_return_status(context, status):
394 eq_(context.response.errorcode, int(status))
396 @then(u'the result is valid (?P<fmt>\w+)')
397 def step_impl(context, fmt):
398 context.execute_steps("Then a HTTP 200 is returned")
399 eq_(context.response.format, fmt)
401 @then(u'result header contains')
402 def check_header_attr(context):
403 for line in context.table:
404 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
405 "attribute '%s': expected: '%s', got '%s'"
406 % (line['attr'], line['value'],
407 context.response.header[line['attr']]))
409 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
410 def check_header_no_attr(context, neg, attrs):
411 for attr in attrs.split(','):
413 assert_not_in(attr, context.response.header)
415 assert_in(attr, context.response.header)
417 @then(u'results contain')
418 def step_impl(context):
419 context.execute_steps("then at least 1 result is returned")
421 for line in context.table:
422 context.response.match_row(line)
424 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
425 def validate_attributes(context, lid, neg, attrs):
427 idx = range(len(context.response.result))
428 context.execute_steps("then at least 1 result is returned")
430 idx = [int(lid.strip())]
431 context.execute_steps("then more than %sresults are returned" % lid)
434 for attr in attrs.split(','):
436 assert_not_in(attr, context.response.result[i])
438 assert_in(attr, context.response.result[i])
440 @then(u'result addresses contain')
441 def step_impl(context):
442 context.execute_steps("then at least 1 result is returned")
444 if 'ID' not in context.table.headings:
445 addr_parts = context.response.property_list('address')
447 for line in context.table:
448 if 'ID' in context.table.headings:
449 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
451 for h in context.table.headings:
455 assert_equal(p[h], line[h], "Bad address value for %s" % h)
457 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
458 def check_address(context, lid, neg, attrs):
459 context.execute_steps("then more than %s results are returned" % lid)
461 addr_parts = context.response.result[int(lid)]['address']
463 for attr in attrs.split(','):
465 assert_not_in(attr, addr_parts)
467 assert_in(attr, addr_parts)
469 @then(u'address of result (?P<lid>\d+) is')
470 def check_address(context, lid):
471 context.execute_steps("then more than %s results are returned" % lid)
473 addr_parts = dict(context.response.result[int(lid)]['address'])
475 for line in context.table:
476 assert_in(line['type'], addr_parts)
477 assert_equal(addr_parts[line['type']], line['value'],
478 "Bad address value for %s" % line['type'])
479 del addr_parts[line['type']]
481 eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
483 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
484 def step_impl(context, lid, coords):
486 context.execute_steps("then at least 1 result is returned")
487 bboxes = context.response.property_list('boundingbox')
489 context.execute_steps("then more than %sresults are returned" % lid)
490 bboxes = [ context.response.result[int(lid)]['boundingbox']]
492 coord = [ float(x) for x in coords.split(',') ]
495 if isinstance(bbox, str):
496 bbox = bbox.split(',')
497 bbox = [ float(x) for x in bbox ]
499 assert_greater_equal(bbox[0], coord[0])
500 assert_less_equal(bbox[1], coord[1])
501 assert_greater_equal(bbox[2], coord[2])
502 assert_less_equal(bbox[3], coord[3])
504 @then(u'there are(?P<neg> no)? duplicates')
505 def check_for_duplicates(context, neg):
506 context.execute_steps("then at least 1 result is returned")
511 for res in context.response.result:
512 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
519 assert not has_dupe, "Found duplicate for %s" % (dup, )
521 assert has_dupe, "No duplicates found"