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