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-php' / '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):
82 if fmt is not None and fmt.strip() != 'debug':
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'
151 if fmt and fmt.strip() == 'debug':
152 params['debug'] = '1'
154 outp, status = send_api_query('search', params, fmt, context)
156 context.response = SearchResponse(outp, fmt or 'json', status)
158 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
159 def website_reverse_request(context, fmt, lat, lon):
165 if fmt and fmt.strip() == 'debug':
166 params['debug'] = '1'
168 outp, status = send_api_query('reverse', params, fmt, context)
170 context.response = ReverseResponse(outp, fmt or 'xml', status)
172 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
173 def website_details_request(context, fmt, query):
175 if query[0] in 'NWR':
176 nid = NominatimID(query)
177 params['osmtype'] = nid.typ
178 params['osmid'] = nid.oid
180 params['class'] = nid.cls
182 params['place_id'] = query
183 outp, status = send_api_query('details', params, fmt, context)
185 context.response = GenericResponse(outp, fmt or 'json', status)
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)
192 context.response = SearchResponse(outp, fmt or 'xml', status)
194 @when(u'sending (?P<fmt>\S+ )?status query')
195 def website_status_request(context, fmt):
197 outp, status = send_api_query('status', params, fmt, context)
199 context.response = StatusResponse(outp, fmt or 'text', status)
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)
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)
213 @then(u'the page contents equals "(?P<text>.+)"')
214 def check_page_content_equals(context, text):
215 assert context.response.page == text
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
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
228 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
230 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
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']])
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(','):
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))
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))
252 @then(u'results contain')
253 def step_impl(context):
254 context.execute_steps("then at least 1 result is returned")
256 for line in context.table:
257 context.response.match_row(line)
259 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
260 def validate_attributes(context, lid, neg, attrs):
262 idx = range(len(context.response.result))
263 context.execute_steps("then at least 1 result is returned")
265 idx = [int(lid.strip())]
266 context.execute_steps("then more than %sresults are returned" % lid)
269 for attr in attrs.split(','):
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))
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))
279 @then(u'result addresses contain')
280 def step_impl(context):
281 context.execute_steps("then at least 1 result is returned")
283 for line in context.table:
284 idx = int(line['ID']) if 'ID' in line.headings else None
286 for name, value in zip(line.headings, line.cells):
288 context.response.assert_address_field(idx, name, value)
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)
294 addr_parts = context.response.result[int(lid)]['address']
296 for attr in attrs.split(','):
298 assert attr not in addr_parts
300 assert attr in addr_parts
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)
307 addr_parts = dict(context.response.result[lid]['address'])
309 for line in context.table:
310 context.response.assert_address_field(lid, line['type'], line['value'])
311 del addr_parts[line['type']]
314 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
316 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
317 def step_impl(context, lid, coords):
319 context.execute_steps("then at least 1 result is returned")
320 bboxes = context.response.property_list('boundingbox')
322 context.execute_steps("then more than {}results are returned".format(lid))
323 bboxes = [context.response.result[int(lid)]['boundingbox']]
325 expected = Bbox(coords)
328 assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
330 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
331 def step_impl(context, lid, coords):
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'))
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'])]
341 expected = Bbox(coords)
343 for centroid in centroids:
344 assert centroid in expected,\
345 "Centroid {} is not inside {}.".format(centroid, expected)
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")
354 for res in context.response.result:
355 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
362 assert not has_dupe, "Found duplicate for %s" % (dup, )
364 assert has_dupe, "No duplicates found"