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
16 LOG = logging.getLogger(__name__)
19 'HTTP_HOST' : 'localhost',
20 'HTTP_USER_AGENT' : 'Mozilla/5.0 (X11; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0',
21 'HTTP_ACCEPT' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
22 'HTTP_ACCEPT_ENCODING' : 'gzip, deflate',
23 'HTTP_CONNECTION' : 'keep-alive',
24 'SERVER_SIGNATURE' : '<address>Nominatim BDD Tests</address>',
25 'SERVER_SOFTWARE' : 'Nominatim test',
26 'SERVER_NAME' : 'localhost',
27 'SERVER_ADDR' : '127.0.1.1',
29 'REMOTE_ADDR' : '127.0.0.1',
30 'DOCUMENT_ROOT' : '/var/www',
31 'REQUEST_SCHEME' : 'http',
32 'CONTEXT_PREFIX' : '/',
33 'SERVER_ADMIN' : 'webmaster@localhost',
34 'REMOTE_PORT' : '49319',
35 'GATEWAY_INTERFACE' : 'CGI/1.1',
36 'SERVER_PROTOCOL' : 'HTTP/1.1',
37 'REQUEST_METHOD' : 'GET',
38 'REDIRECT_STATUS' : 'CGI'
42 def compare(operator, op1, op2):
43 if operator == 'less than':
45 elif operator == 'more than':
47 elif operator == 'exactly':
49 elif operator == 'at least':
51 elif operator == 'at most':
54 raise Exception("unknown operator '%s'" % operator)
57 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
58 def query_cmd(context, query, dups):
59 """ Query directly via PHP script.
61 cmd = ['/usr/bin/env', 'php']
62 cmd.append(context.nominatim.src_dir / 'lib' / 'admin' / 'query.php')
64 cmd.extend(['--search', query])
65 # add more parameters in table form
67 for h in context.table.headings:
68 value = context.table[0][h].strip()
70 cmd.extend(('--' + h, value))
73 cmd.extend(('--dedupe', '0'))
75 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name,
76 env=context.nominatim.test_env)
78 context.response = SearchResponse(outp, 'json')
80 def send_api_query(endpoint, params, fmt, context):
82 params['format'] = fmt.strip()
84 if context.table.headings[0] == 'param':
85 for line in context.table:
86 params[line['param']] = line['value']
88 for h in context.table.headings:
89 params[h] = context.table[0][h]
91 env = dict(BASE_SERVER_ENV)
92 env['QUERY_STRING'] = urlencode(params)
94 env['SCRIPT_NAME'] = '/%s.php' % endpoint
95 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
96 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.website_dir.name, 'website')
97 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
100 LOG.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
102 if hasattr(context, 'http_headers'):
103 env.update(context.http_headers)
105 cmd = ['/usr/bin/env', 'php-cgi', '-f']
106 if context.nominatim.code_coverage_path:
107 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
108 env['COV_PHP_DIR'] = context.nominatim.src_dir
109 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
110 env['SCRIPT_FILENAME'] = \
111 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
112 cmd.append(env['SCRIPT_FILENAME'])
113 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
115 cmd.append(env['SCRIPT_FILENAME'])
117 for k,v in params.items():
118 cmd.append("%s=%s" % (k, v))
120 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
122 assert len(err) == 0, "Unexpected PHP error: %s" % (err)
124 if outp.startswith('Status: '):
125 status = int(outp[8:11])
129 content_start = outp.find('\r\n\r\n')
131 return outp[content_start + 4:], status
133 @given(u'the HTTP header')
134 def add_http_header(context):
135 if not hasattr(context, 'http_headers'):
136 context.http_headers = {}
138 for h in context.table.headings:
139 envvar = 'HTTP_' + h.upper().replace('-', '_')
140 context.http_headers[envvar] = context.table[0][h]
143 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
144 def website_search_request(context, fmt, query, addr):
149 params['addressdetails'] = '1'
151 outp, status = send_api_query('search', params, fmt, context)
153 context.response = SearchResponse(outp, fmt or 'json', status)
155 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
156 def website_reverse_request(context, fmt, lat, lon):
163 outp, status = send_api_query('reverse', params, fmt, context)
165 context.response = ReverseResponse(outp, fmt or 'xml', status)
167 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
168 def website_details_request(context, fmt, query):
170 if query[0] in 'NWR':
171 params['osmtype'] = query[0]
172 params['osmid'] = query[1:]
174 params['place_id'] = query
175 outp, status = send_api_query('details', params, fmt, context)
177 context.response = GenericResponse(outp, fmt or 'json', status)
179 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
180 def website_lookup_request(context, fmt, query):
181 params = { 'osm_ids' : query }
182 outp, status = send_api_query('lookup', params, fmt, context)
184 context.response = SearchResponse(outp, fmt or 'xml', status)
186 @when(u'sending (?P<fmt>\S+ )?status query')
187 def website_status_request(context, fmt):
189 outp, status = send_api_query('status', params, fmt, context)
191 context.response = StatusResponse(outp, fmt or 'text', status)
193 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
194 def validate_result_number(context, operator, number):
195 assert context.response.errorcode == 200
196 numres = len(context.response.result)
197 assert compare(operator, numres, int(number)), \
198 "Bad number of results: expected {} {}, got {}.".format(operator, number, numres)
200 @then(u'a HTTP (?P<status>\d+) is returned')
201 def check_http_return_status(context, status):
202 assert context.response.errorcode == int(status)
204 @then(u'the page contents equals "(?P<text>.+)"')
205 def check_page_content_equals(context, text):
206 assert context.response.page == text
208 @then(u'the result is valid (?P<fmt>\w+)')
209 def step_impl(context, fmt):
210 context.execute_steps("Then a HTTP 200 is returned")
211 assert context.response.format == fmt
213 @then(u'a (?P<fmt>\w+) user error is returned')
214 def check_page_error(context, fmt):
215 context.execute_steps("Then a HTTP 400 is returned")
216 assert context.response.format == fmt
219 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
221 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
223 @then(u'result header contains')
224 def check_header_attr(context):
225 for line in context.table:
226 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
227 "attribute '%s': expected: '%s', got '%s'" % (
228 line['attr'], line['value'],
229 context.response.header[line['attr']])
231 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
232 def check_header_no_attr(context, neg, attrs):
233 for attr in attrs.split(','):
235 assert attr not in context.response.header
237 assert attr in context.response.header
239 @then(u'results contain')
240 def step_impl(context):
241 context.execute_steps("then at least 1 result is returned")
243 for line in context.table:
244 context.response.match_row(line)
246 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
247 def validate_attributes(context, lid, neg, attrs):
249 idx = range(len(context.response.result))
250 context.execute_steps("then at least 1 result is returned")
252 idx = [int(lid.strip())]
253 context.execute_steps("then more than %sresults are returned" % lid)
256 for attr in attrs.split(','):
258 assert attr not in context.response.result[i]
260 assert attr in context.response.result[i]
262 @then(u'result addresses contain')
263 def step_impl(context):
264 context.execute_steps("then at least 1 result is returned")
266 for line in context.table:
267 idx = int(line['ID']) if 'ID' in line.headings else None
269 for name, value in zip(line.headings, line.cells):
271 context.response.assert_address_field(idx, name, value)
273 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
274 def check_address(context, lid, neg, attrs):
275 context.execute_steps("then more than %s results are returned" % lid)
277 addr_parts = context.response.result[int(lid)]['address']
279 for attr in attrs.split(','):
281 assert attr not in addr_parts
283 assert attr in addr_parts
285 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
286 def check_address(context, lid, complete):
287 context.execute_steps("then more than %s results are returned" % lid)
290 addr_parts = dict(context.response.result[lid]['address'])
292 for line in context.table:
293 context.response.assert_address_field(lid, line['type'], line['value'])
294 del addr_parts[line['type']]
297 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
299 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
300 def step_impl(context, lid, coords):
302 context.execute_steps("then at least 1 result is returned")
303 bboxes = context.response.property_list('boundingbox')
305 context.execute_steps("then more than {}results are returned".format(lid))
306 bboxes = [context.response.result[int(lid)]['boundingbox']]
308 expected = Bbox(coords)
311 assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
313 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
314 def step_impl(context, lid, coords):
316 context.execute_steps("then at least 1 result is returned")
317 centroids = zip(context.response.property_list('lon'),
318 context.response.property_list('lat'))
320 context.execute_steps("then more than %sresults are returned".format(lid))
321 res = context.response.result[int(lid)]
322 centroids = [(res['lon'], res['lat'])]
324 expected = Bbox(coords)
326 for centroid in centroids:
327 assert centroid in expected,\
328 "Centroid {} is not inside {}.".format(centroid, expected)
330 @then(u'there are(?P<neg> no)? duplicates')
331 def check_for_duplicates(context, neg):
332 context.execute_steps("then at least 1 result is returned")
337 for res in context.response.result:
338 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
345 assert not has_dupe, "Found duplicate for %s" % (dup, )
347 assert has_dupe, "No duplicates found"