]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/queries.py
get apt-get php-db package running on travis-ci (#973)
[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 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
236 def query_cmd(context, query, dups):
237     """ Query directly via PHP script.
238     """
239     cmd = ['/usr/bin/env', 'php']
240     cmd.append(os.path.join(context.nominatim.build_dir, 'utils', 'query.php'))
241     cmd.extend(['--search', query])
242     # add more parameters in table form
243     if context.table:
244         for h in context.table.headings:
245             value = context.table[0][h].strip()
246             if value:
247                 cmd.extend(('--' + h, value))
248
249     if dups:
250         cmd.extend(('--dedupe', '0'))
251
252     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
253                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
254     (outp, err) = proc.communicate()
255
256     assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
257
258     context.response = SearchResponse(outp.decode('utf-8'), 'json')
259
260 def send_api_query(endpoint, params, fmt, context):
261     if fmt is not None:
262         params['format'] = fmt.strip()
263     if context.table:
264         if context.table.headings[0] == 'param':
265             for line in context.table:
266                 params[line['param']] = line['value']
267         else:
268             for h in context.table.headings:
269                 params[h] = context.table[0][h]
270
271     env = dict(BASE_SERVER_ENV)
272     env['QUERY_STRING'] = urlencode(params)
273
274     env['SCRIPT_NAME'] = '/%s.php' % endpoint
275     env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
276     env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
277     env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
278                                           '%s.php' % endpoint)
279     env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
280
281     logger.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
282
283     if hasattr(context, 'http_headers'):
284         env.update(context.http_headers)
285
286     cmd = ['/usr/bin/env', 'php-cgi', '-f']
287     if context.nominatim.code_coverage_path:
288         env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
289         env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
290         env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
291         env['SCRIPT_FILENAME'] = \
292                 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
293         cmd.append(env['SCRIPT_FILENAME'])
294         env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
295     else:
296         cmd.append(env['SCRIPT_FILENAME'])
297
298     for k,v in params.items():
299         cmd.append("%s=%s" % (k, v))
300
301     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
302                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
303
304     (outp, err) = proc.communicate()
305     outp = outp.decode('utf-8')
306
307     logger.debug("Result: \n===============================\n"
308                  + outp + "\n===============================\n")
309
310     assert_equals(0, proc.returncode,
311                   "%s failed with message: %s\noutput: %s" % (env['SCRIPT_FILENAME'], err, outp))
312
313     assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
314
315     if outp.startswith('Status: '):
316         status = int(outp[8:11])
317     else:
318         status = 200
319
320     content_start = outp.find('\r\n\r\n')
321
322     return outp[content_start + 4:], status
323
324 @given(u'the HTTP header')
325 def add_http_header(context):
326     if not hasattr(context, 'http_headers'):
327         context.http_headers = {}
328
329     for h in context.table.headings:
330         envvar = 'HTTP_' + h.upper().replace('-', '_')
331         context.http_headers[envvar] = context.table[0][h]
332
333
334 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
335 def website_search_request(context, fmt, query, addr):
336     params = {}
337     if query:
338         params['q'] = query
339     if addr is not None:
340         params['addressdetails'] = '1'
341
342     outp, status = send_api_query('search', params, fmt, context)
343
344     if fmt is None:
345         outfmt = 'html'
346     elif fmt == 'jsonv2 ':
347         outfmt = 'json'
348     else:
349         outfmt = fmt.strip()
350
351     context.response = SearchResponse(outp, outfmt, status)
352
353 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
354 def website_reverse_request(context, fmt, lat, lon):
355     params = {}
356     if lat is not None:
357         params['lat'] = lat
358     if lon is not None:
359         params['lon'] = lon
360
361     outp, status = send_api_query('reverse', params, fmt, context)
362
363     if fmt is None:
364         outfmt = 'xml'
365     elif fmt == 'jsonv2 ':
366         outfmt = 'json'
367     else:
368         outfmt = fmt.strip()
369
370     context.response = ReverseResponse(outp, outfmt, status)
371
372 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
373 def website_details_request(context, fmt, query):
374     params = {}
375     if query[0] in 'NWR':
376         params['osmtype'] = query[0]
377         params['osmid'] = query[1:]
378     else:
379         params['place_id'] = query
380     outp, status = send_api_query('details', params, fmt, context)
381
382     context.response = DetailsResponse(outp, 'html', status)
383
384 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
385 def website_lookup_request(context, fmt, query):
386     params = { 'osm_ids' : query }
387     outp, status = send_api_query('lookup', params, fmt, context)
388
389     if fmt == 'json ':
390         outfmt = 'json'
391     else:
392         outfmt = 'xml'
393
394     context.response = SearchResponse(outp, outfmt, status)
395
396 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
397 def validate_result_number(context, operator, number):
398     eq_(context.response.errorcode, 200)
399     numres = len(context.response.result)
400     ok_(compare(operator, numres, int(number)),
401         "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
402
403 @then(u'a HTTP (?P<status>\d+) is returned')
404 def check_http_return_status(context, status):
405     eq_(context.response.errorcode, int(status))
406
407 @then(u'the result is valid (?P<fmt>\w+)')
408 def step_impl(context, fmt):
409     context.execute_steps("Then a HTTP 200 is returned")
410     eq_(context.response.format, fmt)
411
412 @then(u'result header contains')
413 def check_header_attr(context):
414     for line in context.table:
415         assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
416                      "attribute '%s': expected: '%s', got '%s'"
417                        % (line['attr'], line['value'],
418                           context.response.header[line['attr']]))
419
420 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
421 def check_header_no_attr(context, neg, attrs):
422     for attr in attrs.split(','):
423         if neg:
424             assert_not_in(attr, context.response.header)
425         else:
426             assert_in(attr, context.response.header)
427
428 @then(u'results contain')
429 def step_impl(context):
430     context.execute_steps("then at least 1 result is returned")
431
432     for line in context.table:
433         context.response.match_row(line)
434
435 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
436 def validate_attributes(context, lid, neg, attrs):
437     if lid is None:
438         idx = range(len(context.response.result))
439         context.execute_steps("then at least 1 result is returned")
440     else:
441         idx = [int(lid.strip())]
442         context.execute_steps("then more than %sresults are returned" % lid)
443
444     for i in idx:
445         for attr in attrs.split(','):
446             if neg:
447                 assert_not_in(attr, context.response.result[i])
448             else:
449                 assert_in(attr, context.response.result[i])
450
451 @then(u'result addresses contain')
452 def step_impl(context):
453     context.execute_steps("then at least 1 result is returned")
454
455     if 'ID' not in context.table.headings:
456         addr_parts = context.response.property_list('address')
457
458     for line in context.table:
459         if 'ID' in context.table.headings:
460             addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
461
462         for h in context.table.headings:
463             if h != 'ID':
464                 for p in addr_parts:
465                     assert_in(h, p)
466                     assert_equal(p[h], line[h], "Bad address value for %s" % h)
467
468 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
469 def check_address(context, lid, neg, attrs):
470     context.execute_steps("then more than %s results are returned" % lid)
471
472     addr_parts = context.response.result[int(lid)]['address']
473
474     for attr in attrs.split(','):
475         if neg:
476             assert_not_in(attr, addr_parts)
477         else:
478             assert_in(attr, addr_parts)
479
480 @then(u'address of result (?P<lid>\d+) is')
481 def check_address(context, lid):
482     context.execute_steps("then more than %s results are returned" % lid)
483
484     addr_parts = dict(context.response.result[int(lid)]['address'])
485
486     for line in context.table:
487         assert_in(line['type'], addr_parts)
488         assert_equal(addr_parts[line['type']], line['value'],
489                      "Bad address value for %s" % line['type'])
490         del addr_parts[line['type']]
491
492     eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
493
494 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
495 def step_impl(context, lid, coords):
496     if lid is None:
497         context.execute_steps("then at least 1 result is returned")
498         bboxes = context.response.property_list('boundingbox')
499     else:
500         context.execute_steps("then more than %sresults are returned" % lid)
501         bboxes = [ context.response.result[int(lid)]['boundingbox']]
502
503     coord = [ float(x) for x in coords.split(',') ]
504
505     for bbox in bboxes:
506         if isinstance(bbox, str):
507             bbox = bbox.split(',')
508         bbox = [ float(x) for x in bbox ]
509
510         assert_greater_equal(bbox[0], coord[0])
511         assert_less_equal(bbox[1], coord[1])
512         assert_greater_equal(bbox[2], coord[2])
513         assert_less_equal(bbox[3], coord[3])
514
515 @then(u'there are(?P<neg> no)? duplicates')
516 def check_for_duplicates(context, neg):
517     context.execute_steps("then at least 1 result is returned")
518
519     resarr = set()
520     has_dupe = False
521
522     for res in context.response.result:
523         dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
524         if dup in resarr:
525             has_dupe = True
526             break
527         resarr.add(dup)
528
529     if neg:
530         assert not has_dupe, "Found duplicate for %s" % (dup, )
531     else:
532         assert has_dupe, "No duplicates found"