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(os.path.join(context.nominatim.build_dir, 'utils', '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.build_dir)
77 context.response = SearchResponse(outp, 'json')
79 def send_api_query(endpoint, params, fmt, context):
81 params['format'] = fmt.strip()
83 if context.table.headings[0] == 'param':
84 for line in context.table:
85 params[line['param']] = line['value']
87 for h in context.table.headings:
88 params[h] = context.table[0][h]
90 env = dict(BASE_SERVER_ENV)
91 env['QUERY_STRING'] = urlencode(params)
93 env['SCRIPT_NAME'] = '/%s.php' % endpoint
94 env['REQUEST_URI'] = '%s?%s' % (env['SCRIPT_NAME'], env['QUERY_STRING'])
95 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.website_dir.name, 'website')
96 env['SCRIPT_FILENAME'] = os.path.join(env['CONTEXT_DOCUMENT_ROOT'],
99 LOG.debug("Environment:" + json.dumps(env, sort_keys=True, indent=2))
101 if hasattr(context, 'http_headers'):
102 env.update(context.http_headers)
104 cmd = ['/usr/bin/env', 'php-cgi', '-f']
105 if context.nominatim.code_coverage_path:
106 env['COV_SCRIPT_FILENAME'] = env['SCRIPT_FILENAME']
107 env['COV_PHP_DIR'] = os.path.join(context.nominatim.src_dir, "lib")
108 env['COV_TEST_NAME'] = '%s:%s' % (context.scenario.filename, context.scenario.line)
109 env['SCRIPT_FILENAME'] = \
110 os.path.join(os.path.split(__file__)[0], 'cgi-with-coverage.php')
111 cmd.append(env['SCRIPT_FILENAME'])
112 env['PHP_CODE_COVERAGE_FILE'] = context.nominatim.next_code_coverage_file()
114 cmd.append(env['SCRIPT_FILENAME'])
116 for k,v in params.items():
117 cmd.append("%s=%s" % (k, v))
119 outp, err = run_script(cmd, cwd=context.nominatim.website_dir.name, env=env)
121 assert len(err) == 0, "Unexpected PHP error: %s" % (err)
123 if outp.startswith('Status: '):
124 status = int(outp[8:11])
128 content_start = outp.find('\r\n\r\n')
130 return outp[content_start + 4:], status
132 @given(u'the HTTP header')
133 def add_http_header(context):
134 if not hasattr(context, 'http_headers'):
135 context.http_headers = {}
137 for h in context.table.headings:
138 envvar = 'HTTP_' + h.upper().replace('-', '_')
139 context.http_headers[envvar] = context.table[0][h]
142 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"(?P<addr> with address)?')
143 def website_search_request(context, fmt, query, addr):
148 params['addressdetails'] = '1'
150 outp, status = send_api_query('search', params, fmt, context)
152 context.response = SearchResponse(outp, fmt or 'json', status)
154 @when(u'sending (?P<fmt>\S+ )?reverse coordinates (?P<lat>.+)?,(?P<lon>.+)?')
155 def website_reverse_request(context, fmt, lat, lon):
162 outp, status = send_api_query('reverse', params, fmt, context)
164 context.response = ReverseResponse(outp, fmt or 'xml', status)
166 @when(u'sending (?P<fmt>\S+ )?details query for (?P<query>.*)')
167 def website_details_request(context, fmt, query):
169 if query[0] in 'NWR':
170 params['osmtype'] = query[0]
171 params['osmid'] = query[1:]
173 params['place_id'] = query
174 outp, status = send_api_query('details', params, fmt, context)
176 context.response = GenericResponse(outp, fmt or 'json', status)
178 @when(u'sending (?P<fmt>\S+ )?lookup query for (?P<query>.*)')
179 def website_lookup_request(context, fmt, query):
180 params = { 'osm_ids' : query }
181 outp, status = send_api_query('lookup', params, fmt, context)
183 context.response = SearchResponse(outp, fmt or 'xml', status)
185 @when(u'sending (?P<fmt>\S+ )?status query')
186 def website_status_request(context, fmt):
188 outp, status = send_api_query('status', params, fmt, context)
190 context.response = StatusResponse(outp, fmt or 'text', status)
192 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
193 def validate_result_number(context, operator, number):
194 assert context.response.errorcode == 200
195 numres = len(context.response.result)
196 assert compare(operator, numres, int(number)), \
197 "Bad number of results: expected {} {}, got {}.".format(operator, number, numres)
199 @then(u'a HTTP (?P<status>\d+) is returned')
200 def check_http_return_status(context, status):
201 assert context.response.errorcode == int(status)
203 @then(u'the page contents equals "(?P<text>.+)"')
204 def check_page_content_equals(context, text):
205 assert context.response.page == text
207 @then(u'the result is valid (?P<fmt>\w+)')
208 def step_impl(context, fmt):
209 context.execute_steps("Then a HTTP 200 is returned")
210 assert context.response.format == fmt
212 @then(u'a (?P<fmt>\w+) user error is returned')
213 def check_page_error(context, fmt):
214 context.execute_steps("Then a HTTP 400 is returned")
215 assert context.response.format == fmt
218 assert re.search(r'<error>.+</error>', context.response.page, re.DOTALL) is not None
220 assert re.search(r'({"error":)', context.response.page, re.DOTALL) is not None
222 @then(u'result header contains')
223 def check_header_attr(context):
224 for line in context.table:
225 assert re.fullmatch(line['value'], context.response.header[line['attr']]) is not None, \
226 "attribute '%s': expected: '%s', got '%s'" % (
227 line['attr'], line['value'],
228 context.response.header[line['attr']])
230 @then(u'result header has (?P<neg>not )?attributes (?P<attrs>.*)')
231 def check_header_no_attr(context, neg, attrs):
232 for attr in attrs.split(','):
234 assert attr not in context.response.header
236 assert attr in context.response.header
238 @then(u'results contain')
239 def step_impl(context):
240 context.execute_steps("then at least 1 result is returned")
242 for line in context.table:
243 context.response.match_row(line)
245 @then(u'result (?P<lid>\d+ )?has (?P<neg>not )?attributes (?P<attrs>.*)')
246 def validate_attributes(context, lid, neg, attrs):
248 idx = range(len(context.response.result))
249 context.execute_steps("then at least 1 result is returned")
251 idx = [int(lid.strip())]
252 context.execute_steps("then more than %sresults are returned" % lid)
255 for attr in attrs.split(','):
257 assert attr not in context.response.result[i]
259 assert attr in context.response.result[i]
261 @then(u'result addresses contain')
262 def step_impl(context):
263 context.execute_steps("then at least 1 result is returned")
265 for line in context.table:
266 idx = int(line['ID']) if 'ID' in line.headings else None
268 for name, value in zip(line.headings, line.cells):
270 context.response.assert_address_field(idx, name, value)
272 @then(u'address of result (?P<lid>\d+) has(?P<neg> no)? types (?P<attrs>.*)')
273 def check_address(context, lid, neg, attrs):
274 context.execute_steps("then more than %s results are returned" % lid)
276 addr_parts = context.response.result[int(lid)]['address']
278 for attr in attrs.split(','):
280 assert attr not in addr_parts
282 assert attr in addr_parts
284 @then(u'address of result (?P<lid>\d+) (?P<complete>is|contains)')
285 def check_address(context, lid, complete):
286 context.execute_steps("then more than %s results are returned" % lid)
289 addr_parts = dict(context.response.result[lid]['address'])
291 for line in context.table:
292 context.response.assert_address_field(lid, line['type'], line['value'])
293 del addr_parts[line['type']]
296 assert len(addr_parts) == 0, "Additional address parts found: %s" % str(addr_parts)
298 @then(u'result (?P<lid>\d+ )?has bounding box in (?P<coords>[\d,.-]+)')
299 def step_impl(context, lid, coords):
301 context.execute_steps("then at least 1 result is returned")
302 bboxes = context.response.property_list('boundingbox')
304 context.execute_steps("then more than {}results are returned".format(lid))
305 bboxes = [context.response.result[int(lid)]['boundingbox']]
307 expected = Bbox(coords)
310 assert bbox in expected, "Bbox {} is not contained in {}.".format(bbox, expected)
312 @then(u'result (?P<lid>\d+ )?has centroid in (?P<coords>[\d,.-]+)')
313 def step_impl(context, lid, coords):
315 context.execute_steps("then at least 1 result is returned")
316 centroids = zip(context.response.property_list('lon'),
317 context.response.property_list('lat'))
319 context.execute_steps("then more than %sresults are returned".format(lid))
320 res = context.response.result[int(lid)]
321 centroids = [(res['lon'], res['lat'])]
323 expected = Bbox(coords)
325 for centroid in centroids:
326 assert centroid in expected,\
327 "Centroid {} is not inside {}.".format(centroid, expected)
329 @then(u'there are(?P<neg> no)? duplicates')
330 def check_for_duplicates(context, neg):
331 context.execute_steps("then at least 1 result is returned")
336 for res in context.response.result:
337 dup = (res['osm_type'], res['class'], res['type'], res['display_name'])
344 assert not has_dupe, "Found duplicate for %s" % (dup, )
346 assert has_dupe, "No duplicates found"