]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/steps_api_queries.py
bdd: directly call utility scripts in lib
[nominatim.git] / test / bdd / steps / steps_api_queries.py
1 """ Steps that run queries against the API.
2
3     Queries may either be run directly via PHP using the query script
4     or via the HTTP interface using php-cgi.
5 """
6 import json
7 import os
8 import re
9 import logging
10 from urllib.parse import urlencode
11
12 from utils import run_script
13 from http_responses import GenericResponse, SearchResponse, ReverseResponse, StatusResponse
14 from check_functions import Bbox
15
16 LOG = logging.getLogger(__name__)
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_ENCODING' : 'gzip, deflate',
23     'HTTP_CONNECTION' : 'keep-alive',
24     'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
25     'SERVER_SOFTWARE' : 'Nominatim test',
26     'SERVER_NAME' : 'localhost',
27     'SERVER_ADDR' : '127.0.1.1',
28     'SERVER_PORT' : '80',
29     'REMOTE_ADDR' : '127.0.0.1',
30     'DOCUMENT_ROOT' : '/var/www',
31     'REQUEST_SCHEME' : 'http',
32     'CONTEXT_PREFIX' : '/',
33     'SERVER_ADMIN' : 'webmaster@localhost',
34     'REMOTE_PORT' : '49319',
35     'GATEWAY_INTERFACE' : 'CGI/1.1',
36     'SERVER_PROTOCOL' : 'HTTP/1.1',
37     'REQUEST_METHOD' : 'GET',
38     'REDIRECT_STATUS' : 'CGI'
39 }
40
41
42 def compare(operator, op1, op2):
43     if operator == 'less than':
44         return op1 < op2
45     elif operator == 'more than':
46         return op1 > op2
47     elif operator == 'exactly':
48         return op1 == op2
49     elif operator == 'at least':
50         return op1 >= op2
51     elif operator == 'at most':
52         return op1 <= op2
53     else:
54         raise Exception("unknown operator '%s'" % operator)
55
56
57 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
58 def query_cmd(context, query, dups):
59     """ Query directly via PHP script.
60     """
61     cmd = ['/usr/bin/env', 'php']
62     cmd.append(context.nominatim.src_dir  / 'lib' / 'admin' / 'query.php')
63     if query:
64         cmd.extend(['--search', query])
65     # add more parameters in table form
66     if context.table:
67         for h in context.table.headings:
68             value = context.table[0][h].strip()
69             if value:
70                 cmd.extend(('--' + h, value))
71
72     if dups:
73         cmd.extend(('--dedupe', '0'))
74
75     outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name,
76                            env=context.nominatim.test_env)
77
78     context.response = SearchResponse(outp, 'json')
79
80 def send_api_query(endpoint, params, fmt, context):
81     if fmt is not None:
82         params['format'] = fmt.strip()
83     if context.table:
84         if context.table.headings[0] == 'param':
85             for line in context.table:
86                 params[line['param']] = line['value']
87         else:
88             for h in context.table.headings:
89                 params[h] = context.table[0][h]
90
91     env = dict(BASE_SERVER_ENV)
92     env['QUERY_STRING'] = urlencode(params)
93
94     env['SCRIPT_NAME'] = '/%s.php' % endpoint
95     env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
96     env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.website_dir.name, 'website')
97     env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
98                                           '%s.php' % endpoint)
99
100     LOG.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
101
102     if hasattr(context, 'http_headers'):
103         env.update(context.http_headers)
104
105     cmd = ['/usr/bin/env', 'php-cgi', '-f']
106     if context.nominatim.code_coverage_path:
107         env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
108         env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
109         env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
110         env['SCRIPT_FILENAME'] = \
111                 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
112         cmd.append(env['SCRIPT_FILENAME'])
113         env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
114     else:
115         cmd.append(env['SCRIPT_FILENAME'])
116
117     for k,v in params.items():
118         cmd.append("%s=%s" % (k, v))
119
120     outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
121
122     assert len(err) == 0, "Unexpected PHP error: %s" % (err)
123
124     if outp.startswith('Status: '):
125         status = int(outp[8:11])
126     else:
127         status = 200
128
129     content_start = outp.find('\r\n\r\n')
130
131     return outp[content_start + 4:], status
132
133 @given(u'the HTTP header')
134 def add_http_header(context):
135     if not hasattr(context, 'http_headers'):
136         context.http_headers = {}
137
138     for h in context.table.headings:
139         envvar = 'HTTP_' + h.upper().replace('-', '_')
140         context.http_headers[envvar] = context.table[0][h]
141
142
143 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
144 def website_search_request(context, fmt, query, addr):
145     params = {}
146     if query:
147         params['q'] = query
148     if addr is not None:
149         params['addressdetails'] = '1'
150
151     outp, status = send_api_query('search', params, fmt, context)
152
153     context.response = SearchResponse(outp, fmt or 'json', status)
154
155 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
156 def website_reverse_request(context, fmt, lat, lon):
157     params = {}
158     if lat is not None:
159         params['lat'] = lat
160     if lon is not None:
161         params['lon'] = lon
162
163     outp, status = send_api_query('reverse', params, fmt, context)
164
165     context.response = ReverseResponse(outp, fmt or 'xml', status)
166
167 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
168 def website_details_request(context, fmt, query):
169     params = {}
170     if query[0] in 'NWR':
171         params['osmtype'] = query[0]
172         params['osmid'] = query[1:]
173     else:
174         params['place_id'] = query
175     outp, status = send_api_query('details', params, fmt, context)
176
177     context.response = GenericResponse(outp, fmt or 'json', status)
178
179 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
180 def website_lookup_request(context, fmt, query):
181     params = { 'osm_ids' : query }
182     outp, status = send_api_query('lookup', params, fmt, context)
183
184     context.response = SearchResponse(outp, fmt or 'xml', status)
185
186 @when(u'sending (?P<fmt>\S+ )?status query')
187 def website_status_request(context, fmt):
188     params = {}
189     outp, status = send_api_query('status', params, fmt, context)
190
191     context.response = StatusResponse(outp, fmt or 'text', status)
192
193 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
194 def validate_result_number(context, operator, number):
195     assert context.response.errorcode == 200
196     numres = len(context.response.result)
197     assert compare(operator, numres, int(number)), \
198         "Bad number of results: expected {} {}, got {}.".format(operator, number, numres)
199
200 @then(u'a HTTP (?P<status>\d+) is returned')
201 def check_http_return_status(context, status):
202     assert context.response.errorcode == int(status)
203
204 @then(u'the page contents equals "(?P<text>.+)"')
205 def check_page_content_equals(context, text):
206     assert context.response.page == text
207
208 @then(u'the result is valid (?P<fmt>\w+)')
209 def step_impl(context, fmt):
210     context.execute_steps("Then a HTTP 200 is returned")
211     assert context.response.format == fmt
212
213 @then(u'a (?P<fmt>\w+) user error is returned')
214 def check_page_error(context, fmt):
215     context.execute_steps("Then a HTTP 400 is returned")
216     assert context.response.format == fmt
217
218     if fmt == 'xml':
219         assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
220     else:
221         assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
222
223 @then(u'result header contains')
224 def check_header_attr(context):
225     for line in context.table:
226         assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
227                "attribute '%s': expected: '%s', got '%s'" % (
228                     line['attr'], line['value'],
229                     context.response.header[line['attr']])
230
231 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
232 def check_header_no_attr(context, neg, attrs):
233     for attr in attrs.split(','):
234         if neg:
235             assert attr not in context.response.header
236         else:
237             assert attr in context.response.header
238
239 @then(u'results contain')
240 def step_impl(context):
241     context.execute_steps("then at least 1 result is returned")
242
243     for line in context.table:
244         context.response.match_row(line)
245
246 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
247 def validate_attributes(context, lid, neg, attrs):
248     if lid is None:
249         idx = range(len(context.response.result))
250         context.execute_steps("then at least 1 result is returned")
251     else:
252         idx = [int(lid.strip())]
253         context.execute_steps("then more than %sresults are returned" % lid)
254
255     for i in idx:
256         for attr in attrs.split(','):
257             if neg:
258                 assert attr not in context.response.result[i]
259             else:
260                 assert attr in context.response.result[i]
261
262 @then(u'result addresses contain')
263 def step_impl(context):
264     context.execute_steps("then at least 1 result is returned")
265
266     for line in context.table:
267         idx = int(line['ID']) if 'ID' in line.headings else None
268
269         for name, value in zip(line.headings, line.cells):
270             if name != 'ID':
271                 context.response.assert_address_field(idx, name, value)
272
273 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
274 def check_address(context, lid, neg, attrs):
275     context.execute_steps("then more than %s results are returned" % lid)
276
277     addr_parts = context.response.result[int(lid)]['address']
278
279     for attr in attrs.split(','):
280         if neg:
281             assert attr not in addr_parts
282         else:
283             assert attr in addr_parts
284
285 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
286 def check_address(context, lid, complete):
287     context.execute_steps("then more than %s results are returned" % lid)
288
289     lid = int(lid)
290     addr_parts = dict(context.response.result[lid]['address'])
291
292     for line in context.table:
293         context.response.assert_address_field(lid, line['type'], line['value'])
294         del addr_parts[line['type']]
295
296     if complete == 'is':
297         assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
298
299 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
300 def step_impl(context, lid, coords):
301     if lid is None:
302         context.execute_steps("then at least 1 result is returned")
303         bboxes = context.response.property_list('boundingbox')
304     else:
305         context.execute_steps("then more than {}results are returned".format(lid))
306         bboxes = [context.response.result[int(lid)]['boundingbox']]
307
308     expected = Bbox(coords)
309
310     for bbox in bboxes:
311         assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
312
313 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
314 def step_impl(context, lid, coords):
315     if lid is None:
316         context.execute_steps("then at least 1 result is returned")
317         centroids = zip(context.response.property_list('lon'),
318                         context.response.property_list('lat'))
319     else:
320         context.execute_steps("then more than %sresults are returned".format(lid))
321         res = context.response.result[int(lid)]
322         centroids = [(res['lon'], res['lat'])]
323
324     expected = Bbox(coords)
325
326     for centroid in centroids:
327         assert centroid in expected,\
328                "Centroid {} is not inside {}.".format(centroid, expected)
329
330 @then(u'there are(?P<neg> no)? duplicates')
331 def check_for_duplicates(context, neg):
332     context.execute_steps("then at least 1 result is returned")
333
334     resarr = set()
335     has_dupe = False
336
337     for res in context.response.result:
338         dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
339         if dup in resarr:
340             has_dupe = True
341             break
342         resarr.add(dup)
343
344     if neg:
345         assert not has_dupe, "Found duplicate for %s" % (dup, )
346     else:
347         assert has_dupe, "No duplicates found"