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
15 LOG = logging.getLogger(__name__)
18 'HTTP_HOST' : 'localhost',
19 'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
20 'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
21 'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
22 'HTTP_CONNECTION' : 'keep-alive',
23 'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
24 'SERVER_SOFTWARE' : 'Nominatim test',
25 'SERVER_NAME' : 'localhost',
26 'SERVER_ADDR' : '127.0.1.1',
28 'REMOTE_ADDR' : '127.0.0.1',
29 'DOCUMENT_ROOT' : '/var/www',
30 'REQUEST_SCHEME' : 'http',
31 'CONTEXT_PREFIX' : '/',
32 'SERVER_ADMIN' : 'webmaster@localhost',
33 'REMOTE_PORT' : '49319',
34 'GATEWAY_INTERFACE' : 'CGI/1.1',
35 'SERVER_PROTOCOL' : 'HTTP/1.1',
36 'REQUEST_METHOD' : 'GET',
37 'REDIRECT_STATUS' : 'CGI'
41 def compare(operator, op1, op2):
42 if operator == 'less than':
44 elif operator == 'more than':
46 elif operator == 'exactly':
48 elif operator == 'at least':
50 elif operator == 'at most':
53 raise Exception("unknown operator '%s'" % operator)
56 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
57 def query_cmd(context, query, dups):
58 """ Query directly via PHP script.
60 cmd = ['/usr/bin/env', 'php']
61 cmd.append(os.path.join(context.nominatim.build_dir, 'utils', 'query.php'))
63 cmd.extend(['--search', query])
64 # add more parameters in table form
66 for h in context.table.headings:
67 value = context.table[0][h].strip()
69 cmd.extend(('--' + h, value))
72 cmd.extend(('--dedupe', '0'))
74 outp, err = run_script(cmd, cwd=context.nominatim.build_dir)
76 context.response = SearchResponse(outp, 'json')
78 def send_api_query(endpoint, params, fmt, context):
80 params['format'] = fmt.strip()
82 if context.table.headings[0] == 'param':
83 for line in context.table:
84 params[line['param']] = line['value']
86 for h in context.table.headings:
87 params[h] = context.table[0][h]
89 env = dict(BASE_SERVER_ENV)
90 env['QUERY_STRING'] = urlencode(params)
92 env['SCRIPT_NAME'] = '/%s.php' % endpoint
93 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
94 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.website_dir.name, 'website')
95 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
98 LOG.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
100 if hasattr(context, 'http_headers'):
101 env.update(context.http_headers)
103 cmd = ['/usr/bin/env', 'php-cgi', '-f']
104 if context.nominatim.code_coverage_path:
105 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
106 env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
107 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
108 env['SCRIPT_FILENAME'] = \
109 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
110 cmd.append(env['SCRIPT_FILENAME'])
111 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
113 cmd.append(env['SCRIPT_FILENAME'])
115 for k,v in params.items():
116 cmd.append("%s=%s" % (k, v))
118 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
120 assert len(err) == 0, "Unexpected PHP error: %s" % (err)
122 if outp.startswith('Status: '):
123 status = int(outp[8:11])
127 content_start = outp.find('\r\n\r\n')
129 return outp[content_start + 4:], status
131 @given(u'the HTTP header')
132 def add_http_header(context):
133 if not hasattr(context, 'http_headers'):
134 context.http_headers = {}
136 for h in context.table.headings:
137 envvar = 'HTTP_' + h.upper().replace('-', '_')
138 context.http_headers[envvar] = context.table[0][h]
141 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
142 def website_search_request(context, fmt, query, addr):
147 params['addressdetails'] = '1'
149 outp, status = send_api_query('search', params, fmt, context)
151 if fmt is None or fmt == 'jsonv2 ':
156 context.response = SearchResponse(outp, outfmt, status)
158 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
159 def website_reverse_request(context, fmt, lat, lon):
166 outp, status = send_api_query('reverse', params, fmt, context)
170 elif fmt == 'jsonv2 ':
175 context.response = ReverseResponse(outp, outfmt, status)
177 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
178 def website_details_request(context, fmt, query):
180 if query[0] in 'NWR':
181 params['osmtype'] = query[0]
182 params['osmid'] = query[1:]
184 params['place_id'] = query
185 outp, status = send_api_query('details', params, fmt, context)
192 context.response = GenericResponse(outp, outfmt, status)
194 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
195 def website_lookup_request(context, fmt, query):
196 params = { 'osm_ids' : query }
197 outp, status = send_api_query('lookup', params, fmt, context)
201 elif fmt == 'jsonv2 ':
203 elif fmt == 'geojson ':
205 elif fmt == 'geocodejson ':
206 outfmt = 'geocodejson'
210 context.response = SearchResponse(outp, outfmt, status)
212 @when(u'sending (?P<fmt>\S+ )?status query')
213 def website_status_request(context, fmt):
215 outp, status = send_api_query('status', params, fmt, context)
222 context.response = StatusResponse(outp, outfmt, status)
224 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
225 def validate_result_number(context, operator, number):
226 assert context.response.errorcode == 200
227 numres = len(context.response.result)
228 assert compare(operator, numres, int(number)), \
229 "Bad number of results: expected %s %s, got %d." % (operator, number, numres)
231 @then(u'a HTTP (?P<status>\d+) is returned')
232 def check_http_return_status(context, status):
233 assert context.response.errorcode == int(status)
235 @then(u'the page contents equals "(?P<text>.+)"')
236 def check_page_content_equals(context, text):
237 assert context.response.page == text
239 @then(u'the result is valid (?P<fmt>\w+)')
240 def step_impl(context, fmt):
241 context.execute_steps("Then a HTTP 200 is returned")
242 assert context.response.format == fmt
244 @then(u'a (?P<fmt>\w+) user error is returned')
245 def check_page_error(context, fmt):
246 context.execute_steps("Then a HTTP 400 is returned")
247 assert context.response.format == fmt
250 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
252 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
254 @then(u'result header contains')
255 def check_header_attr(context):
256 for line in context.table:
257 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
258 "attribute '%s': expected: '%s', got '%s'" % (
259 line['attr'], line['value'],
260 context.response.header[line['attr']])
262 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
263 def check_header_no_attr(context, neg, attrs):
264 for attr in attrs.split(','):
266 assert attr not in context.response.header
268 assert attr in context.response.header
270 @then(u'results contain')
271 def step_impl(context):
272 context.execute_steps("then at least 1 result is returned")
274 for line in context.table:
275 context.response.match_row(line)
277 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
278 def validate_attributes(context, lid, neg, attrs):
280 idx = range(len(context.response.result))
281 context.execute_steps("then at least 1 result is returned")
283 idx = [int(lid.strip())]
284 context.execute_steps("then more than %sresults are returned" % lid)
287 for attr in attrs.split(','):
289 assert attr not in context.response.result[i]
291 assert attr in context.response.result[i]
293 @then(u'result addresses contain')
294 def step_impl(context):
295 context.execute_steps("then at least 1 result is returned")
297 if 'ID' not in context.table.headings:
298 addr_parts = context.response.property_list('address')
300 for line in context.table:
301 if 'ID' in context.table.headings:
302 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
304 for h in context.table.headings:
308 assert p[h] == line[h], "Bad address value for %s" % h
310 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
311 def check_address(context, lid, neg, attrs):
312 context.execute_steps("then more than %s results are returned" % lid)
314 addr_parts = context.response.result[int(lid)]['address']
316 for attr in attrs.split(','):
318 assert attr not in addr_parts
320 assert attr in addr_parts
322 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
323 def check_address(context, lid, complete):
324 context.execute_steps("then more than %s results are returned" % lid)
326 addr_parts = dict(context.response.result[int(lid)]['address'])
328 for line in context.table:
329 assert line['type'] in addr_parts
330 assert addr_parts[line['type']] == line['value'], \
331 "Bad address value for %s" % line['type']
332 del addr_parts[line['type']]
335 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
337 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
338 def step_impl(context, lid, coords):
340 context.execute_steps("then at least 1 result is returned")
341 bboxes = context.response.property_list('boundingbox')
343 context.execute_steps("then more than %sresults are returned" % lid)
344 bboxes = [ context.response.result[int(lid)]['boundingbox']]
346 coord = [ float(x) for x in coords.split(',') ]
349 if isinstance(bbox, str):
350 bbox = bbox.split(',')
351 bbox = [ float(x) for x in bbox ]
353 assert bbox[0] >= coord[0]
354 assert bbox[1] <= coord[1]
355 assert bbox[2] >= coord[2]
356 assert bbox[3] <= coord[3]
358 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
359 def step_impl(context, lid, coords):
361 context.execute_steps("then at least 1 result is returned")
362 bboxes = zip(context.response.property_list('lat'),
363 context.response.property_list('lon'))
365 context.execute_steps("then more than %sresults are returned" % lid)
366 res = context.response.result[int(lid)]
367 bboxes = [ (res['lat'], res['lon']) ]
369 coord = [ float(x) for x in coords.split(',') ]
371 for lat, lon in bboxes:
374 assert lat >= coord[0]
375 assert lat <= coord[1]
376 assert lon >= coord[2]
377 assert lon <= coord[3]
379 @then(u'there are(?P<neg> no)? duplicates')
380 def check_for_duplicates(context, neg):
381 context.execute_steps("then at least 1 result is returned")
386 for res in context.response.result:
387 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
394 assert not has_dupe, "Found duplicate for %s" % (dup, )
396 assert has_dupe, "No duplicates found"