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_LANGUAGE' : 'en,de;q=0.5',
23 'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
24 'HTTP_CONNECTION' : 'keep-alive',
25 'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
26 'SERVER_SOFTWARE' : 'Nominatim test',
27 'SERVER_NAME' : 'localhost',
28 'SERVER_ADDR' : '127.0.1.1',
30 'REMOTE_ADDR' : '127.0.0.1',
31 'DOCUMENT_ROOT' : '/var/www',
32 'REQUEST_SCHEME' : 'http',
33 'CONTEXT_PREFIX' : '/',
34 'SERVER_ADMIN' : 'webmaster@localhost',
35 'REMOTE_PORT' : '49319',
36 'GATEWAY_INTERFACE' : 'CGI/1.1',
37 'SERVER_PROTOCOL' : 'HTTP/1.1',
38 'REQUEST_METHOD' : 'GET',
39 'REDIRECT_STATUS' : 'CGI'
43 def compare(operator, op1, op2):
44 if operator == 'less than':
46 elif operator == 'more than':
48 elif operator == 'exactly':
50 elif operator == 'at least':
52 elif operator == 'at most':
55 raise Exception("unknown operator '%s'" % operator)
57 class GenericResponse(object):
59 def match_row(self, row):
60 if 'ID' in row.headings:
61 todo = [int(row['ID'])]
63 todo = range(len(self.result))
67 for h in row.headings:
71 assert_equal(res['osm_type'], row[h][0])
72 assert_equal(res['osm_id'], row[h][1:])
74 x, y = row[h].split(' ')
75 assert_almost_equal(float(y), float(res['lat']))
76 assert_almost_equal(float(x), float(res['lon']))
77 elif row[h].startswith("^"):
79 assert_is_not_none(re.fullmatch(row[h], res[h]),
80 "attribute '%s': expected: '%s', got '%s'"
81 % (h, row[h], res[h]))
84 assert_equal(str(res[h]), str(row[h]))
86 def property_list(self, prop):
87 return [ x[prop] for x in self.result ]
90 class SearchResponse(GenericResponse):
92 def __init__(self, page, fmt='json', errorcode=200):
95 self.errorcode = errorcode
100 getattr(self, 'parse_' + fmt)()
102 def parse_json(self):
103 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
108 self.header['json_func'] = m.group(1)
109 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
111 def parse_html(self):
112 content, errors = tidy_document(self.page,
113 options={'char-encoding' : 'utf8'})
114 #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
116 b = content.find('nominatim_results =')
117 e = content.find('</script>')
118 content = content[b:e]
119 b = content.find('[')
120 e = content.rfind(']')
122 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
125 et = ET.fromstring(self.page)
127 self.header = dict(et.attrib)
130 assert_equal(child.tag, "place")
131 self.result.append(dict(child.attrib))
135 if sub.tag == 'extratags':
136 self.result[-1]['extratags'] = {}
138 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
139 elif sub.tag == 'namedetails':
140 self.result[-1]['namedetails'] = {}
142 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
143 elif sub.tag in ('geokml'):
144 self.result[-1][sub.tag] = True
146 address[sub.tag] = sub.text
149 self.result[-1]['address'] = address
153 class ReverseResponse(GenericResponse):
155 def __init__(self, page, fmt='json', errorcode=200):
158 self.errorcode = errorcode
163 getattr(self, 'parse_' + fmt)()
165 def parse_html(self):
166 content, errors = tidy_document(self.page,
167 options={'char-encoding' : 'utf8'})
168 #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
170 b = content.find('nominatim_results =')
171 e = content.find('</script>')
172 content = content[b:e]
173 b = content.find('[')
174 e = content.rfind(']')
176 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
178 def parse_json(self):
179 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
184 self.header['json_func'] = m.group(1)
185 self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)]
188 et = ET.fromstring(self.page)
190 self.header = dict(et.attrib)
194 if child.tag == 'result':
195 eq_(0, len(self.result), "More than one result in reverse result")
196 self.result.append(dict(child.attrib))
197 elif child.tag == 'addressparts':
200 address[sub.tag] = sub.text
201 self.result[0]['address'] = address
202 elif child.tag == 'extratags':
203 self.result[0]['extratags'] = {}
205 self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
206 elif child.tag == 'namedetails':
207 self.result[0]['namedetails'] = {}
209 self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
210 elif child.tag in ('geokml'):
211 self.result[0][child.tag] = True
213 assert child.tag == 'error', \
214 "Unknown XML tag %s on page: %s" % (child.tag, self.page)
217 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
218 def query_cmd(context, query, dups):
219 """ Query directly via PHP script.
221 cmd = [os.path.join(context.nominatim.build_dir, 'utils', 'query.php'),
223 # add more parameters in table form
225 for h in context.table.headings:
226 value = context.table[0][h].strip()
228 cmd.extend(('--' + h, value))
231 cmd.extend(('--dedupe', '0'))
233 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
234 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
235 (outp, err) = proc.communicate()
237 assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
239 context.response = SearchResponse(outp.decode('utf-8'), 'json')
241 def send_api_query(endpoint, params, fmt, context):
243 params['format'] = fmt.strip()
245 if context.table.headings[0] == 'param':
246 for line in context.table:
247 params[line['param']] = line['value']
249 for h in context.table.headings:
250 params[h] = context.table[0][h]
252 env = BASE_SERVER_ENV
253 env['QUERY_STRING'] = urlencode(params)
255 env['SCRIPT_NAME'] = '/%s.php' % endpoint
256 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
257 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
258 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
260 env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
262 cmd = ['/usr/bin/php-cgi', env['SCRIPT_FILENAME']]
263 for k,v in params.items():
264 cmd.append("%s=%s" % (k, v))
266 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
267 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
269 (outp, err) = proc.communicate()
271 assert_equals(0, proc.returncode,
272 "query.php failed with message: %s\noutput: %s" % (err, outp))
274 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
276 outp = outp.decode('utf-8')
278 if outp.startswith('Status: '):
279 status = int(outp[8:11])
283 content_start = outp.find('\r\n\r\n')
285 return outp[content_start + 4:], status
288 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
289 def website_search_request(context, fmt, query, addr):
295 params['addressdetails'] = '1'
297 outp, status = send_api_query('search', params, fmt, context)
301 elif fmt == 'jsonv2 ':
306 context.response = SearchResponse(outp, outfmt, status)
308 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>[0-9.-]+)?,(?P<lon>[0-9.-]+)?')
309 def website_reverse_request(context, fmt, lat, lon):
316 outp, status = send_api_query('reverse', params, fmt, context)
320 elif fmt == 'jsonv2 ':
325 context.response = ReverseResponse(outp, outfmt, status)
329 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
330 def validate_result_number(context, operator, number):
331 eq_(context.response.errorcode, 200)
332 numres = len(context.response.result)
333 ok_(compare(operator, numres, int(number)),
334 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
336 @then(u'a HTTP (?P<status>\d+) is returned')
337 def check_http_return_status(context, status):
338 eq_(context.response.errorcode, int(status))
340 @then(u'the result is valid (?P<fmt>\w+)')
341 def step_impl(context, fmt):
342 context.execute_steps("Then a HTTP 200 is returned")
343 eq_(context.response.format, fmt)
345 @then(u'result header contains')
346 def check_header_attr(context):
347 for line in context.table:
348 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
349 "attribute '%s': expected: '%s', got '%s'"
350 % (line['attr'], line['value'],
351 context.response.header[line['attr']]))
353 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
354 def check_header_no_attr(context, neg, attrs):
355 for attr in attrs.split(','):
357 assert_not_in(attr, context.response.header)
359 assert_in(attr, context.response.header)
361 @then(u'results contain')
362 def step_impl(context):
363 context.execute_steps("then at least 1 result is returned")
365 for line in context.table:
366 context.response.match_row(line)
368 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
369 def validate_attributes(context, lid, neg, attrs):
371 idx = range(len(context.response.result))
372 context.execute_steps("then at least 1 result is returned")
374 idx = [int(lid.strip())]
375 context.execute_steps("then more than %sresults are returned" % lid)
378 for attr in attrs.split(','):
380 assert_not_in(attr, context.response.result[i])
382 assert_in(attr, context.response.result[i])
384 @then(u'result addresses contain')
385 def step_impl(context):
386 context.execute_steps("then at least 1 result is returned")
388 if 'ID' not in context.table.headings:
389 addr_parts = context.response.property_list('address')
391 for line in context.table:
392 if 'ID' in context.table.headings:
393 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
395 for h in context.table.headings:
399 assert_equal(p[h], line[h], "Bad address value for %s" % h)
401 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
402 def check_address(context, lid, neg, attrs):
403 context.execute_steps("then more than %s results are returned" % lid)
405 addr_parts = context.response.result[int(lid)]['address']
407 for attr in attrs.split(','):
409 assert_not_in(attr, addr_parts)
411 assert_in(attr, addr_parts)
413 @then(u'address of result (?P<lid>\d+) is')
414 def check_address(context, lid):
415 context.execute_steps("then more than %s results are returned" % lid)
417 addr_parts = dict(context.response.result[int(lid)]['address'])
419 for line in context.table:
420 assert_in(line['type'], addr_parts)
421 assert_equal(addr_parts[line['type']], line['value'],
422 "Bad address value for %s" % line['type'])
423 del addr_parts[line['type']]
425 eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
427 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
428 def step_impl(context, lid, coords):
430 context.execute_steps("then at least 1 result is returned")
431 bboxes = context.response.property_list('boundingbox')
433 context.execute_steps("then more than %sresults are returned" % lid)
434 bboxes = [ context.response.result[int(lid)]['boundingbox']]
436 coord = [ float(x) for x in coords.split(',') ]
439 if isinstance(bbox, str):
440 bbox = bbox.split(',')
441 bbox = [ float(x) for x in bbox ]
443 assert_greater_equal(bbox[0], coord[0])
444 assert_less_equal(bbox[1], coord[1])
445 assert_greater_equal(bbox[2], coord[2])
446 assert_less_equal(bbox[3], coord[3])
448 @then(u'there are(?P<neg> no)? duplicates')
449 def check_for_duplicates(context, neg):
450 context.execute_steps("then at least 1 result is returned")
455 for res in context.response.result:
456 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
463 assert not has_dupe, "Found duplicate for %s" % (dup, )
465 assert has_dupe, "No duplicates found"