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