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)
58 class SearchResponse(object):
60 def __init__(self, page, fmt='json', errorcode=200):
63 self.errorcode = errorcode
68 getattr(self, 'parse_' + fmt)()
71 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
76 self.header['json_func'] = m.group(1)
77 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
80 content, errors = tidy_document(self.page,
81 options={'char-encoding' : 'utf8'})
82 #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
84 b = content.find('nominatim_results =')
85 e = content.find('</script>')
86 content = content[b:e]
88 e = content.rfind(']')
90 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
93 et = ET.fromstring(self.page)
95 self.header = dict(et.attrib)
98 assert_equal(child.tag, "place")
99 self.result.append(dict(child.attrib))
103 if sub.tag == 'extratags':
104 self.result[-1]['extratags'] = {}
106 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
107 elif sub.tag == 'namedetails':
108 self.result[-1]['namedetails'] = {}
110 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
111 elif sub.tag in ('geokml'):
112 self.result[-1][sub.tag] = True
114 address[sub.tag] = sub.text
117 self.result[-1]['address'] = address
120 def match_row(self, row):
121 if 'ID' in row.headings:
122 todo = [int(row['ID'])]
124 todo = range(len(self.result))
128 for h in row.headings:
132 assert_equal(res['osm_type'], row[h][0])
133 assert_equal(res['osm_id'], row[h][1:])
134 elif h == 'centroid':
135 x, y = row[h].split(' ')
136 assert_almost_equal(float(y), float(res['lat']))
137 assert_almost_equal(float(x), float(res['lon']))
138 elif row[h].startswith("^"):
140 assert_is_not_none(re.fullmatch(row[h], res[h]),
141 "attribute '%s': expected: '%s', got '%s'"
142 % (h, row[h], res[h]))
145 assert_equal(str(res[h]), str(row[h]))
147 def property_list(self, prop):
148 return [ x[prop] for x in self.result ]
151 class ReverseResponse(object):
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)
216 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
217 def query_cmd(context, query, dups):
218 """ Query directly via PHP script.
220 cmd = [os.path.join(context.nominatim.build_dir, 'utils', 'query.php'),
222 # add more parameters in table form
224 for h in context.table.headings:
225 value = context.table[0][h].strip()
227 cmd.extend(('--' + h, value))
230 cmd.extend(('--dedupe', '0'))
232 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
233 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
234 (outp, err) = proc.communicate()
236 assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
238 context.response = SearchResponse(outp.decode('utf-8'), 'json')
240 def send_api_query(endpoint, params, fmt, context):
242 params['format'] = fmt.strip()
244 if context.table.headings[0] == 'param':
245 for line in context.table:
246 params[line['param']] = line['value']
248 for h in context.table.headings:
249 params[h] = context.table[0][h]
251 env = BASE_SERVER_ENV
252 env['QUERY_STRING'] = urlencode(params)
254 env['SCRIPT_NAME'] = '/%s.php' % endpoint
255 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
256 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
257 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
259 env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
261 cmd = ['/usr/bin/php-cgi', env['SCRIPT_FILENAME']]
262 for k,v in params.items():
263 cmd.append("%s=%s" % (k, v))
265 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
266 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
268 (outp, err) = proc.communicate()
270 assert_equals(0, proc.returncode,
271 "query.php failed with message: %s\noutput: %s" % (err, outp))
273 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
275 outp = outp.decode('utf-8')
277 if outp.startswith('Status: '):
278 status = int(outp[8:11])
282 content_start = outp.find('\r\n\r\n')
284 return outp[content_start + 4:], status
287 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
288 def website_search_request(context, fmt, query, addr):
294 params['addressdetails'] = '1'
296 outp, status = send_api_query('search', params, fmt, context)
300 elif fmt == 'jsonv2 ':
305 context.response = SearchResponse(outp, outfmt, status)
307 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>[0-9.-]+)?,(?P<lon>[0-9.-]+)?')
308 def website_reverse_request(context, fmt, lat, lon):
315 outp, status = send_api_query('reverse', params, fmt, context)
319 elif fmt == 'jsonv2 ':
324 context.response = ReverseResponse(outp, outfmt, status)
328 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
329 def validate_result_number(context, operator, number):
330 eq_(context.response.errorcode, 200)
331 numres = len(context.response.result)
332 ok_(compare(operator, numres, int(number)),
333 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
335 @then(u'a HTTP (?P<status>\d+) is returned')
336 def check_http_return_status(context, status):
337 eq_(context.response.errorcode, int(status))
339 @then(u'the result is valid (?P<fmt>\w+)')
340 def step_impl(context, fmt):
341 context.execute_steps("Then a HTTP 200 is returned")
342 eq_(context.response.format, fmt)
344 @then(u'result header contains')
345 def check_header_attr(context):
346 for line in context.table:
347 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
348 "attribute '%s': expected: '%s', got '%s'"
349 % (line['attr'], line['value'],
350 context.response.header[line['attr']]))
352 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
353 def check_header_no_attr(context, neg, attrs):
354 for attr in attrs.split(','):
356 assert_not_in(attr, context.response.header)
358 assert_in(attr, context.response.header)
360 @then(u'results contain')
361 def step_impl(context):
362 context.execute_steps("then at least 1 result is returned")
364 for line in context.table:
365 context.response.match_row(line)
367 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
368 def validate_attributes(context, lid, neg, attrs):
370 idx = range(len(context.response.result))
371 context.execute_steps("then at least 1 result is returned")
373 idx = [int(lid.strip())]
374 context.execute_steps("then more than %sresults are returned" % lid)
377 for attr in attrs.split(','):
379 assert_not_in(attr, context.response.result[i])
381 assert_in(attr, context.response.result[i])
383 @then(u'result addresses contain')
384 def step_impl(context):
385 context.execute_steps("then at least 1 result is returned")
387 if 'ID' not in context.table.headings:
388 addr_parts = context.response.property_list('address')
390 for line in context.table:
391 if 'ID' in context.table.headings:
392 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
394 for h in context.table.headings:
398 assert_equal(p[h], line[h], "Bad address value for %s" % h)
400 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
401 def check_address(context, lid, neg, attrs):
402 context.execute_steps("then more than %s results are returned" % lid)
404 addr_parts = context.response.result[int(lid)]['address']
406 for attr in attrs.split(','):
408 assert_not_in(attr, addr_parts)
410 assert_in(attr, addr_parts)
412 @then(u'address of result (?P<lid>\d+) is')
413 def check_address(context, lid):
414 context.execute_steps("then more than %s results are returned" % lid)
416 addr_parts = dict(context.response.result[int(lid)]['address'])
418 for line in context.table:
419 assert_in(line['type'], addr_parts)
420 assert_equal(addr_parts[line['type']], line['value'],
421 "Bad address value for %s" % line['type'])
422 del addr_parts[line['type']]
424 eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
426 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
427 def step_impl(context, lid, coords):
429 context.execute_steps("then at least 1 result is returned")
430 bboxes = context.response.property_list('boundingbox')
432 context.execute_steps("then more than %sresults are returned" % lid)
433 bboxes = [ context.response.result[int(lid)]['boundingbox']]
435 coord = [ float(x) for x in coords.split(',') ]
438 if isinstance(bbox, str):
439 bbox = bbox.split(',')
440 bbox = [ float(x) for x in bbox ]
442 assert_greater_equal(bbox[0], coord[0])
443 assert_less_equal(bbox[1], coord[1])
444 assert_greater_equal(bbox[2], coord[2])
445 assert_less_equal(bbox[3], coord[3])
447 @then(u'there are(?P<neg> no)? duplicates')
448 def check_for_duplicates(context, neg):
449 context.execute_steps("then at least 1 result is returned")
454 for res in context.response.result:
455 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
462 assert not has_dupe, "Found duplicate for %s" % (dup, )
464 assert has_dupe, "No duplicates found"