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