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