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 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
152 def query_cmd(context, query, dups):
153 """ Query directly via PHP script.
155 cmd = [os.path.join(context.nominatim.build_dir, 'utils', 'query.php'),
157 # add more parameters in table form
159 for h in context.table.headings:
160 value = context.table[0][h].strip()
162 cmd.extend(('--' + h, value))
165 cmd.extend(('--dedupe', '0'))
167 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
168 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
169 (outp, err) = proc.communicate()
171 assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
173 context.response = SearchResponse(outp.decode('utf-8'), 'json')
176 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
177 def website_search_request(context, fmt, query, addr):
178 env = BASE_SERVER_ENV
184 params['format'] = fmt.strip()
186 params['addressdetails'] = '1'
188 if context.table.headings[0] == 'param':
189 for line in context.table:
190 params[line['param']] = line['value']
192 for h in context.table.headings:
193 params[h] = context.table[0][h]
194 env['QUERY_STRING'] = urlencode(params)
196 env['REQUEST_URI'] = '/search.php?' + env['QUERY_STRING']
197 env['SCRIPT_NAME'] = '/search.php'
198 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
199 env['SCRIPT_FILENAME'] = os.path.join(context.nominatim.build_dir, 'website', 'search.php')
200 env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
202 cmd = [ '/usr/bin/php-cgi', env['SCRIPT_FILENAME']]
203 for k,v in params.items():
204 cmd.append("%s=%s" % (k, v))
206 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
207 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
209 (outp, err) = proc.communicate()
211 assert_equals(0, proc.returncode,
212 "query.php failed with message: %s\noutput: %s" % (err, outp))
214 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
216 outp = outp.decode('utf-8')
218 if outp.startswith('Status: '):
219 status = int(outp[8:11])
223 content_start = outp.find('\r\n\r\n')
224 assert_less(11, content_start)
228 elif fmt == 'jsonv2 ':
233 context.response = SearchResponse(outp[content_start + 4:], outfmt, status)
236 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
237 def validate_result_number(context, operator, number):
238 eq_(context.response.errorcode, 200)
239 numres = len(context.response.result)
240 ok_(compare(operator, numres, int(number)),
241 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
243 @then(u'a HTTP (?P<status>\d+) is returned')
244 def check_http_return_status(context, status):
245 eq_(context.response.errorcode, int(status))
247 @then(u'the result is valid (?P<fmt>\w+)')
248 def step_impl(context, fmt):
249 eq_(context.response.format, fmt)
251 @then(u'result header contains')
252 def check_header_attr(context):
253 for line in context.table:
254 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
255 "attribute '%s': expected: '%s', got '%s'"
256 % (line['attr'], line['value'],
257 context.response.header[line['attr']]))
259 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
260 def check_header_no_attr(context, neg, attrs):
261 for attr in attrs.split(','):
263 assert_not_in(attr, context.response.header)
265 assert_in(attr, context.response.header)
267 @then(u'results contain')
268 def step_impl(context):
269 context.execute_steps("then at least 1 result is returned")
271 for line in context.table:
272 context.response.match_row(line)
274 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
275 def validate_attributes(context, lid, neg, attrs):
277 idx = range(len(context.response.result))
278 context.execute_steps("then at least 1 result is returned")
280 idx = [int(lid.strip())]
281 context.execute_steps("then more than %sresults are returned" % lid)
284 for attr in attrs.split(','):
286 assert_not_in(attr, context.response.result[i])
288 assert_in(attr, context.response.result[i])
290 @then(u'result addresses contain')
291 def step_impl(context):
292 context.execute_steps("then at least 1 result is returned")
294 if 'ID' not in context.table.headings:
295 addr_parts = context.response.property_list('address')
297 for line in context.table:
298 if 'ID' in context.table.headings:
299 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
301 for h in context.table.headings:
305 assert_equal(p[h], line[h], "Bad address value for %s" % h)
307 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
308 def check_address(context, lid, neg, attrs):
309 context.execute_steps("then more than %s results are returned" % lid)
311 addr_parts = context.response.result[int(lid)]['address']
313 for attr in attrs.split(','):
315 assert_not_in(attr, addr_parts)
317 assert_in(attr, addr_parts)
319 @then(u'address of result (?P<lid>\d+) is')
320 def check_address(context, lid):
321 context.execute_steps("then more than %s results are returned" % lid)
323 addr_parts = dict(context.response.result[int(lid)]['address'])
325 for line in context.table:
326 assert_in(line['type'], addr_parts)
327 assert_equal(addr_parts[line['type']], line['value'],
328 "Bad address value for %s" % line['type'])
329 del addr_parts[line['type']]
331 eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
333 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
334 def step_impl(context, lid, coords):
336 context.execute_steps("then at least 1 result is returned")
337 bboxes = context.response.property_list('boundingbox')
339 context.execute_steps("then more than %sresults are returned" % lid)
340 bboxes = [ context.response.result[int(lid)]['boundingbox']]
342 coord = [ float(x) for x in coords.split(',') ]
345 if isinstance(bbox, str):
346 bbox = bbox.split(',')
347 bbox = [ float(x) for x in bbox ]
349 assert_greater_equal(bbox[0], coord[0])
350 assert_less_equal(bbox[1], coord[1])
351 assert_greater_equal(bbox[2], coord[2])
352 assert_less_equal(bbox[3], coord[3])
354 @then(u'there are(?P<neg> no)? duplicates')
355 def check_for_duplicates(context, neg):
356 context.execute_steps("then at least 1 result is returned")
361 for res in context.response.result:
362 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
369 assert not has_dupe, "Found duplicate for %s" % (dup, )
371 assert has_dupe, "No duplicates found"