1 """ Steps that run search queries.
3 Queries may either be run directly via PHP using the query script
4 or via the HTTP interface.
11 from tidylib import tidy_document
12 import xml.etree.ElementTree as ET
14 from urllib.parse import urlencode
15 from collections import OrderedDict
16 from nose.tools import * # for assert functions
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_LANGUAGE' : 'en,de;q=0.5',
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 class SearchResponse(object):
60 def __init__(self, page, fmt='json', errorcode=200):
63 self.errorcode = errorcode
68 getattr(self, 'parse_' + fmt)()
71 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
76 self.header['json_func'] = m.group(1)
77 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
80 content, errors = tidy_document(self.page,
81 options={'char-encoding' : 'utf8'})
82 #eq_(len(errors), 0 , "Errors found in HTML document:\n%s" % errors)
84 b = content.find('nominatim_results =')
85 e = content.find('</script>')
86 content = content[b:e]
88 e = content.rfind(']')
90 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(content[b:e+1])
93 et = ET.fromstring(self.page)
95 self.header = dict(et.attrib)
99 assert_equal(child.tag, "place")
100 self.result.append(dict(child.attrib))
102 def match_row(self, row):
103 if 'ID' in row.headings:
104 todo = [int(row['ID'])]
106 todo = range(len(self.result))
110 for h in row.headings:
114 assert_equal(res['osm_type'], row[h][0])
115 assert_equal(res['osm_id'], row[h][1:])
116 elif h == 'centroid':
117 x, y = row[h].split(' ')
118 assert_almost_equal(float(y), float(res['lat']))
119 assert_almost_equal(float(x), float(res['lon']))
122 assert_equal(str(res[h]), str(row[h]))
125 @when(u'searching for "(?P<query>.*)"(?P<dups> with dups)?')
126 def query_cmd(context, query, dups):
127 """ Query directly via PHP script.
129 cmd = [os.path.join(context.nominatim.build_dir, 'utils', 'query.php'),
131 # add more parameters in table form
133 for h in context.table.headings:
134 value = context.table[0][h].strip()
136 cmd.extend(('--' + h, value))
139 cmd.extend(('--dedupe', '0'))
141 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir,
142 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
143 (outp, err) = proc.communicate()
145 assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
147 context.response = SearchResponse(outp.decode('utf-8'), 'json')
150 @when(u'sending (?P<fmt>\S+ )?search query "(?P<query>.*)"')
151 def website_search_request(context, fmt, query):
152 env = BASE_SERVER_ENV
154 params = { 'q' : query }
156 params['format'] = fmt.strip()
158 if context.table.headings[0] == 'param':
159 for line in context.table:
160 params[line['param']] = line['value']
162 for h in context.table.headings:
163 params[h] = context.table[0][h]
164 env['QUERY_STRING'] = urlencode(params)
166 env['REQUEST_URI'] = '/search.php?' + env['QUERY_STRING']
167 env['SCRIPT_NAME'] = '/search.php'
168 env['CONTEXT_DOCUMENT_ROOT'] = os.path.join(context.nominatim.build_dir, 'website')
169 env['SCRIPT_FILENAME'] = os.path.join(context.nominatim.build_dir, 'website', 'search.php')
170 env['NOMINATIM_SETTINGS'] = context.nominatim.local_settings_file
172 cmd = [ '/usr/bin/php-cgi', env['SCRIPT_FILENAME']]
173 for k,v in params.items():
174 cmd.append("%s=%s" % (k, v))
176 proc = subprocess.Popen(cmd, cwd=context.nominatim.build_dir, env=env,
177 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
179 (outp, err) = proc.communicate()
181 assert_equals(0, proc.returncode,
182 "query.php failed with message: %s\noutput: %s" % (err, outp))
184 assert_equals(0, len(err), "Unexpected PHP error: %s" % (err))
186 outp = outp.decode('utf-8')
188 if outp.startswith('Status: '):
189 status = int(outp[8:11])
193 content_start = outp.find('\r\n\r\n')
194 assert_less(11, content_start)
198 elif fmt == 'jsonv2 ':
203 context.response = SearchResponse(outp[content_start + 4:], outfmt, status)
206 @step(u'(?P<operator>less than|more than|exactly|at least|at most) (?P<number>\d+) results? (?:is|are) returned')
207 def validate_result_number(context, operator, number):
208 eq_(context.response.errorcode, 200)
209 numres = len(context.response.result)
210 ok_(compare(operator, numres, int(number)),
211 "Bad number of results: expected %s %s, got %d." % (operator, number, numres))
213 @then(u'a HTTP (?P<status>\d+) is returned')
214 def check_http_return_status(context, status):
215 eq_(context.response.errorcode, int(status))
217 @then(u'the result is valid (?P<fmt>\w+)')
218 def step_impl(context, fmt):
219 eq_(context.response.format, fmt)
221 @then(u'result header contains')
222 def check_header_attr(context):
223 for line in context.table:
224 assert_is_not_none(re.fullmatch(line['value'], context.response.header[line['attr']]),
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_not_in(attr, context.response.header)
235 assert_in(attr, 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):
246 context.execute_steps("then at least %s result is returned" % lid)
248 for attr in attrs.split(','):
250 assert_not_in(attr, context.response.result[int(lid)])
252 assert_in(attr, context.response.result[int(lid)])