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