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