]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/queries.py
set exception handler by request format, not always HTML
[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 import logging
12 from tidylib import tidy_document
13 import xml.etree.ElementTree as ET
14 import subprocess
15 from urllib.parse import urlencode
16 from collections import OrderedDict
17 from nose.tools import * # for assert functions
18
19 logger = logging.getLogger(__name__)
20
21 BASE_SERVER_ENV = {
22     'HTTP_HOST' : 'localhost',
23     'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
24     'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
25     'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
26     'HTTP_CONNECTION' : 'keep-alive',
27     'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
28     'SERVER_SOFTWARE' : 'Nominatim test',
29     'SERVER_NAME' : 'localhost',
30     'SERVER_ADDR' : '127.0.1.1',
31     'SERVER_PORT' : '80',
32     'REMOTE_ADDR' : '127.0.0.1',
33     'DOCUMENT_ROOT' : '/var/www',
34     'REQUEST_SCHEME' : 'http',
35     'CONTEXT_PREFIX' : '/',
36     'SERVER_ADMIN' : 'webmaster@localhost',
37     'REMOTE_PORT' : '49319',
38     'GATEWAY_INTERFACE' : 'CGI/1.1',
39     'SERVER_PROTOCOL' : 'HTTP/1.1',
40     'REQUEST_METHOD' : 'GET',
41     'REDIRECT_STATUS' : 'CGI'
42 }
43
44
45 def compare(operator, op1, op2):
46     if operator == 'less than':
47         return op1 < op2
48     elif operator == 'more than':
49         return op1 > op2
50     elif operator == 'exactly':
51         return op1 == op2
52     elif operator == 'at least':
53         return op1 >= op2
54     elif operator == 'at most':
55         return op1 <= op2
56     else:
57         raise Exception("unknown operator '%s'" % operator)
58
59 class GenericResponse(object):
60
61     def match_row(self, row):
62         if 'ID' in row.headings:
63             todo = [int(row['ID'])]
64         else:
65             todo = range(len(self.result))
66
67         for i in todo:
68             res = self.result[i]
69             for h in row.headings:
70                 if h == 'ID':
71                     pass
72                 elif h == 'osm':
73                     assert_equal(res['osm_type'], row[h][0])
74                     assert_equal(res['osm_id'], row[h][1:])
75                 elif h == 'centroid':
76                     x, y = row[h].split(' ')
77                     assert_almost_equal(float(y), float(res['lat']))
78                     assert_almost_equal(float(x), float(res['lon']))
79                 elif row[h].startswith("^"):
80                     assert_in(h, res)
81                     assert_is_not_none(re.fullmatch(row[h], res[h]),
82                                        "attribute '%s': expected: '%s', got '%s'"
83                                           % (h, row[h], res[h]))
84                 else:
85                     assert_in(h, res)
86                     assert_equal(str(res[h]), str(row[h]))
87
88     def property_list(self, prop):
89         return [ x[prop] for x in self.result ]
90
91
92 class SearchResponse(GenericResponse):
93
94     def __init__(self, page, fmt='json', errorcode=200):
95         self.page = page
96         self.format = fmt
97         self.errorcode = errorcode
98         self.result = []
99         self.header = dict()
100
101         if errorcode == 200:
102             getattr(self, 'parse_' + fmt)()
103
104     def parse_json(self):
105         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
106         if m is None:
107             code = self.page
108         else:
109             code = m.group(2)
110             self.header['json_func'] = m.group(1)
111         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
112
113     def parse_geojson(self):
114         self.parse_json()
115         self.result = geojson_results_to_json_results(self.result)
116
117     def parse_geocodejson(self):
118         return self.parse_geojson()
119
120     def parse_html(self):
121         content, errors = tidy_document(self.page,
122                                         options={'char-encoding' : 'utf8'})
123         #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
124
125         self.result = []
126         b = content.find('nominatim_results =')
127         e = content.find('</script>')
128         if b >= 0 and e >= 0:
129             content = content[b:e]
130
131             b = content.find('[')
132             e = content.rfind(']')
133             if b >= 0 and e >= 0:
134                 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict)\
135                                   .decode(content[b:e+1])
136
137     def parse_xml(self):
138         et = ET.fromstring(self.page)
139
140         self.header = dict(et.attrib)
141
142         for child in et:
143             assert_equal(child.tag, "place")
144             self.result.append(dict(child.attrib))
145
146             address = {}
147             for sub in child:
148                 if sub.tag == 'extratags':
149                     self.result[-1]['extratags'] = {}
150                     for tag in sub:
151                         self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
152                 elif sub.tag == 'namedetails':
153                     self.result[-1]['namedetails'] = {}
154                     for tag in sub:
155                         self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
156                 elif sub.tag in ('geokml'):
157                     self.result[-1][sub.tag] = True
158                 else:
159                     address[sub.tag] = sub.text
160
161             if len(address) > 0:
162                 self.result[-1]['address'] = address
163
164
165 class ReverseResponse(GenericResponse):
166
167     def __init__(self, page, fmt='json', errorcode=200):
168         self.page = page
169         self.format = fmt
170         self.errorcode = errorcode
171         self.result = []
172         self.header = dict()
173
174         if errorcode == 200:
175             getattr(self, 'parse_' + fmt)()
176
177     def parse_html(self):
178         content, errors = tidy_document(self.page,
179                                         options={'char-encoding' : 'utf8'})
180         #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
181
182         b = content.find('nominatim_results =')
183         e = content.find('</script>')
184         content = content[b:e]
185         b = content.find('[')
186         e = content.rfind(']')
187
188         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
189
190     def parse_json(self):
191         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
192         if m is None:
193             code = self.page
194         else:
195             code = m.group(2)
196             self.header['json_func'] = m.group(1)
197         self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)]
198
199     def parse_geojson(self):
200         self.parse_json()
201         if 'error' in self.result:
202             return
203         self.result = geojson_results_to_json_results(self.result[0])
204
205     def parse_geocodejson(self):
206         return self.parse_geojson()
207
208     def parse_xml(self):
209         et = ET.fromstring(self.page)
210
211         self.header = dict(et.attrib)
212         self.result = []
213
214         for child in et:
215             if child.tag == 'result':
216                 eq_(0, len(self.result), "More than one result in reverse result")
217                 self.result.append(dict(child.attrib))
218             elif child.tag == 'addressparts':
219                 address = {}
220                 for sub in child:
221                     address[sub.tag] = sub.text
222                 self.result[0]['address'] = address
223             elif child.tag == 'extratags':
224                 self.result[0]['extratags'] = {}
225                 for tag in child:
226                     self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
227             elif child.tag == 'namedetails':
228                 self.result[0]['namedetails'] = {}
229                 for tag in child:
230                     self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
231             elif child.tag in ('geokml'):
232                 self.result[0][child.tag] = True
233             else:
234                 assert child.tag == 'error', \
235                         "Unknown XML tag %s on page: %s" % (child.tag, self.page)
236
237
238 class DetailsResponse(GenericResponse):
239
240     def __init__(self, page, fmt='json', errorcode=200):
241         self.page = page
242         self.format = fmt
243         self.errorcode = errorcode
244         self.result = []
245         self.header = dict()
246
247         if errorcode == 200:
248             getattr(self, 'parse_' + fmt)()
249
250     def parse_html(self):
251         content, errors = tidy_document(self.page,
252                                         options={'char-encoding' : 'utf8'})
253         self.result = {}
254
255     def parse_json(self):
256         self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
257
258
259 class StatusResponse(GenericResponse):
260
261     def __init__(self, page, fmt='text', errorcode=200):
262         self.page = page
263         self.format = fmt
264         self.errorcode = errorcode
265
266         if errorcode == 200 and fmt != 'text':
267             getattr(self, 'parse_' + fmt)()
268
269     def parse_json(self):
270         self.result = [json.JSONDecoder(object_pairs_hook=OrderedDict).decode(self.page)]
271
272
273 def geojson_result_to_json_result(geojson_result):
274     result = geojson_result['properties']
275     result['geojson'] = geojson_result['geometry']
276     if 'bbox' in geojson_result:
277         # bbox is  minlon, minlat, maxlon, maxlat
278         # boundingbox is minlat, maxlat, minlon, maxlon
279         result['boundingbox'] = [
280                                     geojson_result['bbox'][1],
281                                     geojson_result['bbox'][3],
282                                     geojson_result['bbox'][0],
283                                     geojson_result['bbox'][2]
284                                 ]
285     return result
286
287
288 def geojson_results_to_json_results(geojson_results):
289     if 'error' in geojson_results:
290         return
291     return list(map(geojson_result_to_json_result, geojson_results['features']))
292
293
294 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
295 def query_cmd(context, query, dups):
296     """ Query directly via PHP script.
297     """
298     cmd = ['/usr/bin/env', 'php']
299     cmd.append(os.path.join(context.nominatim.build_dir, 'utils', 'query.php'))
300     cmd.extend(['--search', query])
301     # add more parameters in table form
302     if context.table:
303         for h in context.table.headings:
304             value = context.table[0][h].strip()
305             if value:
306                 cmd.extend(('--' + h, value))
307
308     if dups:
309         cmd.extend(('--dedupe', '0'))
310
311     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
312                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
313     (outp, err) = proc.communicate()
314
315     assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
316
317     context.response = SearchResponse(outp.decode('utf-8'), 'json')
318
319 def send_api_query(endpoint, params, fmt, context):
320     if fmt is not None:
321         params['format'] = fmt.strip()
322     if context.table:
323         if context.table.headings[0] == 'param':
324             for line in context.table:
325                 params[line['param']] = line['value']
326         else:
327             for h in context.table.headings:
328                 params[h] = context.table[0][h]
329
330     env = dict(BASE_SERVER_ENV)
331     env['QUERY_STRING'] = urlencode(params)
332
333     env['SCRIPT_NAME'] = '/%s.php' % endpoint
334     env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
335     env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
336     env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
337                                           '%s.php' % endpoint)
338     env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
339
340     logger.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
341
342     if hasattr(context, 'http_headers'):
343         env.update(context.http_headers)
344
345     cmd = ['/usr/bin/env', 'php-cgi', '-f']
346     if context.nominatim.code_coverage_path:
347         env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
348         env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
349         env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
350         env['SCRIPT_FILENAME'] = \
351                 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
352         cmd.append(env['SCRIPT_FILENAME'])
353         env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
354     else:
355         cmd.append(env['SCRIPT_FILENAME'])
356
357     for k,v in params.items():
358         cmd.append("%s=%s" % (k, v))
359
360     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
361                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
362
363     (outp, err) = proc.communicate()
364     outp = outp.decode('utf-8')
365     err = err.decode("utf-8")
366
367     logger.debug("Result: \n===============================\n"
368                  + outp + "\n===============================\n")
369
370     assert_equals(0, proc.returncode,
371                   "%s failed with message: %s" % (
372                       os.path.basename(env['SCRIPT_FILENAME']),
373                       err))
374
375     assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
376
377     if outp.startswith('Status: '):
378         status = int(outp[8:11])
379     else:
380         status = 200
381
382     content_start = outp.find('\r\n\r\n')
383
384     return outp[content_start + 4:], status
385
386 @given(u'the HTTP header')
387 def add_http_header(context):
388     if not hasattr(context, 'http_headers'):
389         context.http_headers = {}
390
391     for h in context.table.headings:
392         envvar = 'HTTP_' + h.upper().replace('-', '_')
393         context.http_headers[envvar] = context.table[0][h]
394
395
396 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
397 def website_search_request(context, fmt, query, addr):
398     params = {}
399     if query:
400         params['q'] = query
401     if addr is not None:
402         params['addressdetails'] = '1'
403
404     outp, status = send_api_query('search', params, fmt, context)
405
406     if fmt is None:
407         outfmt = 'html'
408     elif fmt == 'jsonv2 ':
409         outfmt = 'json'
410     else:
411         outfmt = fmt.strip()
412
413     context.response = SearchResponse(outp, outfmt, status)
414
415 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
416 def website_reverse_request(context, fmt, lat, lon):
417     params = {}
418     if lat is not None:
419         params['lat'] = lat
420     if lon is not None:
421         params['lon'] = lon
422
423     outp, status = send_api_query('reverse', params, fmt, context)
424
425     if fmt is None:
426         outfmt = 'xml'
427     elif fmt == 'jsonv2 ':
428         outfmt = 'json'
429     else:
430         outfmt = fmt.strip()
431
432     context.response = ReverseResponse(outp, outfmt, status)
433
434 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
435 def website_details_request(context, fmt, query):
436     params = {}
437     if query[0] in 'NWR':
438         params['osmtype'] = query[0]
439         params['osmid'] = query[1:]
440     else:
441         params['place_id'] = query
442     outp, status = send_api_query('details', params, fmt, context)
443
444     if fmt is None:
445         outfmt = 'html'
446     else:
447         outfmt = fmt.strip()
448
449     context.response = DetailsResponse(outp, outfmt, status)
450
451 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
452 def website_lookup_request(context, fmt, query):
453     params = { 'osm_ids' : query }
454     outp, status = send_api_query('lookup', params, fmt, context)
455
456     if fmt == 'json ':
457         outfmt = 'json'
458     elif fmt == 'geojson ':
459         outfmt = 'geojson'
460     else:
461         outfmt = 'xml'
462
463     context.response = SearchResponse(outp, outfmt, status)
464
465 @when(u'sending (?P<fmt>\S+ )?status query')
466 def website_status_request(context, fmt):
467     params = {}
468     outp, status = send_api_query('status', params, fmt, context)
469
470     if fmt is None:
471         outfmt = 'text'
472     else:
473         outfmt = fmt.strip()
474
475     context.response = StatusResponse(outp, outfmt, status)
476
477 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
478 def validate_result_number(context, operator, number):
479     eq_(context.response.errorcode, 200)
480     numres = len(context.response.result)
481     ok_(compare(operator, numres, int(number)),
482         "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
483
484 @then(u'a HTTP (?P<status>\d+) is returned')
485 def check_http_return_status(context, status):
486     eq_(context.response.errorcode, int(status))
487
488 @then(u'the page contents equals "(?P<text>.+)"')
489 def check_page_content_equals(context, text):
490     eq_(context.response.page, text)
491
492 @then(u'the result is valid (?P<fmt>\w+)')
493 def step_impl(context, fmt):
494     context.execute_steps("Then a HTTP 200 is returned")
495     eq_(context.response.format, fmt)
496
497 @then(u'a (?P<fmt>\w+) user error is returned')
498 def check_page_error(context, fmt):
499     context.execute_steps("Then a HTTP 400 is returned")
500     eq_(context.response.format, fmt)
501
502     if fmt == 'html':
503         assert_is_not_none(re.search(r'<html( |>).+</html>', context.response.page, re.DOTALL))
504     elif fmt == 'xml':
505         assert_is_not_none(re.search(r'<error>.+</error>', context.response.page, re.DOTALL))
506     else:
507         assert_is_not_none(re.search(r'({"error":)', context.response.page, re.DOTALL))
508
509 @then(u'result header contains')
510 def check_header_attr(context):
511     for line in context.table:
512         assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
513                      "attribute '%s': expected: '%s', got '%s'"
514                        % (line['attr'], line['value'],
515                           context.response.header[line['attr']]))
516
517 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
518 def check_header_no_attr(context, neg, attrs):
519     for attr in attrs.split(','):
520         if neg:
521             assert_not_in(attr, context.response.header)
522         else:
523             assert_in(attr, context.response.header)
524
525 @then(u'results contain')
526 def step_impl(context):
527     context.execute_steps("then at least 1 result is returned")
528
529     for line in context.table:
530         context.response.match_row(line)
531
532 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
533 def validate_attributes(context, lid, neg, attrs):
534     if lid is None:
535         idx = range(len(context.response.result))
536         context.execute_steps("then at least 1 result is returned")
537     else:
538         idx = [int(lid.strip())]
539         context.execute_steps("then more than %sresults are returned" % lid)
540
541     for i in idx:
542         for attr in attrs.split(','):
543             if neg:
544                 assert_not_in(attr, context.response.result[i])
545             else:
546                 assert_in(attr, context.response.result[i])
547
548 @then(u'result addresses contain')
549 def step_impl(context):
550     context.execute_steps("then at least 1 result is returned")
551
552     if 'ID' not in context.table.headings:
553         addr_parts = context.response.property_list('address')
554
555     for line in context.table:
556         if 'ID' in context.table.headings:
557             addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
558
559         for h in context.table.headings:
560             if h != 'ID':
561                 for p in addr_parts:
562                     assert_in(h, p)
563                     assert_equal(p[h], line[h], "Bad address value for %s" % h)
564
565 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
566 def check_address(context, lid, neg, attrs):
567     context.execute_steps("then more than %s results are returned" % lid)
568
569     addr_parts = context.response.result[int(lid)]['address']
570
571     for attr in attrs.split(','):
572         if neg:
573             assert_not_in(attr, addr_parts)
574         else:
575             assert_in(attr, addr_parts)
576
577 @then(u'address of result (?P<lid>\d+) is')
578 def check_address(context, lid):
579     context.execute_steps("then more than %s results are returned" % lid)
580
581     addr_parts = dict(context.response.result[int(lid)]['address'])
582
583     for line in context.table:
584         assert_in(line['type'], addr_parts)
585         assert_equal(addr_parts[line['type']], line['value'],
586                      "Bad address value for %s" % line['type'])
587         del addr_parts[line['type']]
588
589     eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
590
591 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
592 def step_impl(context, lid, coords):
593     if lid is None:
594         context.execute_steps("then at least 1 result is returned")
595         bboxes = context.response.property_list('boundingbox')
596     else:
597         context.execute_steps("then more than %sresults are returned" % lid)
598         bboxes = [ context.response.result[int(lid)]['boundingbox']]
599
600     coord = [ float(x) for x in coords.split(',') ]
601
602     for bbox in bboxes:
603         if isinstance(bbox, str):
604             bbox = bbox.split(',')
605         bbox = [ float(x) for x in bbox ]
606
607         assert_greater_equal(bbox[0], coord[0])
608         assert_less_equal(bbox[1], coord[1])
609         assert_greater_equal(bbox[2], coord[2])
610         assert_less_equal(bbox[3], coord[3])
611
612 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
613 def step_impl(context, lid, coords):
614     if lid is None:
615         context.execute_steps("then at least 1 result is returned")
616         bboxes = zip(context.response.property_list('lat'),
617                      context.response.property_list('lon'))
618     else:
619         context.execute_steps("then more than %sresults are returned" % lid)
620         res = context.response.result[int(lid)]
621         bboxes = [ (res['lat'], res['lon']) ]
622
623     coord = [ float(x) for x in coords.split(',') ]
624
625     for lat, lon in bboxes:
626         lat = float(lat)
627         lon = float(lon)
628         assert_greater_equal(lat, coord[0])
629         assert_less_equal(lat, coord[1])
630         assert_greater_equal(lon, coord[2])
631         assert_less_equal(lon, coord[3])
632
633 @then(u'there are(?P<neg> no)? duplicates')
634 def check_for_duplicates(context, neg):
635     context.execute_steps("then at least 1 result is returned")
636
637     resarr = set()
638     has_dupe = False
639
640     for res in context.response.result:
641         dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
642         if dup in resarr:
643             has_dupe = True
644             break
645         resarr.add(dup)
646
647     if neg:
648         assert not has_dupe, "Found duplicate for %s" % (dup, )
649     else:
650         assert has_dupe, "No duplicates found"