]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/queries.py
175a85ae7141aa84032df194b5bf0f0bacb62995
[nominatim.git] / test / bdd / steps / queries.py
1 """ Steps that run search queries.
2
3     Queries may either be run directly via PHP using the query script
4     or via the HTTP interface.
5 """
6
7 import json
8 import os
9 import io
10 import re
11 from tidylib import tidy_document
12 import xml.etree.ElementTree as ET
13 import subprocess
14 from urllib.parse import urlencode
15 from collections import OrderedDict
16 from nose.tools import * # for assert functions
17
18 BASE_SERVER_ENV = {
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',
29     'SERVER_PORT' : '80',
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'
40 }
41
42
43 def compare(operator, op1, op2):
44     if operator == 'less than':
45         return op1 < op2
46     elif operator == 'more than':
47         return op1 > op2
48     elif operator == 'exactly':
49         return op1 == op2
50     elif operator == 'at least':
51         return op1 >= op2
52     elif operator == 'at most':
53         return op1 <= op2
54     else:
55         raise Exception("unknown operator '%s'" % operator)
56
57 class GenericResponse(object):
58
59     def match_row(self, row):
60         if 'ID' in row.headings:
61             todo = [int(row['ID'])]
62         else:
63             todo = range(len(self.result))
64
65         for i in todo:
66             res = self.result[i]
67             for h in row.headings:
68                 if h == 'ID':
69                     pass
70                 elif h == 'osm':
71                     assert_equal(res['osm_type'], row[h][0])
72                     assert_equal(res['osm_id'], row[h][1:])
73                 elif h == 'centroid':
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("^"):
78                     assert_in(h, res)
79                     assert_is_not_none(re.fullmatch(row[h], res[h]),
80                                        "attribute '%s': expected: '%s', got '%s'"
81                                           % (h, row[h], res[h]))
82                 else:
83                     assert_in(h, res)
84                     assert_equal(str(res[h]), str(row[h]))
85
86     def property_list(self, prop):
87         return [ x[prop] for x in self.result ]
88
89
90 class SearchResponse(GenericResponse):
91
92     def __init__(self, page, fmt='json', errorcode=200):
93         self.page = page
94         self.format = fmt
95         self.errorcode = errorcode
96         self.result = []
97         self.header = dict()
98
99         if errorcode == 200:
100             getattr(self, 'parse_' + fmt)()
101
102     def parse_json(self):
103         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
104         if m is None:
105             code = self.page
106         else:
107             code = m.group(2)
108             self.header['json_func'] = m.group(1)
109         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
110
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)
115
116         b = content.find('nominatim_results =')
117         e = content.find('</script>')
118         content = content[b:e]
119         b = content.find('[')
120         e = content.rfind(']')
121
122         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
123
124     def parse_xml(self):
125         et = ET.fromstring(self.page)
126
127         self.header = dict(et.attrib)
128
129         for child in et:
130             assert_equal(child.tag, "place")
131             self.result.append(dict(child.attrib))
132
133             address = {}
134             for sub in child:
135                 if sub.tag == 'extratags':
136                     self.result[-1]['extratags'] = {}
137                     for tag in sub:
138                         self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
139                 elif sub.tag == 'namedetails':
140                     self.result[-1]['namedetails'] = {}
141                     for tag in sub:
142                         self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
143                 elif sub.tag in ('geokml'):
144                     self.result[-1][sub.tag] = True
145                 else:
146                     address[sub.tag] = sub.text
147
148             if len(address) > 0:
149                 self.result[-1]['address'] = address
150
151
152
153 class ReverseResponse(GenericResponse):
154
155     def __init__(self, page, fmt='json', errorcode=200):
156         self.page = page
157         self.format = fmt
158         self.errorcode = errorcode
159         self.result = []
160         self.header = dict()
161
162         if errorcode == 200:
163             getattr(self, 'parse_' + fmt)()
164
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)
169
170         b = content.find('nominatim_results =')
171         e = content.find('</script>')
172         content = content[b:e]
173         b = content.find('[')
174         e = content.rfind(']')
175
176         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
177
178     def parse_json(self):
179         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
180         if m is None:
181             code = self.page
182         else:
183             code = m.group(2)
184             self.header['json_func'] = m.group(1)
185         self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)]
186
187     def parse_xml(self):
188         et = ET.fromstring(self.page)
189
190         self.header = dict(et.attrib)
191         self.result = []
192
193         for child in et:
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':
198                 address = {}
199                 for sub in child:
200                     address[sub.tag] = sub.text
201                 self.result[0]['address'] = address
202             elif child.tag == 'extratags':
203                 self.result[0]['extratags'] = {}
204                 for tag in child:
205                     self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
206             elif child.tag == 'namedetails':
207                 self.result[0]['namedetails'] = {}
208                 for tag in child:
209                     self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
210             elif child.tag in ('geokml'):
211                 self.result[0][child.tag] = True
212             else:
213                 assert child.tag == 'error', \
214                         "Unknown XML tag %s on page: %s" % (child.tag, self.page)
215
216
217 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
218 def query_cmd(context, query, dups):
219     """ Query directly via PHP script.
220     """
221     cmd = [os.path.join(context.nominatim.build_dir, 'utils', 'query.php'),
222            '--search', query]
223     # add more parameters in table form
224     if context.table:
225         for h in context.table.headings:
226             value = context.table[0][h].strip()
227             if value:
228                 cmd.extend(('--' + h, value))
229
230     if dups:
231         cmd.extend(('--dedupe', '0'))
232
233     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
234                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
235     (outp, err) = proc.communicate()
236
237     assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
238
239     context.response = SearchResponse(outp.decode('utf-8'), 'json')
240
241 def send_api_query(endpoint, params, fmt, context):
242     if fmt is not None:
243         params['format'] = fmt.strip()
244     if context.table:
245         if context.table.headings[0] == 'param':
246             for line in context.table:
247                 params[line['param']] = line['value']
248         else:
249             for h in context.table.headings:
250                 params[h] = context.table[0][h]
251
252     env = BASE_SERVER_ENV
253     env['QUERY_STRING'] = urlencode(params)
254
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'],
259                                           '%s.php' % endpoint)
260     env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
261
262     cmd = ['/usr/bin/php-cgi', env['SCRIPT_FILENAME']]
263     for k,v in params.items():
264         cmd.append("%s=%s" % (k, v))
265
266     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
267                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
268
269     (outp, err) = proc.communicate()
270
271     assert_equals(0, proc.returncode,
272                   "query.php failed with message: %s\noutput: %s" % (err, outp))
273
274     assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
275
276     outp = outp.decode('utf-8')
277
278     if outp.startswith('Status: '):
279         status = int(outp[8:11])
280     else:
281         status = 200
282
283     content_start = outp.find('\r\n\r\n')
284
285     return outp[content_start + 4:], status
286
287
288 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
289 def website_search_request(context, fmt, query, addr):
290
291     params = {}
292     if query:
293         params['q'] = query
294     if addr is not None:
295         params['addressdetails'] = '1'
296
297     outp, status = send_api_query('search', params, fmt, context)
298
299     if fmt is None:
300         outfmt = 'html'
301     elif fmt == 'jsonv2 ':
302         outfmt = 'json'
303     else:
304         outfmt = fmt.strip()
305
306     context.response = SearchResponse(outp, outfmt, status)
307
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):
310     params = {}
311     if lat is not None:
312         params['lat'] = lat
313     if lon is not None:
314         params['lon'] = lon
315
316     outp, status = send_api_query('reverse', params, fmt, context)
317
318     if fmt is None:
319         outfmt = 'xml'
320     elif fmt == 'jsonv2 ':
321         outfmt = 'json'
322     else:
323         outfmt = fmt.strip()
324
325     context.response = ReverseResponse(outp, outfmt, status)
326
327
328
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))
335
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))
339
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)
344
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']]))
352
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(','):
356         if neg:
357             assert_not_in(attr, context.response.header)
358         else:
359             assert_in(attr, context.response.header)
360
361 @then(u'results contain')
362 def step_impl(context):
363     context.execute_steps("then at least 1 result is returned")
364
365     for line in context.table:
366         context.response.match_row(line)
367
368 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
369 def validate_attributes(context, lid, neg, attrs):
370     if lid is None:
371         idx = range(len(context.response.result))
372         context.execute_steps("then at least 1 result is returned")
373     else:
374         idx = [int(lid.strip())]
375         context.execute_steps("then more than %sresults are returned" % lid)
376
377     for i in idx:
378         for attr in attrs.split(','):
379             if neg:
380                 assert_not_in(attr, context.response.result[i])
381             else:
382                 assert_in(attr, context.response.result[i])
383
384 @then(u'result addresses contain')
385 def step_impl(context):
386     context.execute_steps("then at least 1 result is returned")
387
388     if 'ID' not in context.table.headings:
389         addr_parts = context.response.property_list('address')
390
391     for line in context.table:
392         if 'ID' in context.table.headings:
393             addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
394
395         for h in context.table.headings:
396             if h != 'ID':
397                 for p in addr_parts:
398                     assert_in(h, p)
399                     assert_equal(p[h], line[h], "Bad address value for %s" % h)
400
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)
404
405     addr_parts = context.response.result[int(lid)]['address']
406
407     for attr in attrs.split(','):
408         if neg:
409             assert_not_in(attr, addr_parts)
410         else:
411             assert_in(attr, addr_parts)
412
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)
416
417     addr_parts = dict(context.response.result[int(lid)]['address'])
418
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']]
424
425     eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
426
427 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
428 def step_impl(context, lid, coords):
429     if lid is None:
430         context.execute_steps("then at least 1 result is returned")
431         bboxes = context.response.property_list('boundingbox')
432     else:
433         context.execute_steps("then more than %sresults are returned" % lid)
434         bboxes = [ context.response.result[int(lid)]['boundingbox']]
435
436     coord = [ float(x) for x in coords.split(',') ]
437
438     for bbox in bboxes:
439         if isinstance(bbox, str):
440             bbox = bbox.split(',')
441         bbox = [ float(x) for x in bbox ]
442
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])
447
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")
451
452     resarr = set()
453     has_dupe = False
454
455     for res in context.response.result:
456         dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
457         if dup in resarr:
458             has_dupe = True
459             break
460         resarr.add(dup)
461
462     if neg:
463         assert not has_dupe, "Found duplicate for %s" % (dup, )
464     else:
465         assert has_dupe, "No duplicates found"