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 context.response = SearchResponse(outp, fmt or 'json', status)
153 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
154 def website_reverse_request(context, fmt, lat, lon):
161 outp, status = send_api_query('reverse', params, fmt, context)
163 context.response = ReverseResponse(outp, fmt or 'xml', status)
165 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
166 def website_details_request(context, fmt, query):
168 if query[0] in 'NWR':
169 params['osmtype'] = query[0]
170 params['osmid'] = query[1:]
172 params['place_id'] = query
173 outp, status = send_api_query('details', params, fmt, context)
175 context.response = GenericResponse(outp, fmt or 'json', status)
177 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
178 def website_lookup_request(context, fmt, query):
179 params = { 'osm_ids' : query }
180 outp, status = send_api_query('lookup', params, fmt, context)
182 context.response = SearchResponse(outp, fmt or 'xml', status)
184 @when(u'sending (?P<fmt>\S+ )?status query')
185 def website_status_request(context, fmt):
187 outp, status = send_api_query('status', params, fmt, context)
189 context.response = StatusResponse(outp, fmt or 'text', status)
191 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
192 def validate_result_number(context, operator, number):
193 assert context.response.errorcode == 200
194 numres = len(context.response.result)
195 assert compare(operator, numres, int(number)), \
196 "Bad number of results: expected %s %s, got %d." % (operator, number, numres)
198 @then(u'a HTTP (?P<status>\d+) is returned')
199 def check_http_return_status(context, status):
200 assert context.response.errorcode == int(status)
202 @then(u'the page contents equals "(?P<text>.+)"')
203 def check_page_content_equals(context, text):
204 assert context.response.page == text
206 @then(u'the result is valid (?P<fmt>\w+)')
207 def step_impl(context, fmt):
208 context.execute_steps("Then a HTTP 200 is returned")
209 assert context.response.format == fmt
211 @then(u'a (?P<fmt>\w+) user error is returned')
212 def check_page_error(context, fmt):
213 context.execute_steps("Then a HTTP 400 is returned")
214 assert context.response.format == fmt
217 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
219 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
221 @then(u'result header contains')
222 def check_header_attr(context):
223 for line in context.table:
224 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
225 "attribute '%s': expected: '%s', got '%s'" % (
226 line['attr'], line['value'],
227 context.response.header[line['attr']])
229 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
230 def check_header_no_attr(context, neg, attrs):
231 for attr in attrs.split(','):
233 assert attr not in context.response.header
235 assert attr in context.response.header
237 @then(u'results contain')
238 def step_impl(context):
239 context.execute_steps("then at least 1 result is returned")
241 for line in context.table:
242 context.response.match_row(line)
244 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
245 def validate_attributes(context, lid, neg, attrs):
247 idx = range(len(context.response.result))
248 context.execute_steps("then at least 1 result is returned")
250 idx = [int(lid.strip())]
251 context.execute_steps("then more than %sresults are returned" % lid)
254 for attr in attrs.split(','):
256 assert attr not in context.response.result[i]
258 assert attr in context.response.result[i]
260 @then(u'result addresses contain')
261 def step_impl(context):
262 context.execute_steps("then at least 1 result is returned")
264 if 'ID' not in context.table.headings:
265 addr_parts = context.response.property_list('address')
267 for line in context.table:
268 if 'ID' in context.table.headings:
269 addr_parts = [dict(context.response.result[int(line['ID'])]['address'])]
271 for h in context.table.headings:
275 assert p[h] == line[h], "Bad address value for %s" % h
277 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
278 def check_address(context, lid, neg, attrs):
279 context.execute_steps("then more than %s results are returned" % lid)
281 addr_parts = context.response.result[int(lid)]['address']
283 for attr in attrs.split(','):
285 assert attr not in addr_parts
287 assert attr in addr_parts
289 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
290 def check_address(context, lid, complete):
291 context.execute_steps("then more than %s results are returned" % lid)
293 addr_parts = dict(context.response.result[int(lid)]['address'])
295 for line in context.table:
296 assert line['type'] in addr_parts
297 assert addr_parts[line['type']] == line['value'], \
298 "Bad address value for %s" % line['type']
299 del addr_parts[line['type']]
302 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
304 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
305 def step_impl(context, lid, coords):
307 context.execute_steps("then at least 1 result is returned")
308 bboxes = context.response.property_list('boundingbox')
310 context.execute_steps("then more than %sresults are returned" % lid)
311 bboxes = [ context.response.result[int(lid)]['boundingbox']]
313 coord = [ float(x) for x in coords.split(',') ]
316 if isinstance(bbox, str):
317 bbox = bbox.split(',')
318 bbox = [ float(x) for x in bbox ]
320 assert bbox[0] >= coord[0]
321 assert bbox[1] <= coord[1]
322 assert bbox[2] >= coord[2]
323 assert bbox[3] <= coord[3]
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 bboxes = zip(context.response.property_list('lat'),
330 context.response.property_list('lon'))
332 context.execute_steps("then more than %sresults are returned" % lid)
333 res = context.response.result[int(lid)]
334 bboxes = [ (res['lat'], res['lon']) ]
336 coord = [ float(x) for x in coords.split(',') ]
338 for lat, lon in bboxes:
341 assert lat >= coord[0]
342 assert lat <= coord[1]
343 assert lon >= coord[2]
344 assert lon <= coord[3]
346 @then(u'there are(?P<neg> no)? duplicates')
347 def check_for_duplicates(context, neg):
348 context.execute_steps("then at least 1 result is returned")
353 for res in context.response.result:
354 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
361 assert not has_dupe, "Found duplicate for %s" % (dup, )
363 assert has_dupe, "No duplicates found"