]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/queries.py
b02a6661b7ce46f1e2aeec141f227375ce58d7f4
[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 = {}
181     if query:
182         params['q'] = query
183     if fmt is not None:
184         params['format'] = fmt.strip()
185     if addr is not None:
186         params['addressdetails'] = '1'
187     if context.table:
188         if context.table.headings[0] == 'param':
189             for line in context.table:
190                 params[line['param']] = line['value']
191         else:
192             for h in context.table.headings:
193                 params[h] = context.table[0][h]
194     env['QUERY_STRING'] = urlencode(params)
195
196     env['REQUEST_URI'] = '/search.php?' + env['QUERY_STRING']
197     env['SCRIPT_NAME'] = '/search.php'
198     env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
199     env['SCRIPT_FILENAME'] = os.path.join(context.nominatim.build_dir, 'website', 'search.php')
200     env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
201
202     cmd = [ '/usr/bin/php-cgi', env['SCRIPT_FILENAME']]
203     for k,v in params.items():
204         cmd.append("%s=%s" % (k, v))
205
206     proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
207                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
208
209     (outp, err) = proc.communicate()
210
211     assert_equals(0, proc.returncode,
212                   "query.php failed with message: %s\noutput: %s" % (err, outp))
213
214     assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
215
216     outp = outp.decode('utf-8')
217
218     if outp.startswith('Status: '):
219         status = int(outp[8:11])
220     else:
221         status = 200
222
223     content_start = outp.find('\r\n\r\n')
224     assert_less(11, content_start)
225
226     if fmt is None:
227         outfmt = 'html'
228     elif fmt == 'jsonv2 ':
229         outfmt = 'json'
230     else:
231         outfmt = fmt.strip()
232
233     context.response = SearchResponse(outp[content_start + 4:], outfmt, status)
234
235
236 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
237 def validate_result_number(context, operator, number):
238     eq_(context.response.errorcode, 200)
239     numres = len(context.response.result)
240     ok_(compare(operator, numres, int(number)),
241         "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
242
243 @then(u'a HTTP (?P<status>\d+) is returned')
244 def check_http_return_status(context, status):
245     eq_(context.response.errorcode, int(status))
246
247 @then(u'the result is valid (?P<fmt>\w+)')
248 def step_impl(context, fmt):
249     eq_(context.response.format, fmt)
250
251 @then(u'result header contains')
252 def check_header_attr(context):
253     for line in context.table:
254         assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
255                      "attribute '%s': expected: '%s', got '%s'"
256                        % (line['attr'], line['value'],
257                           context.response.header[line['attr']]))
258
259 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
260 def check_header_no_attr(context, neg, attrs):
261     for attr in attrs.split(','):
262         if neg:
263             assert_not_in(attr, context.response.header)
264         else:
265             assert_in(attr, context.response.header)
266
267 @then(u'results contain')
268 def step_impl(context):
269     context.execute_steps("then at least 1 result is returned")
270
271     for line in context.table:
272         context.response.match_row(line)
273
274 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
275 def validate_attributes(context, lid, neg, attrs):
276     if lid is None:
277         idx = range(len(context.response.result))
278         context.execute_steps("then at least 1 result is returned")
279     else:
280         idx = [int(lid.strip())]
281         context.execute_steps("then more than %sresults are returned" % lid)
282
283     for i in idx:
284         for attr in attrs.split(','):
285             if neg:
286                 assert_not_in(attr, context.response.result[i])
287             else:
288                 assert_in(attr, context.response.result[i])
289
290 @then(u'result addresses contain')
291 def step_impl(context):
292     context.execute_steps("then at least 1 result is returned")
293
294     if 'ID' not in context.table.headings:
295         addr_parts = context.response.property_list('address')
296
297     for line in context.table:
298         if 'ID' in context.table.headings:
299             addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
300
301         for h in context.table.headings:
302             if h != 'ID':
303                 for p in addr_parts:
304                     assert_in(h, p)
305                     assert_equal(p[h], line[h], "Bad address value for %s" % h)
306
307 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
308 def check_address(context, lid, neg, attrs):
309     context.execute_steps("then more than %s results are returned" % lid)
310
311     addr_parts = context.response.result[int(lid)]['address']
312
313     for attr in attrs.split(','):
314         if neg:
315             assert_not_in(attr, addr_parts)
316         else:
317             assert_in(attr, addr_parts)
318
319 @then(u'address of result (?P<lid>\d+) is')
320 def check_address(context, lid):
321     context.execute_steps("then more than %s results are returned" % lid)
322
323     addr_parts = dict(context.response.result[int(lid)]['address'])
324
325     for line in context.table:
326         assert_in(line['type'], addr_parts)
327         assert_equal(addr_parts[line['type']], line['value'],
328                      "Bad address value for %s" % line['type'])
329         del addr_parts[line['type']]
330
331     eq_(0, len(addr_parts), "Additional address parts found: %s" % str(addr_parts))
332
333 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
334 def step_impl(context, lid, coords):
335     if lid is None:
336         context.execute_steps("then at least 1 result is returned")
337         bboxes = context.response.property_list('boundingbox')
338     else:
339         context.execute_steps("then more than %sresults are returned" % lid)
340         bboxes = [ context.response.result[int(lid)]['boundingbox']]
341
342     coord = [ float(x) for x in coords.split(',') ]
343
344     for bbox in bboxes:
345         if isinstance(bbox, str):
346             bbox = bbox.split(',')
347         bbox = [ float(x) for x in bbox ]
348
349         assert_greater_equal(bbox[0], coord[0])
350         assert_less_equal(bbox[1], coord[1])
351         assert_greater_equal(bbox[2], coord[2])
352         assert_less_equal(bbox[3], coord[3])
353
354 @then(u'there are(?P<neg> no)? duplicates')
355 def check_for_duplicates(context, neg):
356     context.execute_steps("then at least 1 result is returned")
357
358     resarr = set()
359     has_dupe = False
360
361     for res in context.response.result:
362         dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
363         if dup in resarr:
364             has_dupe = True
365             break
366         resarr.add(dup)
367
368     if neg:
369         assert not has_dupe, "Found duplicate for %s" % (dup, )
370     else:
371         assert has_dupe, "No duplicates found"