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
180 params = { 'q' : query }
182 params['format'] = fmt.strip()
184 params['addressdetails'] = '1'
186 if context.table.headings[0] == 'param':
187 for line in context.table:
188 params[line['param']] = line['value']
190 for h in context.table.headings:
191 params[h] = context.table[0][h]
192 env['QUERY_STRING'] = urlencode(params)
194 env['REQUEST_URI'] = '/search.php?' + env['QUERY_STRING']
195 env['SCRIPT_NAME'] = '/search.php'
196 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
197 env['SCRIPT_FILENAME'] = os.path.join(context.nominatim.build_dir, 'website', 'search.php')
198 env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
200 cmd = [ '/usr/bin/php-cgi', env['SCRIPT_FILENAME']]
201 for k,v in params.items():
202 cmd.append("%s=%s" % (k, v))
204 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
205 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
207 (outp, err) = proc.communicate()
209 assert_equals(0, proc.returncode,
210 "query.php failed with message: %s\noutput: %s" % (err, outp))
212 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
214 outp = outp.decode('utf-8')
216 if outp.startswith('Status: '):
217 status = int(outp[8:11])
221 content_start = outp.find('\r\n\r\n')
222 assert_less(11, content_start)
226 elif fmt == 'jsonv2 ':
231 context.response = SearchResponse(outp[content_start + 4:], outfmt, status)
234 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
235 def validate_result_number(context, operator, number):
236 eq_(context.response.errorcode, 200)
237 numres = len(context.response.result)
238 ok_(compare(operator, numres, int(number)),
239 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
241 @then(u'a HTTP (?P<status>\d+) is returned')
242 def check_http_return_status(context, status):
243 eq_(context.response.errorcode, int(status))
245 @then(u'the result is valid (?P<fmt>\w+)')
246 def step_impl(context, fmt):
247 eq_(context.response.format, fmt)
249 @then(u'result header contains')
250 def check_header_attr(context):
251 for line in context.table:
252 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
253 "attribute '%s': expected: '%s', got '%s'"
254 % (line['attr'], line['value'],
255 context.response.header[line['attr']]))
257 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
258 def check_header_no_attr(context, neg, attrs):
259 for attr in attrs.split(','):
261 assert_not_in(attr, context.response.header)
263 assert_in(attr, context.response.header)
265 @then(u'results contain')
266 def step_impl(context):
267 context.execute_steps("then at least 1 result is returned")
269 for line in context.table:
270 context.response.match_row(line)
272 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
273 def validate_attributes(context, lid, neg, attrs):
275 idx = range(len(context.response.result))
276 context.execute_steps("then at least 1 result is returned")
278 idx = [int(lid.strip())]
279 context.execute_steps("then more than %sresults are returned" % lid)
282 for attr in attrs.split(','):
284 assert_not_in(attr, context.response.result[i])
286 assert_in(attr, context.response.result[i])
288 @then(u'result addresses contain')
289 def step_impl(context):
290 context.execute_steps("then at least 1 result is returned")
292 if 'ID' not in context.table.headings:
293 addr_parts = context.response.property_list('address')
295 for line in context.table:
296 if 'ID' in context.table.headings:
297 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
299 for h in context.table.headings:
303 assert_equal(p[h], line[h], "Bad address value for %s" % h)
305 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
306 def check_address(context, lid, neg, attrs):
307 context.execute_steps("then more than %s results are returned" % lid)
309 addr_parts = context.response.result[int(lid)]['address']
311 for attr in attrs.split(','):
313 assert_not_in(attr, addr_parts)
315 assert_in(attr, addr_parts)
317 @then(u'address of result (?P<lid>\d+) is')
318 def check_address(context, lid):
319 context.execute_steps("then more than %s results are returned" % lid)
321 addr_parts = dict(context.response.result[int(lid)]['address'])
323 for line in context.table:
324 assert_in(line['type'], addr_parts)
325 assert_equal(addr_parts[line['type']], line['value'],
326 "Bad address value for %s" % line['type'])
327 del addr_parts[line['type']]
329 eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
331 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
332 def step_impl(context, lid, coords):
334 context.execute_steps("then at least 1 result is returned")
335 bboxes = context.response.property_list('boundingbox')
337 context.execute_steps("then more than %sresults are returned" % lid)
338 bboxes = [ context.response.result[int(lid)]['boundingbox']]
340 coord = [ float(x) for x in coords.split(',') ]
343 if isinstance(bbox, str):
344 bbox = bbox.split(',')
345 bbox = [ float(x) for x in bbox ]
347 assert_greater_equal(bbox[0], coord[0])
348 assert_less_equal(bbox[1], coord[1])
349 assert_greater_equal(bbox[2], coord[2])
350 assert_less_equal(bbox[3], coord[3])
352 @then(u'there are(?P<neg> no)? duplicates')
353 def check_for_duplicates(context, neg):
354 context.execute_steps("then at least 1 result is returned")
359 for res in context.response.result:
360 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
367 assert not has_dupe, "Found duplicate for %s" % (dup, )
369 assert has_dupe, "No duplicates found"