]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/steps_api_queries.py
Merge pull request #2132 from lonvia/reduce-api-testdb
[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(os.path.join(context.nominatim.build_dir, 'utils', '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.build_dir)
76
77     context.response = SearchResponse(outp, 'json')
78
79 def send_api_query(endpoint, params, fmt, context):
80     if fmt is not None:
81         params['format'] = fmt.strip()
82     if context.table:
83         if context.table.headings[0] == 'param':
84             for line in context.table:
85                 params[line['param']] = line['value']
86         else:
87             for h in context.table.headings:
88                 params[h] = context.table[0][h]
89
90     env = dict(BASE_SERVER_ENV)
91     env['QUERY_STRING'] = urlencode(params)
92
93     env['SCRIPT_NAME'] = '/%s.php' % endpoint
94     env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
95     env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.website_dir.name, 'website')
96     env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
97                                           '%s.php' % endpoint)
98
99     LOG.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
100
101     if hasattr(context, 'http_headers'):
102         env.update(context.http_headers)
103
104     cmd = ['/usr/bin/env', 'php-cgi', '-f']
105     if context.nominatim.code_coverage_path:
106         env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
107         env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
108         env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
109         env['SCRIPT_FILENAME'] = \
110                 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
111         cmd.append(env['SCRIPT_FILENAME'])
112         env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
113     else:
114         cmd.append(env['SCRIPT_FILENAME'])
115
116     for k,v in params.items():
117         cmd.append("%s=%s" % (k, v))
118
119     outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
120
121     assert len(err) == 0, "Unexpected PHP error: %s" % (err)
122
123     if outp.startswith('Status: '):
124         status = int(outp[8:11])
125     else:
126         status = 200
127
128     content_start = outp.find('\r\n\r\n')
129
130     return outp[content_start + 4:], status
131
132 @given(u'the HTTP header')
133 def add_http_header(context):
134     if not hasattr(context, 'http_headers'):
135         context.http_headers = {}
136
137     for h in context.table.headings:
138         envvar = 'HTTP_' + h.upper().replace('-', '_')
139         context.http_headers[envvar] = context.table[0][h]
140
141
142 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
143 def website_search_request(context, fmt, query, addr):
144     params = {}
145     if query:
146         params['q'] = query
147     if addr is not None:
148         params['addressdetails'] = '1'
149
150     outp, status = send_api_query('search', params, fmt, context)
151
152     context.response = SearchResponse(outp, fmt or 'json', status)
153
154 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
155 def website_reverse_request(context, fmt, lat, lon):
156     params = {}
157     if lat is not None:
158         params['lat'] = lat
159     if lon is not None:
160         params['lon'] = lon
161
162     outp, status = send_api_query('reverse', params, fmt, context)
163
164     context.response = ReverseResponse(outp, fmt or 'xml', status)
165
166 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
167 def website_details_request(context, fmt, query):
168     params = {}
169     if query[0] in 'NWR':
170         params['osmtype'] = query[0]
171         params['osmid'] = query[1:]
172     else:
173         params['place_id'] = query
174     outp, status = send_api_query('details', params, fmt, context)
175
176     context.response = GenericResponse(outp, fmt or 'json', status)
177
178 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
179 def website_lookup_request(context, fmt, query):
180     params = { 'osm_ids' : query }
181     outp, status = send_api_query('lookup', params, fmt, context)
182
183     context.response = SearchResponse(outp, fmt or 'xml', status)
184
185 @when(u'sending (?P<fmt>\S+ )?status query')
186 def website_status_request(context, fmt):
187     params = {}
188     outp, status = send_api_query('status', params, fmt, context)
189
190     context.response = StatusResponse(outp, fmt or 'text', status)
191
192 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
193 def validate_result_number(context, operator, number):
194     assert context.response.errorcode == 200
195     numres = len(context.response.result)
196     assert compare(operator, numres, int(number)), \
197         "Bad number of results: expected {} {}, got {}.".format(operator, number, numres)
198
199 @then(u'a HTTP (?P<status>\d+) is returned')
200 def check_http_return_status(context, status):
201     assert context.response.errorcode == int(status)
202
203 @then(u'the page contents equals "(?P<text>.+)"')
204 def check_page_content_equals(context, text):
205     assert context.response.page == text
206
207 @then(u'the result is valid (?P<fmt>\w+)')
208 def step_impl(context, fmt):
209     context.execute_steps("Then a HTTP 200 is returned")
210     assert context.response.format == fmt
211
212 @then(u'a (?P<fmt>\w+) user error is returned')
213 def check_page_error(context, fmt):
214     context.execute_steps("Then a HTTP 400 is returned")
215     assert context.response.format == fmt
216
217     if fmt == 'xml':
218         assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
219     else:
220         assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
221
222 @then(u'result header contains')
223 def check_header_attr(context):
224     for line in context.table:
225         assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
226                "attribute '%s': expected: '%s', got '%s'" % (
227                     line['attr'], line['value'],
228                     context.response.header[line['attr']])
229
230 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
231 def check_header_no_attr(context, neg, attrs):
232     for attr in attrs.split(','):
233         if neg:
234             assert attr not in context.response.header
235         else:
236             assert attr in context.response.header
237
238 @then(u'results contain')
239 def step_impl(context):
240     context.execute_steps("then at least 1 result is returned")
241
242     for line in context.table:
243         context.response.match_row(line)
244
245 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
246 def validate_attributes(context, lid, neg, attrs):
247     if lid is None:
248         idx = range(len(context.response.result))
249         context.execute_steps("then at least 1 result is returned")
250     else:
251         idx = [int(lid.strip())]
252         context.execute_steps("then more than %sresults are returned" % lid)
253
254     for i in idx:
255         for attr in attrs.split(','):
256             if neg:
257                 assert attr not in context.response.result[i]
258             else:
259                 assert attr in context.response.result[i]
260
261 @then(u'result addresses contain')
262 def step_impl(context):
263     context.execute_steps("then at least 1 result is returned")
264
265     for line in context.table:
266         idx = int(line['ID']) if 'ID' in line.headings else None
267
268         for name, value in zip(line.headings, line.cells):
269             if name != 'ID':
270                 context.response.assert_address_field(idx, name, value)
271
272 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
273 def check_address(context, lid, neg, attrs):
274     context.execute_steps("then more than %s results are returned" % lid)
275
276     addr_parts = context.response.result[int(lid)]['address']
277
278     for attr in attrs.split(','):
279         if neg:
280             assert attr not in addr_parts
281         else:
282             assert attr in addr_parts
283
284 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
285 def check_address(context, lid, complete):
286     context.execute_steps("then more than %s results are returned" % lid)
287
288     lid = int(lid)
289     addr_parts = dict(context.response.result[lid]['address'])
290
291     for line in context.table:
292         context.response.assert_address_field(lid, line['type'], line['value'])
293         del addr_parts[line['type']]
294
295     if complete == 'is':
296         assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
297
298 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
299 def step_impl(context, lid, coords):
300     if lid is None:
301         context.execute_steps("then at least 1 result is returned")
302         bboxes = context.response.property_list('boundingbox')
303     else:
304         context.execute_steps("then more than {}results are returned".format(lid))
305         bboxes = [context.response.result[int(lid)]['boundingbox']]
306
307     expected = Bbox(coords)
308
309     for bbox in bboxes:
310         assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
311
312 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
313 def step_impl(context, lid, coords):
314     if lid is None:
315         context.execute_steps("then at least 1 result is returned")
316         centroids = zip(context.response.property_list('lon'),
317                         context.response.property_list('lat'))
318     else:
319         context.execute_steps("then more than %sresults are returned".format(lid))
320         res = context.response.result[int(lid)]
321         centroids = [(res['lon'], res['lat'])]
322
323     expected = Bbox(coords)
324
325     for centroid in centroids:
326         assert centroid in expected,\
327                "Centroid {} is not inside {}.".format(centroid, expected)
328
329 @then(u'there are(?P<neg> no)? duplicates')
330 def check_for_duplicates(context, neg):
331     context.execute_steps("then at least 1 result is returned")
332
333     resarr = set()
334     has_dupe = False
335
336     for res in context.response.result:
337         dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
338         if dup in resarr:
339             has_dupe = True
340             break
341         resarr.add(dup)
342
343     if neg:
344         assert not has_dupe, "Found duplicate for %s" % (dup, )
345     else:
346         assert has_dupe, "No duplicates found"