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 def send_api_query(endpoint, params, fmt, context):
59 if fmt is not None and fmt.strip() != 'debug':
60 params['format'] = fmt.strip()
62 if context.table.headings[0] == 'param':
63 for line in context.table:
64 params[line['param']] = line['value']
66 for h in context.table.headings:
67 params[h] = context.table[0][h]
69 env = dict(BASE_SERVER_ENV)
70 env['QUERY_STRING'] = urlencode(params)
72 env['SCRIPT_NAME'] = '/%s.php' % endpoint
73 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
74 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.website_dir.name, 'website')
75 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
78 LOG.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
80 if hasattr(context, 'http_headers'):
81 env.update(context.http_headers)
83 cmd = ['/usr/bin/env', 'php-cgi', '-f']
84 if context.nominatim.code_coverage_path:
85 env['XDEBUG_MODE'] = 'coverage'
86 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
87 env['COV_PHP_DIR'] = context.nominatim.src_dir
88 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
89 env['SCRIPT_FILENAME'] = \
90 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
91 cmd.append(env['SCRIPT_FILENAME'])
92 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
94 cmd.append(env['SCRIPT_FILENAME'])
96 for k,v in params.items():
97 cmd.append("%s=%s" % (k, v))
99 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
101 assert len(err) == 0, "Unexpected PHP error: %s" % (err)
103 if outp.startswith('Status: '):
104 status = int(outp[8:11])
108 content_start = outp.find('\r\n\r\n')
110 return outp[content_start + 4:], status
112 @given(u'the HTTP header')
113 def add_http_header(context):
114 if not hasattr(context, 'http_headers'):
115 context.http_headers = {}
117 for h in context.table.headings:
118 envvar = 'HTTP_' + h.upper().replace('-', '_')
119 context.http_headers[envvar] = context.table[0][h]
122 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
123 def website_search_request(context, fmt, query, addr):
128 params['addressdetails'] = '1'
129 if fmt and fmt.strip() == 'debug':
130 params['debug'] = '1'
132 outp, status = send_api_query('search', params, fmt, context)
134 context.response = SearchResponse(outp, fmt or 'json', status)
136 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
137 def website_reverse_request(context, fmt, lat, lon):
143 if fmt and fmt.strip() == 'debug':
144 params['debug'] = '1'
146 outp, status = send_api_query('reverse', params, fmt, context)
148 context.response = ReverseResponse(outp, fmt or 'xml', status)
150 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
151 def website_details_request(context, fmt, query):
153 if query[0] in 'NWR':
154 nid = NominatimID(query)
155 params['osmtype'] = nid.typ
156 params['osmid'] = nid.oid
158 params['class'] = nid.cls
160 params['place_id'] = query
161 outp, status = send_api_query('details', params, fmt, context)
163 context.response = GenericResponse(outp, fmt or 'json', status)
165 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
166 def website_lookup_request(context, fmt, query):
167 params = { 'osm_ids' : query }
168 outp, status = send_api_query('lookup', params, fmt, context)
170 context.response = SearchResponse(outp, fmt or 'xml', status)
172 @when(u'sending (?P<fmt>\S+ )?status query')
173 def website_status_request(context, fmt):
175 outp, status = send_api_query('status', params, fmt, context)
177 context.response = StatusResponse(outp, fmt or 'text', status)
179 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
180 def validate_result_number(context, operator, number):
181 assert context.response.errorcode == 200
182 numres = len(context.response.result)
183 assert compare(operator, numres, int(number)), \
184 "Bad number of results: expected {} {}, got {}.".format(operator, number, numres)
186 @then(u'a HTTP (?P<status>\d+) is returned')
187 def check_http_return_status(context, status):
188 assert context.response.errorcode == int(status), \
189 "Return HTTP status is {}.".format(context.response.errorcode)
191 @then(u'the page contents equals "(?P<text>.+)"')
192 def check_page_content_equals(context, text):
193 assert context.response.page == text
195 @then(u'the result is valid (?P<fmt>\w+)')
196 def step_impl(context, fmt):
197 context.execute_steps("Then a HTTP 200 is returned")
198 assert context.response.format == fmt
200 @then(u'a (?P<fmt>\w+) user error is returned')
201 def check_page_error(context, fmt):
202 context.execute_steps("Then a HTTP 400 is returned")
203 assert context.response.format == fmt
206 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
208 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
210 @then(u'result header contains')
211 def check_header_attr(context):
212 for line in context.table:
213 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
214 "attribute '%s': expected: '%s', got '%s'" % (
215 line['attr'], line['value'],
216 context.response.header[line['attr']])
218 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
219 def check_header_no_attr(context, neg, attrs):
220 for attr in attrs.split(','):
222 assert attr not in context.response.header, \
223 "Unexpected attribute {}. Full response:\n{}".format(
224 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
226 assert attr in context.response.header, \
227 "No attribute {}. Full response:\n{}".format(
228 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
230 @then(u'results contain')
231 def step_impl(context):
232 context.execute_steps("then at least 1 result is returned")
234 for line in context.table:
235 context.response.match_row(line)
237 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
238 def validate_attributes(context, lid, neg, attrs):
240 idx = range(len(context.response.result))
241 context.execute_steps("then at least 1 result is returned")
243 idx = [int(lid.strip())]
244 context.execute_steps("then more than %sresults are returned" % lid)
247 for attr in attrs.split(','):
249 assert attr not in context.response.result[i],\
250 "Unexpected attribute {}. Full response:\n{}".format(
251 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
253 assert attr in context.response.result[i], \
254 "No attribute {}. Full response:\n{}".format(
255 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
257 @then(u'result addresses contain')
258 def step_impl(context):
259 context.execute_steps("then at least 1 result is returned")
261 for line in context.table:
262 idx = int(line['ID']) if 'ID' in line.headings else None
264 for name, value in zip(line.headings, line.cells):
266 context.response.assert_address_field(idx, name, value)
268 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
269 def check_address(context, lid, neg, attrs):
270 context.execute_steps("then more than %s results are returned" % lid)
272 addr_parts = context.response.result[int(lid)]['address']
274 for attr in attrs.split(','):
276 assert attr not in addr_parts
278 assert attr in addr_parts
280 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
281 def check_address(context, lid, complete):
282 context.execute_steps("then more than %s results are returned" % lid)
285 addr_parts = dict(context.response.result[lid]['address'])
287 for line in context.table:
288 context.response.assert_address_field(lid, line['type'], line['value'])
289 del addr_parts[line['type']]
292 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
294 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
295 def step_impl(context, lid, coords):
297 context.execute_steps("then at least 1 result is returned")
298 bboxes = context.response.property_list('boundingbox')
300 context.execute_steps("then more than {}results are returned".format(lid))
301 bboxes = [context.response.result[int(lid)]['boundingbox']]
303 expected = Bbox(coords)
306 assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
308 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
309 def step_impl(context, lid, coords):
311 context.execute_steps("then at least 1 result is returned")
312 centroids = zip(context.response.property_list('lon'),
313 context.response.property_list('lat'))
315 context.execute_steps("then more than %sresults are returned".format(lid))
316 res = context.response.result[int(lid)]
317 centroids = [(res['lon'], res['lat'])]
319 expected = Bbox(coords)
321 for centroid in centroids:
322 assert centroid in expected,\
323 "Centroid {} is not inside {}.".format(centroid, expected)
325 @then(u'there are(?P<neg> no)? duplicates')
326 def check_for_duplicates(context, neg):
327 context.execute_steps("then at least 1 result is returned")
332 for res in context.response.result:
333 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
340 assert not has_dupe, "Found duplicate for %s" % (dup, )
342 assert has_dupe, "No duplicates found"