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['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
86 env['COV_PHP_DIR'] = context.nominatim.src_dir
87 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
88 env['SCRIPT_FILENAME'] = \
89 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
90 cmd.append(env['SCRIPT_FILENAME'])
91 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
93 cmd.append(env['SCRIPT_FILENAME'])
95 for k,v in params.items():
96 cmd.append("%s=%s" % (k, v))
98 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
100 assert len(err) == 0, "Unexpected PHP error: %s" % (err)
102 if outp.startswith('Status: '):
103 status = int(outp[8:11])
107 content_start = outp.find('\r\n\r\n')
109 return outp[content_start + 4:], status
111 @given(u'the HTTP header')
112 def add_http_header(context):
113 if not hasattr(context, 'http_headers'):
114 context.http_headers = {}
116 for h in context.table.headings:
117 envvar = 'HTTP_' + h.upper().replace('-', '_')
118 context.http_headers[envvar] = context.table[0][h]
121 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
122 def website_search_request(context, fmt, query, addr):
127 params['addressdetails'] = '1'
128 if fmt and fmt.strip() == 'debug':
129 params['debug'] = '1'
131 outp, status = send_api_query('search', params, fmt, context)
133 context.response = SearchResponse(outp, fmt or 'json', status)
135 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
136 def website_reverse_request(context, fmt, lat, lon):
142 if fmt and fmt.strip() == 'debug':
143 params['debug'] = '1'
145 outp, status = send_api_query('reverse', params, fmt, context)
147 context.response = ReverseResponse(outp, fmt or 'xml', status)
149 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
150 def website_details_request(context, fmt, query):
152 if query[0] in 'NWR':
153 nid = NominatimID(query)
154 params['osmtype'] = nid.typ
155 params['osmid'] = nid.oid
157 params['class'] = nid.cls
159 params['place_id'] = query
160 outp, status = send_api_query('details', params, fmt, context)
162 context.response = GenericResponse(outp, fmt or 'json', status)
164 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
165 def website_lookup_request(context, fmt, query):
166 params = { 'osm_ids' : query }
167 outp, status = send_api_query('lookup', params, fmt, context)
169 context.response = SearchResponse(outp, fmt or 'xml', status)
171 @when(u'sending (?P<fmt>\S+ )?status query')
172 def website_status_request(context, fmt):
174 outp, status = send_api_query('status', params, fmt, context)
176 context.response = StatusResponse(outp, fmt or 'text', status)
178 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
179 def validate_result_number(context, operator, number):
180 assert context.response.errorcode == 200
181 numres = len(context.response.result)
182 assert compare(operator, numres, int(number)), \
183 "Bad number of results: expected {} {}, got {}.".format(operator, number, numres)
185 @then(u'a HTTP (?P<status>\d+) is returned')
186 def check_http_return_status(context, status):
187 assert context.response.errorcode == int(status), \
188 "Return HTTP status is {}.".format(context.response.errorcode)
190 @then(u'the page contents equals "(?P<text>.+)"')
191 def check_page_content_equals(context, text):
192 assert context.response.page == text
194 @then(u'the result is valid (?P<fmt>\w+)')
195 def step_impl(context, fmt):
196 context.execute_steps("Then a HTTP 200 is returned")
197 assert context.response.format == fmt
199 @then(u'a (?P<fmt>\w+) user error is returned')
200 def check_page_error(context, fmt):
201 context.execute_steps("Then a HTTP 400 is returned")
202 assert context.response.format == fmt
205 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
207 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
209 @then(u'result header contains')
210 def check_header_attr(context):
211 for line in context.table:
212 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
213 "attribute '%s': expected: '%s', got '%s'" % (
214 line['attr'], line['value'],
215 context.response.header[line['attr']])
217 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
218 def check_header_no_attr(context, neg, attrs):
219 for attr in attrs.split(','):
221 assert attr not in context.response.header, \
222 "Unexpected attribute {}. Full response:\n{}".format(
223 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
225 assert attr in context.response.header, \
226 "No attribute {}. Full response:\n{}".format(
227 attr, json.dumps(context.response.header, sort_keys=True, indent=2))
229 @then(u'results contain')
230 def step_impl(context):
231 context.execute_steps("then at least 1 result is returned")
233 for line in context.table:
234 context.response.match_row(line)
236 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
237 def validate_attributes(context, lid, neg, attrs):
239 idx = range(len(context.response.result))
240 context.execute_steps("then at least 1 result is returned")
242 idx = [int(lid.strip())]
243 context.execute_steps("then more than %sresults are returned" % lid)
246 for attr in attrs.split(','):
248 assert attr not in context.response.result[i],\
249 "Unexpected attribute {}. Full response:\n{}".format(
250 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
252 assert attr in context.response.result[i], \
253 "No attribute {}. Full response:\n{}".format(
254 attr, json.dumps(context.response.result[i], sort_keys=True, indent=2))
256 @then(u'result addresses contain')
257 def step_impl(context):
258 context.execute_steps("then at least 1 result is returned")
260 for line in context.table:
261 idx = int(line['ID']) if 'ID' in line.headings else None
263 for name, value in zip(line.headings, line.cells):
265 context.response.assert_address_field(idx, name, value)
267 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
268 def check_address(context, lid, neg, attrs):
269 context.execute_steps("then more than %s results are returned" % lid)
271 addr_parts = context.response.result[int(lid)]['address']
273 for attr in attrs.split(','):
275 assert attr not in addr_parts
277 assert attr in addr_parts
279 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
280 def check_address(context, lid, complete):
281 context.execute_steps("then more than %s results are returned" % lid)
284 addr_parts = dict(context.response.result[lid]['address'])
286 for line in context.table:
287 context.response.assert_address_field(lid, line['type'], line['value'])
288 del addr_parts[line['type']]
291 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
293 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
294 def step_impl(context, lid, coords):
296 context.execute_steps("then at least 1 result is returned")
297 bboxes = context.response.property_list('boundingbox')
299 context.execute_steps("then more than {}results are returned".format(lid))
300 bboxes = [context.response.result[int(lid)]['boundingbox']]
302 expected = Bbox(coords)
305 assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
307 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
308 def step_impl(context, lid, coords):
310 context.execute_steps("then at least 1 result is returned")
311 centroids = zip(context.response.property_list('lon'),
312 context.response.property_list('lat'))
314 context.execute_steps("then more than %sresults are returned".format(lid))
315 res = context.response.result[int(lid)]
316 centroids = [(res['lon'], res['lat'])]
318 expected = Bbox(coords)
320 for centroid in centroids:
321 assert centroid in expected,\
322 "Centroid {} is not inside {}.".format(centroid, expected)
324 @then(u'there are(?P<neg> no)? duplicates')
325 def check_for_duplicates(context, neg):
326 context.execute_steps("then at least 1 result is returned")
331 for res in context.response.result:
332 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
339 assert not has_dupe, "Found duplicate for %s" % (dup, )
341 assert has_dupe, "No duplicates found"