1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2024 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Tests for the Python web frameworks adaptor, v1 API.
11 import xml.etree.ElementTree as ET
15 from fake_adaptor import FakeAdaptor, FakeError, FakeResponse
17 import nominatim_api.v1.server_glue as glue
18 import nominatim_api as napi
19 import nominatim_api.logging as loglib
22 # ASGIAdaptor.get_int/bool()
24 @pytest.mark.parametrize('func', ['get_int', 'get_bool'])
25 def test_adaptor_get_int_missing_but_required(func):
26 with pytest.raises(FakeError, match='^400 -- .*missing'):
27 getattr(FakeAdaptor(), func)('something')
30 @pytest.mark.parametrize('func, val', [('get_int', 23), ('get_bool', True)])
31 def test_adaptor_get_int_missing_with_default(func, val):
32 assert getattr(FakeAdaptor(), func)('something', val) == val
35 @pytest.mark.parametrize('inp', ['0', '234', '-4566953498567934876'])
36 def test_adaptor_get_int_success(inp):
37 assert FakeAdaptor(params={'foo': inp}).get_int('foo') == int(inp)
38 assert FakeAdaptor(params={'foo': inp}).get_int('foo', 4) == int(inp)
41 @pytest.mark.parametrize('inp', ['rs', '4.5', '6f'])
42 def test_adaptor_get_int_bad_number(inp):
43 with pytest.raises(FakeError, match='^400 -- .*must be a number'):
44 FakeAdaptor(params={'foo': inp}).get_int('foo')
47 @pytest.mark.parametrize('inp', ['1', 'true', 'whatever', 'false'])
48 def test_adaptor_get_bool_trueish(inp):
49 assert FakeAdaptor(params={'foo': inp}).get_bool('foo')
52 def test_adaptor_get_bool_falsish():
53 assert not FakeAdaptor(params={'foo': '0'}).get_bool('foo')
56 # ASGIAdaptor.parse_format()
58 def test_adaptor_parse_format_use_default():
59 adaptor = FakeAdaptor()
61 assert glue.parse_format(adaptor, napi.StatusResult, 'text') == 'text'
62 assert adaptor.content_type == 'text/plain; charset=utf-8'
65 def test_adaptor_parse_format_use_configured():
66 adaptor = FakeAdaptor(params={'format': 'json'})
68 assert glue.parse_format(adaptor, napi.StatusResult, 'text') == 'json'
69 assert adaptor.content_type == 'application/json; charset=utf-8'
72 def test_adaptor_parse_format_invalid_value():
73 adaptor = FakeAdaptor(params={'format': '@!#'})
75 with pytest.raises(FakeError, match='^400 -- .*must be one of'):
76 glue.parse_format(adaptor, napi.StatusResult, 'text')
79 # ASGIAdaptor.get_accepted_languages()
81 def test_accepted_languages_from_param():
82 a = FakeAdaptor(params={'accept-language': 'de'})
83 assert glue.get_accepted_languages(a) == 'de'
86 def test_accepted_languages_from_header():
87 a = FakeAdaptor(headers={'accept-language': 'de'})
88 assert glue.get_accepted_languages(a) == 'de'
91 def test_accepted_languages_from_default(monkeypatch):
92 monkeypatch.setenv('NOMINATIM_DEFAULT_LANGUAGE', 'de')
94 assert glue.get_accepted_languages(a) == 'de'
97 def test_accepted_languages_param_over_header():
98 a = FakeAdaptor(params={'accept-language': 'de'},
99 headers={'accept-language': 'en'})
100 assert glue.get_accepted_languages(a) == 'de'
103 def test_accepted_languages_header_over_default(monkeypatch):
104 monkeypatch.setenv('NOMINATIM_DEFAULT_LANGUAGE', 'en')
105 a = FakeAdaptor(headers={'accept-language': 'de'})
106 assert glue.get_accepted_languages(a) == 'de'
109 # ASGIAdaptor.raise_error()
111 class TestAdaptorRaiseError:
113 @pytest.fixture(autouse=True)
114 def init_adaptor(self):
115 self.adaptor = FakeAdaptor()
116 glue.setup_debugging(self.adaptor)
118 def run_raise_error(self, msg, status):
119 with pytest.raises(FakeError) as excinfo:
120 self.adaptor.raise_error(msg, status=status)
125 def test_without_content_set(self):
126 err = self.run_raise_error('TEST', 404)
128 assert self.adaptor.content_type == 'text/plain; charset=utf-8'
129 assert err.msg == 'ERROR 404: TEST'
130 assert err.status == 404
134 self.adaptor.content_type = 'application/json; charset=utf-8'
136 err = self.run_raise_error('TEST', 501)
138 content = json.loads(err.msg)['error']
139 assert content['code'] == 501
140 assert content['message'] == 'TEST'
144 self.adaptor.content_type = 'text/xml; charset=utf-8'
146 err = self.run_raise_error('this!', 503)
148 content = ET.fromstring(err.msg)
150 assert content.tag == 'error'
151 assert content.find('code').text == '503'
152 assert content.find('message').text == 'this!'
155 def test_raise_error_during_debug():
156 a = FakeAdaptor(params={'debug': '1'})
157 glue.setup_debugging(a)
158 loglib.log().section('Ongoing')
160 with pytest.raises(FakeError) as excinfo:
161 a.raise_error('badstate')
163 content = ET.fromstring(excinfo.value.msg)
165 assert content.tag == 'html'
167 assert '>Ongoing<' in excinfo.value.msg
168 assert 'badstate' in excinfo.value.msg
171 # ASGIAdaptor.build_response
173 def test_build_response_without_content_type():
174 resp = glue.build_response(FakeAdaptor(), 'attention')
176 assert isinstance(resp, FakeResponse)
177 assert resp.status == 200
178 assert resp.output == 'attention'
179 assert resp.content_type == 'text/plain; charset=utf-8'
182 def test_build_response_with_status():
183 a = FakeAdaptor(params={'format': 'json'})
184 glue.parse_format(a, napi.StatusResult, 'text')
186 resp = glue.build_response(a, 'stuff\nmore stuff', status=404)
188 assert isinstance(resp, FakeResponse)
189 assert resp.status == 404
190 assert resp.output == 'stuff\nmore stuff'
191 assert resp.content_type == 'application/json; charset=utf-8'
194 def test_build_response_jsonp_with_json():
195 a = FakeAdaptor(params={'format': 'json', 'json_callback': 'test.func'})
196 glue.parse_format(a, napi.StatusResult, 'text')
198 resp = glue.build_response(a, '{}')
200 assert isinstance(resp, FakeResponse)
201 assert resp.status == 200
202 assert resp.output == 'test.func({})'
203 assert resp.content_type == 'application/javascript; charset=utf-8'
206 def test_build_response_jsonp_without_json():
207 a = FakeAdaptor(params={'format': 'text', 'json_callback': 'test.func'})
208 glue.parse_format(a, napi.StatusResult, 'text')
210 resp = glue.build_response(a, '{}')
212 assert isinstance(resp, FakeResponse)
213 assert resp.status == 200
214 assert resp.output == '{}'
215 assert resp.content_type == 'text/plain; charset=utf-8'
218 @pytest.mark.parametrize('param', ['alert(); func', '\\n', '', 'a b'])
219 def test_build_response_jsonp_bad_format(param):
220 a = FakeAdaptor(params={'format': 'json', 'json_callback': param})
221 glue.parse_format(a, napi.StatusResult, 'text')
223 with pytest.raises(FakeError, match='^400 -- .*Invalid'):
224 glue.build_response(a, '{}')
229 class TestStatusEndpoint:
231 @pytest.fixture(autouse=True)
232 def patch_status_func(self, monkeypatch):
233 async def _status(*args, **kwargs):
236 monkeypatch.setattr(napi.NominatimAPIAsync, 'status', _status)
240 async def test_status_without_params(self):
242 self.status = napi.StatusResult(0, 'foo')
244 resp = await glue.status_endpoint(napi.NominatimAPIAsync(), a)
246 assert isinstance(resp, FakeResponse)
247 assert resp.status == 200
248 assert resp.content_type == 'text/plain; charset=utf-8'
252 async def test_status_with_error(self):
254 self.status = napi.StatusResult(405, 'foo')
256 resp = await glue.status_endpoint(napi.NominatimAPIAsync(), a)
258 assert isinstance(resp, FakeResponse)
259 assert resp.status == 500
260 assert resp.content_type == 'text/plain; charset=utf-8'
264 async def test_status_json_with_error(self):
265 a = FakeAdaptor(params={'format': 'json'})
266 self.status = napi.StatusResult(405, 'foo')
268 resp = await glue.status_endpoint(napi.NominatimAPIAsync(), a)
270 assert isinstance(resp, FakeResponse)
271 assert resp.status == 200
272 assert resp.content_type == 'application/json; charset=utf-8'
276 async def test_status_bad_format(self):
277 a = FakeAdaptor(params={'format': 'foo'})
278 self.status = napi.StatusResult(0, 'foo')
280 with pytest.raises(FakeError):
281 await glue.status_endpoint(napi.NominatimAPIAsync(), a)
286 class TestDetailsEndpoint:
288 @pytest.fixture(autouse=True)
289 def patch_lookup_func(self, monkeypatch):
290 self.result = napi.DetailedResult(napi.SourceTable.PLACEX,
292 napi.Point(1.0, 2.0))
293 self.lookup_args = []
295 async def _lookup(*args, **kwargs):
296 self.lookup_args.extend(args[1:])
299 monkeypatch.setattr(napi.NominatimAPIAsync, 'details', _lookup)
303 async def test_details_no_params(self):
306 with pytest.raises(FakeError, match='^400 -- .*Missing'):
307 await glue.details_endpoint(napi.NominatimAPIAsync(), a)
311 async def test_details_by_place_id(self):
312 a = FakeAdaptor(params={'place_id': '4573'})
314 await glue.details_endpoint(napi.NominatimAPIAsync(), a)
316 assert self.lookup_args[0].place_id == 4573
320 async def test_details_by_osm_id(self):
321 a = FakeAdaptor(params={'osmtype': 'N', 'osmid': '45'})
323 await glue.details_endpoint(napi.NominatimAPIAsync(), a)
325 assert self.lookup_args[0].osm_type == 'N'
326 assert self.lookup_args[0].osm_id == 45
327 assert self.lookup_args[0].osm_class is None
331 async def test_details_with_debugging(self):
332 a = FakeAdaptor(params={'osmtype': 'N', 'osmid': '45', 'debug': '1'})
334 resp = await glue.details_endpoint(napi.NominatimAPIAsync(), a)
335 content = ET.fromstring(resp.output)
337 assert resp.content_type == 'text/html; charset=utf-8'
338 assert content.tag == 'html'
342 async def test_details_no_result(self):
343 a = FakeAdaptor(params={'place_id': '4573'})
346 with pytest.raises(FakeError, match='^404 -- .*found'):
347 await glue.details_endpoint(napi.NominatimAPIAsync(), a)
351 class TestReverseEndPoint:
353 @pytest.fixture(autouse=True)
354 def patch_reverse_func(self, monkeypatch):
355 self.result = napi.ReverseResult(napi.SourceTable.PLACEX,
357 napi.Point(1.0, 2.0))
358 async def _reverse(*args, **kwargs):
361 monkeypatch.setattr(napi.NominatimAPIAsync, 'reverse', _reverse)
365 @pytest.mark.parametrize('params', [{}, {'lat': '3.4'}, {'lon': '6.7'}])
366 async def test_reverse_no_params(self, params):
369 a.params['format'] = 'xml'
371 with pytest.raises(FakeError, match='^400 -- (?s:.*)missing'):
372 await glue.reverse_endpoint(napi.NominatimAPIAsync(), a)
376 @pytest.mark.parametrize('params', [{'lat': '45.6', 'lon': '4563'}])
377 async def test_reverse_success(self, params):
380 a.params['format'] = 'json'
382 res = await glue.reverse_endpoint(napi.NominatimAPIAsync(), a)
388 async def test_reverse_success(self):
390 a.params['lat'] = '56.3'
391 a.params['lon'] = '6.8'
393 assert await glue.reverse_endpoint(napi.NominatimAPIAsync(), a)
397 async def test_reverse_from_search(self):
399 a.params['q'] = '34.6 2.56'
400 a.params['format'] = 'json'
402 res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
404 assert len(json.loads(res.output)) == 1
409 class TestLookupEndpoint:
411 @pytest.fixture(autouse=True)
412 def patch_lookup_func(self, monkeypatch):
413 self.results = [napi.SearchResult(napi.SourceTable.PLACEX,
415 napi.Point(1.0, 2.0))]
416 async def _lookup(*args, **kwargs):
417 return napi.SearchResults(self.results)
419 monkeypatch.setattr(napi.NominatimAPIAsync, 'lookup', _lookup)
423 async def test_lookup_no_params(self):
425 a.params['format'] = 'json'
427 res = await glue.lookup_endpoint(napi.NominatimAPIAsync(), a)
429 assert res.output == '[]'
433 @pytest.mark.parametrize('param', ['w', 'bad', ''])
434 async def test_lookup_bad_params(self, param):
436 a.params['format'] = 'json'
437 a.params['osm_ids'] = f'W34,{param},N33333'
439 res = await glue.lookup_endpoint(napi.NominatimAPIAsync(), a)
441 assert len(json.loads(res.output)) == 1
445 @pytest.mark.parametrize('param', ['p234234', '4563'])
446 async def test_lookup_bad_osm_type(self, param):
448 a.params['format'] = 'json'
449 a.params['osm_ids'] = f'W34,{param},N33333'
451 res = await glue.lookup_endpoint(napi.NominatimAPIAsync(), a)
453 assert len(json.loads(res.output)) == 1
457 async def test_lookup_working(self):
459 a.params['format'] = 'json'
460 a.params['osm_ids'] = 'N23,W34'
462 res = await glue.lookup_endpoint(napi.NominatimAPIAsync(), a)
464 assert len(json.loads(res.output)) == 1
469 class TestSearchEndPointSearch:
471 @pytest.fixture(autouse=True)
472 def patch_lookup_func(self, monkeypatch):
473 self.results = [napi.SearchResult(napi.SourceTable.PLACEX,
475 napi.Point(1.0, 2.0))]
476 async def _search(*args, **kwargs):
477 return napi.SearchResults(self.results)
479 monkeypatch.setattr(napi.NominatimAPIAsync, 'search', _search)
483 async def test_search_free_text(self):
485 a.params['q'] = 'something'
487 res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
489 assert len(json.loads(res.output)) == 1
493 async def test_search_free_text_xml(self):
495 a.params['q'] = 'something'
496 a.params['format'] = 'xml'
498 res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
500 assert res.status == 200
501 assert res.output.index('something') > 0
505 async def test_search_free_and_structured(self):
507 a.params['q'] = 'something'
508 a.params['city'] = 'ignored'
510 with pytest.raises(FakeError, match='^400 -- .*cannot be used together'):
511 res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
515 @pytest.mark.parametrize('dedupe,numres', [(True, 1), (False, 2)])
516 async def test_search_dedupe(self, dedupe, numres):
517 self.results = self.results * 2
519 a.params['q'] = 'something'
521 a.params['dedupe'] = '0'
523 res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
525 assert len(json.loads(res.output)) == numres
528 class TestSearchEndPointSearchAddress:
530 @pytest.fixture(autouse=True)
531 def patch_lookup_func(self, monkeypatch):
532 self.results = [napi.SearchResult(napi.SourceTable.PLACEX,
534 napi.Point(1.0, 2.0))]
535 async def _search(*args, **kwargs):
536 return napi.SearchResults(self.results)
538 monkeypatch.setattr(napi.NominatimAPIAsync, 'search_address', _search)
542 async def test_search_structured(self):
544 a.params['street'] = 'something'
546 res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
548 assert len(json.loads(res.output)) == 1
551 class TestSearchEndPointSearchCategory:
553 @pytest.fixture(autouse=True)
554 def patch_lookup_func(self, monkeypatch):
555 self.results = [napi.SearchResult(napi.SourceTable.PLACEX,
557 napi.Point(1.0, 2.0))]
558 async def _search(*args, **kwargs):
559 return napi.SearchResults(self.results)
561 monkeypatch.setattr(napi.NominatimAPIAsync, 'search_category', _search)
565 async def test_search_category(self):
567 a.params['q'] = '[shop=fog]'
569 res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
571 assert len(json.loads(res.output)) == 1