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.
11 from tidylib import tidy_document
12 import xml.etree.ElementTree as ET
14 from urllib.parse import urlencode
15 from collections import OrderedDict
16 from nose.tools import * # for assert functions
19 'HTTP_HOST' : 'localhost',
20 'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
21 'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
22 'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
23 'HTTP_CONNECTION' : 'keep-alive',
24 'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
25 'SERVER_SOFTWARE' : 'Nominatim test',
26 'SERVER_NAME' : 'localhost',
27 'SERVER_ADDR' : '127.0.1.1',
29 'REMOTE_ADDR' : '127.0.0.1',
30 'DOCUMENT_ROOT' : '/var/www',
31 'REQUEST_SCHEME' : 'http',
32 'CONTEXT_PREFIX' : '/',
33 'SERVER_ADMIN' : 'webmaster@localhost',
34 'REMOTE_PORT' : '49319',
35 'GATEWAY_INTERFACE' : 'CGI/1.1',
36 'SERVER_PROTOCOL' : 'HTTP/1.1',
37 'REQUEST_METHOD' : 'GET',
38 'REDIRECT_STATUS' : 'CGI'
42 def compare(operator, op1, op2):
43 if operator == 'less than':
45 elif operator == 'more than':
47 elif operator == 'exactly':
49 elif operator == 'at least':
51 elif operator == 'at most':
54 raise Exception("unknown operator '%s'" % operator)
56 class GenericResponse(object):
58 def match_row(self, row):
59 if 'ID' in row.headings:
60 todo = [int(row['ID'])]
62 todo = range(len(self.result))
66 for h in row.headings:
70 assert_equal(res['osm_type'], row[h][0])
71 assert_equal(res['osm_id'], row[h][1:])
73 x, y = row[h].split(' ')
74 assert_almost_equal(float(y), float(res['lat']))
75 assert_almost_equal(float(x), float(res['lon']))
76 elif row[h].startswith("^"):
78 assert_is_not_none(re.fullmatch(row[h], res[h]),
79 "attribute '%s': expected: '%s', got '%s'"
80 % (h, row[h], res[h]))
83 assert_equal(str(res[h]), str(row[h]))
85 def property_list(self, prop):
86 return [ x[prop] for x in self.result ]
89 class SearchResponse(GenericResponse):
91 def __init__(self, page, fmt='json', errorcode=200):
94 self.errorcode = errorcode
99 getattr(self, 'parse_' + fmt)()
101 def parse_json(self):
102 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
107 self.header['json_func'] = m.group(1)
108 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
110 def parse_html(self):
111 content, errors = tidy_document(self.page,
112 options={'char-encoding' : 'utf8'})
113 #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
115 b = content.find('nominatim_results =')
116 e = content.find('</script>')
117 content = content[b:e]
118 b = content.find('[')
119 e = content.rfind(']')
121 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
124 et = ET.fromstring(self.page)
126 self.header = dict(et.attrib)
129 assert_equal(child.tag, "place")
130 self.result.append(dict(child.attrib))
134 if sub.tag == 'extratags':
135 self.result[-1]['extratags'] = {}
137 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
138 elif sub.tag == 'namedetails':
139 self.result[-1]['namedetails'] = {}
141 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
142 elif sub.tag in ('geokml'):
143 self.result[-1][sub.tag] = True
145 address[sub.tag] = sub.text
148 self.result[-1]['address'] = address
151 class ReverseResponse(GenericResponse):
153 def __init__(self, page, fmt='json', errorcode=200):
156 self.errorcode = errorcode
161 getattr(self, 'parse_' + fmt)()
163 def parse_html(self):
164 content, errors = tidy_document(self.page,
165 options={'char-encoding' : 'utf8'})
166 #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
168 b = content.find('nominatim_results =')
169 e = content.find('</script>')
170 content = content[b:e]
171 b = content.find('[')
172 e = content.rfind(']')
174 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
176 def parse_json(self):
177 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
182 self.header['json_func'] = m.group(1)
183 self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)]
186 et = ET.fromstring(self.page)
188 self.header = dict(et.attrib)
192 if child.tag == 'result':
193 eq_(0, len(self.result), "More than one result in reverse result")
194 self.result.append(dict(child.attrib))
195 elif child.tag == 'addressparts':
198 address[sub.tag] = sub.text
199 self.result[0]['address'] = address
200 elif child.tag == 'extratags':
201 self.result[0]['extratags'] = {}
203 self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
204 elif child.tag == 'namedetails':
205 self.result[0]['namedetails'] = {}
207 self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
208 elif child.tag in ('geokml'):
209 self.result[0][child.tag] = True
211 assert child.tag == 'error', \
212 "Unknown XML tag %s on page: %s" % (child.tag, self.page)
215 class DetailsResponse(GenericResponse):
217 def __init__(self, page, fmt='json', errorcode=200):
220 self.errorcode = errorcode
225 getattr(self, 'parse_' + fmt)()
227 def parse_html(self):
228 content, errors = tidy_document(self.page,
229 options={'char-encoding' : 'utf8'})
232 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
233 def query_cmd(context, query, dups):
234 """ Query directly via PHP script.
236 cmd = [os.path.join(context.nominatim.build_dir, 'utils', 'query.php'),
238 # add more parameters in table form
240 for h in context.table.headings:
241 value = context.table[0][h].strip()
243 cmd.extend(('--' + h, value))
246 cmd.extend(('--dedupe', '0'))
248 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
249 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
250 (outp, err) = proc.communicate()
252 assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
254 context.response = SearchResponse(outp.decode('utf-8'), 'json')
256 def send_api_query(endpoint, params, fmt, context):
258 params['format'] = fmt.strip()
260 if context.table.headings[0] == 'param':
261 for line in context.table:
262 params[line['param']] = line['value']
264 for h in context.table.headings:
265 params[h] = context.table[0][h]
267 env = dict(BASE_SERVER_ENV)
268 env['QUERY_STRING'] = urlencode(params)
270 env['SCRIPT_NAME'] = '/%s.php' % endpoint
271 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
272 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
273 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
275 env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
277 if hasattr(context, 'http_headers'):
278 env.update(context.http_headers)
280 cmd = ['/usr/bin/php-cgi', env['SCRIPT_FILENAME']]
281 for k,v in params.items():
282 cmd.append("%s=%s" % (k, v))
284 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
285 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
287 (outp, err) = proc.communicate()
289 assert_equals(0, proc.returncode,
290 "query.php failed with message: %s\noutput: %s" % (err, outp))
292 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
294 outp = outp.decode('utf-8')
296 if outp.startswith('Status: '):
297 status = int(outp[8:11])
301 content_start = outp.find('\r\n\r\n')
303 return outp[content_start + 4:], status
305 @given(u'the HTTP header')
306 def add_http_header(context):
307 if not hasattr(context, 'http_headers'):
308 context.http_headers = {}
310 for h in context.table.headings:
311 envvar = 'HTTP_' + h.upper().replace('-', '_')
312 context.http_headers[envvar] = context.table[0][h]
315 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
316 def website_search_request(context, fmt, query, addr):
321 params['addressdetails'] = '1'
323 outp, status = send_api_query('search', params, fmt, context)
327 elif fmt == 'jsonv2 ':
332 context.response = SearchResponse(outp, outfmt, status)
334 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>[0-9.-]+)?,(?P<lon>[0-9.-]+)?')
335 def website_reverse_request(context, fmt, lat, lon):
342 outp, status = send_api_query('reverse', params, fmt, context)
346 elif fmt == 'jsonv2 ':
351 context.response = ReverseResponse(outp, outfmt, status)
353 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
354 def website_details_request(context, fmt, query):
356 if query[0] in 'NWR':
357 params['osmtype'] = query[0]
358 params['osmid'] = query[1:]
360 params['place_id'] = query
361 outp, status = send_api_query('details', params, fmt, context)
363 context.response = DetailsResponse(outp, 'html', status)
365 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
366 def website_lookup_request(context, fmt, query):
367 params = { 'osm_ids' : query }
368 outp, status = send_api_query('lookup', params, fmt, context)
375 context.response = SearchResponse(outp, outfmt, status)
378 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
379 def validate_result_number(context, operator, number):
380 eq_(context.response.errorcode, 200)
381 numres = len(context.response.result)
382 ok_(compare(operator, numres, int(number)),
383 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
385 @then(u'a HTTP (?P<status>\d+) is returned')
386 def check_http_return_status(context, status):
387 eq_(context.response.errorcode, int(status))
389 @then(u'the result is valid (?P<fmt>\w+)')
390 def step_impl(context, fmt):
391 context.execute_steps("Then a HTTP 200 is returned")
392 eq_(context.response.format, fmt)
394 @then(u'result header contains')
395 def check_header_attr(context):
396 for line in context.table:
397 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
398 "attribute '%s': expected: '%s', got '%s'"
399 % (line['attr'], line['value'],
400 context.response.header[line['attr']]))
402 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
403 def check_header_no_attr(context, neg, attrs):
404 for attr in attrs.split(','):
406 assert_not_in(attr, context.response.header)
408 assert_in(attr, context.response.header)
410 @then(u'results contain')
411 def step_impl(context):
412 context.execute_steps("then at least 1 result is returned")
414 for line in context.table:
415 context.response.match_row(line)
417 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
418 def validate_attributes(context, lid, neg, attrs):
420 idx = range(len(context.response.result))
421 context.execute_steps("then at least 1 result is returned")
423 idx = [int(lid.strip())]
424 context.execute_steps("then more than %sresults are returned" % lid)
427 for attr in attrs.split(','):
429 assert_not_in(attr, context.response.result[i])
431 assert_in(attr, context.response.result[i])
433 @then(u'result addresses contain')
434 def step_impl(context):
435 context.execute_steps("then at least 1 result is returned")
437 if 'ID' not in context.table.headings:
438 addr_parts = context.response.property_list('address')
440 for line in context.table:
441 if 'ID' in context.table.headings:
442 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
444 for h in context.table.headings:
448 assert_equal(p[h], line[h], "Bad address value for %s" % h)
450 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
451 def check_address(context, lid, neg, attrs):
452 context.execute_steps("then more than %s results are returned" % lid)
454 addr_parts = context.response.result[int(lid)]['address']
456 for attr in attrs.split(','):
458 assert_not_in(attr, addr_parts)
460 assert_in(attr, addr_parts)
462 @then(u'address of result (?P<lid>\d+) is')
463 def check_address(context, lid):
464 context.execute_steps("then more than %s results are returned" % lid)
466 addr_parts = dict(context.response.result[int(lid)]['address'])
468 for line in context.table:
469 assert_in(line['type'], addr_parts)
470 assert_equal(addr_parts[line['type']], line['value'],
471 "Bad address value for %s" % line['type'])
472 del addr_parts[line['type']]
474 eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
476 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
477 def step_impl(context, lid, coords):
479 context.execute_steps("then at least 1 result is returned")
480 bboxes = context.response.property_list('boundingbox')
482 context.execute_steps("then more than %sresults are returned" % lid)
483 bboxes = [ context.response.result[int(lid)]['boundingbox']]
485 coord = [ float(x) for x in coords.split(',') ]
488 if isinstance(bbox, str):
489 bbox = bbox.split(',')
490 bbox = [ float(x) for x in bbox ]
492 assert_greater_equal(bbox[0], coord[0])
493 assert_less_equal(bbox[1], coord[1])
494 assert_greater_equal(bbox[2], coord[2])
495 assert_less_equal(bbox[3], coord[3])
497 @then(u'there are(?P<neg> no)? duplicates')
498 def check_for_duplicates(context, neg):
499 context.execute_steps("then at least 1 result is returned")
504 for res in context.response.result:
505 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
512 assert not has_dupe, "Found duplicate for %s" % (dup, )
514 assert has_dupe, "No duplicates found"