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