1 """ Steps that run queries against the API.
3 Queries may either be run directly via PHP using the query script
4 or via the HTTP interface using php-cgi.
10 from urllib.parse import urlencode
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
17 LOG = logging.getLogger(__name__)
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',
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'
43 def compare(operator, op1, op2):
44 if operator == 'less than':
46 elif operator == 'more than':
48 elif operator == 'exactly':
50 elif operator == 'at least':
52 elif operator == 'at most':
55 raise Exception("unknown operator '%s'" % operator)
58 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
59 def query_cmd(context, query, dups):
60 """ Query directly via PHP script.
62 cmd = ['/usr/bin/env', 'php']
63 cmd.append(context.nominatim.src_dir / 'lib' / 'admin' / 'query.php')
65 cmd.extend(['--search', query])
66 # add more parameters in table form
68 for h in context.table.headings:
69 value = context.table[0][h].strip()
71 cmd.extend(('--' + h, value))
74 cmd.extend(('--dedupe', '0'))
76 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name,
77 env=context.nominatim.test_env)
79 context.response = SearchResponse(outp, 'json')
81 def send_api_query(endpoint, params, fmt, context):
83 params['format'] = fmt.strip()
85 if context.table.headings[0] == 'param':
86 for line in context.table:
87 params[line['param']] = line['value']
89 for h in context.table.headings:
90 params[h] = context.table[0][h]
92 env = dict(BASE_SERVER_ENV)
93 env['QUERY_STRING'] = urlencode(params)
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'],
101 LOG.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
103 if hasattr(context, 'http_headers'):
104 env.update(context.http_headers)
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()
116 cmd.append(env['SCRIPT_FILENAME'])
118 for k,v in params.items():
119 cmd.append("%s=%s" % (k, v))
121 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
123 assert len(err) == 0, "Unexpected PHP error: %s" % (err)
125 if outp.startswith('Status: '):
126 status = int(outp[8:11])
130 content_start = outp.find('\r\n\r\n')
132 return outp[content_start + 4:], status
134 @given(u'the HTTP header')
135 def add_http_header(context):
136 if not hasattr(context, 'http_headers'):
137 context.http_headers = {}
139 for h in context.table.headings:
140 envvar = 'HTTP_' + h.upper().replace('-', '_')
141 context.http_headers[envvar] = context.table[0][h]
144 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
145 def website_search_request(context, fmt, query, addr):
150 params['addressdetails'] = '1'
152 outp, status = send_api_query('search', params, fmt, context)
154 context.response = SearchResponse(outp, fmt or 'json', status)
156 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
157 def website_reverse_request(context, fmt, lat, lon):
164 outp, status = send_api_query('reverse', params, fmt, context)
166 context.response = ReverseResponse(outp, fmt or 'xml', status)
168 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
169 def website_details_request(context, fmt, query):
171 if query[0] in 'NWR':
172 nid = NominatimID(query)
173 params['osmtype'] = nid.typ
174 params['osmid'] = nid.oid
176 params['class'] = nid.cls
178 params['place_id'] = query
179 outp, status = send_api_query('details', params, fmt, context)
181 context.response = GenericResponse(outp, fmt or 'json', status)
183 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
184 def website_lookup_request(context, fmt, query):
185 params = { 'osm_ids' : query }
186 outp, status = send_api_query('lookup', params, fmt, context)
188 context.response = SearchResponse(outp, fmt or 'xml', status)
190 @when(u'sending (?P<fmt>\S+ )?status query')
191 def website_status_request(context, fmt):
193 outp, status = send_api_query('status', params, fmt, context)
195 context.response = StatusResponse(outp, fmt or 'text', status)
197 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
198 def validate_result_number(context, operator, number):
199 assert context.response.errorcode == 200
200 numres = len(context.response.result)
201 assert compare(operator, numres, int(number)), \
202 "Bad number of results: expected {} {}, got {}.".format(operator, number, numres)
204 @then(u'a HTTP (?P<status>\d+) is returned')
205 def check_http_return_status(context, status):
206 assert context.response.errorcode == int(status)
208 @then(u'the page contents equals "(?P<text>.+)"')
209 def check_page_content_equals(context, text):
210 assert context.response.page == text
212 @then(u'the result is valid (?P<fmt>\w+)')
213 def step_impl(context, fmt):
214 context.execute_steps("Then a HTTP 200 is returned")
215 assert context.response.format == fmt
217 @then(u'a (?P<fmt>\w+) user error is returned')
218 def check_page_error(context, fmt):
219 context.execute_steps("Then a HTTP 400 is returned")
220 assert context.response.format == fmt
223 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
225 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
227 @then(u'result header contains')
228 def check_header_attr(context):
229 for line in context.table:
230 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
231 "attribute '%s': expected: '%s', got '%s'" % (
232 line['attr'], line['value'],
233 context.response.header[line['attr']])
235 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
236 def check_header_no_attr(context, neg, attrs):
237 for attr in attrs.split(','):
239 assert attr not in context.response.header, \
240 "Unexpected attribute {}. Full response:\n{}".format(
241 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
243 assert attr in context.response.header, \
244 "No attribute {}. Full response:\n{}".format(
245 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
247 @then(u'results contain')
248 def step_impl(context):
249 context.execute_steps("then at least 1 result is returned")
251 for line in context.table:
252 context.response.match_row(line)
254 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
255 def validate_attributes(context, lid, neg, attrs):
257 idx = range(len(context.response.result))
258 context.execute_steps("then at least 1 result is returned")
260 idx = [int(lid.strip())]
261 context.execute_steps("then more than %sresults are returned" % lid)
264 for attr in attrs.split(','):
266 assert attr not in context.response.result[i],\
267 "Unexpected attribute {}. Full response:\n{}".format(
268 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
270 assert attr in context.response.result[i], \
271 "No attribute {}. Full response:\n{}".format(
272 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
274 @then(u'result addresses contain')
275 def step_impl(context):
276 context.execute_steps("then at least 1 result is returned")
278 for line in context.table:
279 idx = int(line['ID']) if 'ID' in line.headings else None
281 for name, value in zip(line.headings, line.cells):
283 context.response.assert_address_field(idx, name, value)
285 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
286 def check_address(context, lid, neg, attrs):
287 context.execute_steps("then more than %s results are returned" % lid)
289 addr_parts = context.response.result[int(lid)]['address']
291 for attr in attrs.split(','):
293 assert attr not in addr_parts
295 assert attr in addr_parts
297 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
298 def check_address(context, lid, complete):
299 context.execute_steps("then more than %s results are returned" % lid)
302 addr_parts = dict(context.response.result[lid]['address'])
304 for line in context.table:
305 context.response.assert_address_field(lid, line['type'], line['value'])
306 del addr_parts[line['type']]
309 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
311 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
312 def step_impl(context, lid, coords):
314 context.execute_steps("then at least 1 result is returned")
315 bboxes = context.response.property_list('boundingbox')
317 context.execute_steps("then more than {}results are returned".format(lid))
318 bboxes = [context.response.result[int(lid)]['boundingbox']]
320 expected = Bbox(coords)
323 assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
325 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
326 def step_impl(context, lid, coords):
328 context.execute_steps("then at least 1 result is returned")
329 centroids = zip(context.response.property_list('lon'),
330 context.response.property_list('lat'))
332 context.execute_steps("then more than %sresults are returned".format(lid))
333 res = context.response.result[int(lid)]
334 centroids = [(res['lon'], res['lat'])]
336 expected = Bbox(coords)
338 for centroid in centroids:
339 assert centroid in expected,\
340 "Centroid {} is not inside {}.".format(centroid, expected)
342 @then(u'there are(?P<neg> no)? duplicates')
343 def check_for_duplicates(context, neg):
344 context.execute_steps("then at least 1 result is returned")
349 for res in context.response.result:
350 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
357 assert not has_dupe, "Found duplicate for %s" % (dup, )
359 assert has_dupe, "No duplicates found"