]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/queries.py
d0cda77469bab1559260e3af3b6f3529ffdfa775
[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 from tidylib import tidy_document
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 BASE_SERVER_ENV = {
19     'HTTP_HOST' : 'localhost',
20     'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
21     'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
22     'HTTP_ACCEPT_LANGUAGE' : 'en,de;q=0.5',
23     'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
24     'HTTP_CONNECTION' : 'keep-alive',
25     'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
26     'SERVER_SOFTWARE' : 'Nominatim test',
27     'SERVER_NAME' : 'localhost',
28     'SERVER_ADDR' : '127.0.1.1',
29     'SERVER_PORT' : '80',
30     'REMOTE_ADDR' : '127.0.0.1',
31     'DOCUMENT_ROOT' : '/var/www',
32     'REQUEST_SCHEME' : 'http',
33     'CONTEXT_PREFIX' : '/',
34     'SERVER_ADMIN' : 'webmaster@localhost',
35     'REMOTE_PORT' : '49319',
36     'GATEWAY_INTERFACE' : 'CGI/1.1',
37     'SERVER_PROTOCOL' : 'HTTP/1.1',
38     'REQUEST_METHOD' : 'GET',
39     'REDIRECT_STATUS' : 'CGI'
40 }
41
42
43 def compare(operator, op1, op2):
44     if operator == 'less than':
45         return op1 < op2
46     elif operator == 'more than':
47         return op1 > op2
48     elif operator == 'exactly':
49         return op1 == op2
50     elif operator == 'at least':
51         return op1 >= op2
52     elif operator == 'at most':
53         return op1 <= op2
54     else:
55         raise Exception("unknown operator '%s'" % operator)
56
57
58 class SearchResponse(object):
59
60     def __init__(self, page, fmt='json', errorcode=200):
61         self.page = page
62         self.format = fmt
63         self.errorcode = errorcode
64         self.result = []
65         self.header = dict()
66
67         if errorcode == 200:
68             getattr(self, 'parse_' + fmt)()
69
70     def parse_json(self):
71         m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
72         if m is None:
73             code = self.page
74         else:
75             code = m.group(2)
76             self.header['json_func'] = m.group(1)
77         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
78
79     def parse_html(self):
80         content, errors = tidy_document(self.page,
81                                         options={'char-encoding' : 'utf8'})
82         #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
83
84         b = content.find('nominatim_results =')
85         e = content.find('</script>')
86         content = content[b:e]
87         b = content.find('[')
88         e = content.rfind(']')
89
90         self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
91
92     def parse_xml(self):
93         et = ET.fromstring(self.page)
94
95         self.header = dict(et.attrib)
96
97         for child in et:
98             assert_equal(child.tag, "place")
99             self.result.append(dict(child.attrib))
100
101             address = {}
102             for sub in child:
103                 if sub.tag == 'extratags':
104                     self.result[-1]['extratags'] = {}
105                     for tag in sub:
106                         self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
107                 elif sub.tag == 'namedetails':
108                     self.result[-1]['namedetails'] = {}
109                     for tag in sub:
110                         self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
111                 elif sub.tag in ('geokml'):
112                     self.result[-1][sub.tag] = True
113                 else:
114                     address[sub.tag] = sub.text
115
116             if len(address) > 0:
117                 self.result[-1]['address'] = address
118
119
120     def match_row(self, row):
121         if 'ID' in row.headings:
122             todo = [int(row['ID'])]
123         else:
124             todo = range(len(self.result))
125
126         for i in todo:
127             res = self.result[i]
128             for h in row.headings:
129                 if h == 'ID':
130                     pass
131                 elif h == 'osm':
132                     assert_equal(res['osm_type'], row[h][0])
133                     assert_equal(res['osm_id'], row[h][1:])
134                 elif h == 'centroid':
135                     x, y = row[h].split(' ')
136                     assert_almost_equal(float(y), float(res['lat']))
137                     assert_almost_equal(float(x), float(res['lon']))
138                 elif row[h].startswith("^"):
139                     assert_in(h, res)
140                     assert_is_not_none(re.fullmatch(row[h], res[h]),
141                                        "attribute '%s': expected: '%s', got '%s'"
142                                           % (h, row[h], res[h]))
143                 else:
144                     assert_in(h, res)
145                     assert_equal(str(res[h]), str(row[h]))
146
147     def property_list(self, prop):
148         return [ x[prop] for x in self.result ]
149
150
151 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
152 def query_cmd(context, query, dups):
153     """ Query directly via PHP script.
154     """
155     cmd = [os.path.join(context.nominatim.build_dir, 'utils', 'query.php'),
156            '--search', query]
157     # add more parameters in table form
158     if context.table:
159         for h in context.table.headings:
160             value = context.table[0][h].strip()
161             if value:
162                 cmd.extend(('--' + h, value))
163
164     if dups:
165         cmd.extend(('--dedupe', '0'))
166
167     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
168                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
169     (outp, err) = proc.communicate()
170
171     assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
172
173     context.response = SearchResponse(outp.decode('utf-8'), 'json')
174
175
176 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
177 def website_search_request(context, fmt, query, addr):
178     env = BASE_SERVER_ENV
179
180     params = { 'q' : query }
181     if fmt is not None:
182         params['format'] = fmt.strip()
183     if addr is not None:
184         params['addressdetails'] = '1'
185     if context.table:
186         if context.table.headings[0] == 'param':
187             for line in context.table:
188                 params[line['param']] = line['value']
189         else:
190             for h in context.table.headings:
191                 params[h] = context.table[0][h]
192     env['QUERY_STRING'] = urlencode(params)
193
194     env['REQUEST_URI'] = '/search.php?' + env['QUERY_STRING']
195     env['SCRIPT_NAME'] = '/search.php'
196     env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
197     env['SCRIPT_FILENAME'] = os.path.join(context.nominatim.build_dir, 'website', 'search.php')
198     env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
199
200     cmd = [ '/usr/bin/php-cgi', env['SCRIPT_FILENAME']]
201     for k,v in params.items():
202         cmd.append("%s=%s" % (k, v))
203
204     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
205                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
206
207     (outp, err) = proc.communicate()
208
209     assert_equals(0, proc.returncode,
210                   "query.php failed with message: %s\noutput: %s" % (err, outp))
211
212     assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
213
214     outp = outp.decode('utf-8')
215
216     if outp.startswith('Status: '):
217         status = int(outp[8:11])
218     else:
219         status = 200
220
221     content_start = outp.find('\r\n\r\n')
222     assert_less(11, content_start)
223
224     if fmt is None:
225         outfmt = 'html'
226     elif fmt == 'jsonv2 ':
227         outfmt = 'json'
228     else:
229         outfmt = fmt.strip()
230
231     context.response = SearchResponse(outp[content_start + 4:], outfmt, status)
232
233
234 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
235 def validate_result_number(context, operator, number):
236     eq_(context.response.errorcode, 200)
237     numres = len(context.response.result)
238     ok_(compare(operator, numres, int(number)),
239         "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
240
241 @then(u'a HTTP (?P<status>\d+) is returned')
242 def check_http_return_status(context, status):
243     eq_(context.response.errorcode, int(status))
244
245 @then(u'the result is valid (?P<fmt>\w+)')
246 def step_impl(context, fmt):
247     eq_(context.response.format, fmt)
248
249 @then(u'result header contains')
250 def check_header_attr(context):
251     for line in context.table:
252         assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
253                      "attribute '%s': expected: '%s', got '%s'"
254                        % (line['attr'], line['value'],
255                           context.response.header[line['attr']]))
256
257 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
258 def check_header_no_attr(context, neg, attrs):
259     for attr in attrs.split(','):
260         if neg:
261             assert_not_in(attr, context.response.header)
262         else:
263             assert_in(attr, context.response.header)
264
265 @then(u'results contain')
266 def step_impl(context):
267     context.execute_steps("then at least 1 result is returned")
268
269     for line in context.table:
270         context.response.match_row(line)
271
272 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
273 def validate_attributes(context, lid, neg, attrs):
274     if lid is None:
275         idx = range(len(context.response.result))
276         context.execute_steps("then at least 1 result is returned")
277     else:
278         idx = [int(lid.strip())]
279         context.execute_steps("then more than %sresults are returned" % lid)
280
281     for i in idx:
282         for attr in attrs.split(','):
283             if neg:
284                 assert_not_in(attr, context.response.result[i])
285             else:
286                 assert_in(attr, context.response.result[i])
287
288 @then(u'result addresses contain')
289 def step_impl(context):
290     context.execute_steps("then at least 1 result is returned")
291
292     if 'ID' not in context.table.headings:
293         addr_parts = context.response.property_list('address')
294
295     for line in context.table:
296         if 'ID' in context.table.headings:
297             addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
298
299         for h in context.table.headings:
300             if h != 'ID':
301                 for p in addr_parts:
302                     assert_in(h, p)
303                     assert_equal(p[h], line[h], "Bad address value for %s" % h)
304
305 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
306 def check_address(context, lid, neg, attrs):
307     context.execute_steps("then more than %s results are returned" % lid)
308
309     addr_parts = context.response.result[int(lid)]['address']
310
311     for attr in attrs.split(','):
312         if neg:
313             assert_not_in(attr, addr_parts)
314         else:
315             assert_in(attr, addr_parts)
316
317 @then(u'address of result (?P<lid>\d+) is')
318 def check_address(context, lid):
319     context.execute_steps("then more than %s results are returned" % lid)
320
321     addr_parts = dict(context.response.result[int(lid)]['address'])
322
323     for line in context.table:
324         assert_in(line['type'], addr_parts)
325         assert_equal(addr_parts[line['type']], line['value'],
326                      "Bad address value for %s" % line['type'])
327         del addr_parts[line['type']]
328
329     eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
330
331 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
332 def step_impl(context, lid, coords):
333     if lid is None:
334         context.execute_steps("then at least 1 result is returned")
335         bboxes = context.response.property_list('boundingbox')
336     else:
337         context.execute_steps("then more than %sresults are returned" % lid)
338         bboxes = [ context.response.result[int(lid)]['boundingbox']]
339
340     coord = [ float(x) for x in coords.split(',') ]
341
342     for bbox in bboxes:
343         if isinstance(bbox, str):
344             bbox = bbox.split(',')
345         bbox = [ float(x) for x in bbox ]
346
347         assert_greater_equal(bbox[0], coord[0])
348         assert_less_equal(bbox[1], coord[1])
349         assert_greater_equal(bbox[2], coord[2])
350         assert_less_equal(bbox[3], coord[3])
351
352 @then(u'there are(?P<neg> no)? duplicates')
353 def check_for_duplicates(context, neg):
354     context.execute_steps("then at least 1 result is returned")
355
356     resarr = set()
357     has_dupe = False
358
359     for res in context.response.result:
360         dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
361         if dup in resarr:
362             has_dupe = True
363             break
364         resarr.add(dup)
365
366     if neg:
367         assert not has_dupe, "Found duplicate for %s" % (dup, )
368     else:
369         assert has_dupe, "No duplicates found"