]> git.openstreetmap.org Git - nominatim.git/blob - test/python/api/test_server_glue_v1.py
Merge pull request #4130 from lonvia/avoid-creating-word-lookup-indexes
[nominatim.git] / test / python / api / test_server_glue_v1.py
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2025 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Tests for the Python web frameworks adaptor, v1 API.
9 """
10 import json
11 import xml.etree.ElementTree as ET
12
13 import pytest
14
15 from fake_adaptor import FakeAdaptor, FakeError, FakeResponse
16
17 import nominatim_api.v1.server_glue as glue
18 import nominatim_api as napi
19 import nominatim_api.logging as loglib
20
21
22 # ASGIAdaptor.get_int/bool()
23
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')
28
29
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
33
34
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)
39
40
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')
45
46
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')
50
51
52 def test_adaptor_get_bool_falsish():
53     assert not FakeAdaptor(params={'foo': '0'}).get_bool('foo')
54
55
56 # ASGIAdaptor.parse_format()
57
58 def test_adaptor_parse_format_use_default():
59     adaptor = FakeAdaptor()
60
61     assert glue.parse_format(adaptor, napi.StatusResult, 'text') == 'text'
62     assert adaptor.content_type == 'text/plain; charset=utf-8'
63
64
65 def test_adaptor_parse_format_use_configured():
66     adaptor = FakeAdaptor(params={'format': 'json'})
67
68     assert glue.parse_format(adaptor, napi.StatusResult, 'text') == 'json'
69     assert adaptor.content_type == 'application/json; charset=utf-8'
70
71
72 def test_adaptor_parse_format_invalid_value():
73     adaptor = FakeAdaptor(params={'format': '@!#'})
74
75     with pytest.raises(FakeError, match='^400 -- .*must be one of'):
76         glue.parse_format(adaptor, napi.StatusResult, 'text')
77
78
79 # ASGIAdaptor.get_accepted_languages()
80
81 def test_accepted_languages_from_param():
82     a = FakeAdaptor(params={'accept-language': 'de'})
83     assert glue.get_accepted_languages(a) == 'de'
84
85
86 def test_accepted_languages_from_header():
87     a = FakeAdaptor(headers={'accept-language': 'de'})
88     assert glue.get_accepted_languages(a) == 'de'
89
90
91 def test_accepted_languages_from_default(monkeypatch):
92     monkeypatch.setenv('NOMINATIM_DEFAULT_LANGUAGE', 'de')
93     a = FakeAdaptor()
94     assert glue.get_accepted_languages(a) == 'de'
95
96
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'
101
102
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'
107
108
109 # ASGIAdaptor.raise_error()
110
111 class TestAdaptorRaiseError:
112
113     @pytest.fixture(autouse=True)
114     def init_adaptor(self):
115         self.adaptor = FakeAdaptor()
116         glue.setup_debugging(self.adaptor)
117
118     def run_raise_error(self, msg, status):
119         with pytest.raises(FakeError) as excinfo:
120             self.adaptor.raise_error(msg, status=status)
121
122         return excinfo.value
123
124     def test_without_content_set(self):
125         err = self.run_raise_error('TEST', 404)
126
127         assert self.adaptor.content_type == 'text/plain; charset=utf-8'
128         assert err.msg == 'ERROR 404: TEST'
129         assert err.status == 404
130
131     def test_json(self):
132         self.adaptor.content_type = 'application/json; charset=utf-8'
133
134         err = self.run_raise_error('TEST', 501)
135
136         content = json.loads(err.msg)['error']
137         assert content['code'] == 501
138         assert content['message'] == 'TEST'
139
140     def test_xml(self):
141         self.adaptor.content_type = 'text/xml; charset=utf-8'
142
143         err = self.run_raise_error('this!', 503)
144
145         content = ET.fromstring(err.msg)
146
147         assert content.tag == 'error'
148         assert content.find('code').text == '503'
149         assert content.find('message').text == 'this!'
150
151
152 def test_raise_error_during_debug():
153     a = FakeAdaptor(params={'debug': '1'})
154     glue.setup_debugging(a)
155     loglib.log().section('Ongoing')
156
157     with pytest.raises(FakeError) as excinfo:
158         a.raise_error('badstate')
159
160     content = ET.fromstring(excinfo.value.msg)
161
162     assert content.tag == 'html'
163
164     assert '>Ongoing<' in excinfo.value.msg
165     assert 'badstate' in excinfo.value.msg
166
167
168 # ASGIAdaptor.build_response
169
170 def test_build_response_without_content_type():
171     resp = glue.build_response(FakeAdaptor(), 'attention')
172
173     assert isinstance(resp, FakeResponse)
174     assert resp.status == 200
175     assert resp.output == 'attention'
176     assert resp.content_type == 'text/plain; charset=utf-8'
177
178
179 def test_build_response_with_status():
180     a = FakeAdaptor(params={'format': 'json'})
181     glue.parse_format(a, napi.StatusResult, 'text')
182
183     resp = glue.build_response(a, 'stuff\nmore stuff', status=404)
184
185     assert isinstance(resp, FakeResponse)
186     assert resp.status == 404
187     assert resp.output == 'stuff\nmore stuff'
188     assert resp.content_type == 'application/json; charset=utf-8'
189
190
191 def test_build_response_jsonp_with_json():
192     a = FakeAdaptor(params={'format': 'json', 'json_callback': 'test.func'})
193     glue.parse_format(a, napi.StatusResult, 'text')
194
195     resp = glue.build_response(a, '{}')
196
197     assert isinstance(resp, FakeResponse)
198     assert resp.status == 200
199     assert resp.output == 'test.func({})'
200     assert resp.content_type == 'application/javascript; charset=utf-8'
201
202
203 def test_build_response_jsonp_without_json():
204     a = FakeAdaptor(params={'format': 'text', 'json_callback': 'test.func'})
205     glue.parse_format(a, napi.StatusResult, 'text')
206
207     resp = glue.build_response(a, '{}')
208
209     assert isinstance(resp, FakeResponse)
210     assert resp.status == 200
211     assert resp.output == '{}'
212     assert resp.content_type == 'text/plain; charset=utf-8'
213
214
215 @pytest.mark.parametrize('param', ['alert(); func', '\\n', '', 'a b'])
216 def test_build_response_jsonp_bad_format(param):
217     a = FakeAdaptor(params={'format': 'json', 'json_callback': param})
218     glue.parse_format(a, napi.StatusResult, 'text')
219
220     with pytest.raises(FakeError, match='^400 -- .*Invalid'):
221         glue.build_response(a, '{}')
222
223
224 # status_endpoint()
225
226 class TestStatusEndpoint:
227
228     @pytest.fixture(autouse=True)
229     def patch_status_func(self, monkeypatch):
230         async def _status(*args, **kwargs):
231             return self.status
232
233         monkeypatch.setattr(napi.NominatimAPIAsync, 'status', _status)
234
235     @pytest.mark.asyncio
236     async def test_status_without_params(self):
237         a = FakeAdaptor()
238         self.status = napi.StatusResult(0, 'foo')
239
240         resp = await glue.status_endpoint(napi.NominatimAPIAsync(), a)
241
242         assert isinstance(resp, FakeResponse)
243         assert resp.status == 200
244         assert resp.content_type == 'text/plain; charset=utf-8'
245
246     @pytest.mark.asyncio
247     async def test_status_with_error(self):
248         a = FakeAdaptor()
249         self.status = napi.StatusResult(405, 'foo')
250
251         resp = await glue.status_endpoint(napi.NominatimAPIAsync(), a)
252
253         assert isinstance(resp, FakeResponse)
254         assert resp.status == 500
255         assert resp.content_type == 'text/plain; charset=utf-8'
256
257     @pytest.mark.asyncio
258     async def test_status_json_with_error(self):
259         a = FakeAdaptor(params={'format': 'json'})
260         self.status = napi.StatusResult(405, 'foo')
261
262         resp = await glue.status_endpoint(napi.NominatimAPIAsync(), a)
263
264         assert isinstance(resp, FakeResponse)
265         assert resp.status == 200
266         assert resp.content_type == 'application/json; charset=utf-8'
267
268     @pytest.mark.asyncio
269     async def test_status_bad_format(self):
270         a = FakeAdaptor(params={'format': 'foo'})
271         self.status = napi.StatusResult(0, 'foo')
272
273         with pytest.raises(FakeError):
274             await glue.status_endpoint(napi.NominatimAPIAsync(), a)
275
276
277 # details_endpoint()
278
279 class TestDetailsEndpoint:
280
281     @pytest.fixture(autouse=True)
282     def patch_lookup_func(self, monkeypatch):
283         self.result = napi.DetailedResult(napi.SourceTable.PLACEX,
284                                           ('place', 'thing'),
285                                           napi.Point(1.0, 2.0))
286         self.lookup_args = []
287
288         async def _lookup(*args, **kwargs):
289             self.lookup_args.extend(args[1:])
290             return self.result
291
292         monkeypatch.setattr(napi.NominatimAPIAsync, 'details', _lookup)
293
294     @pytest.mark.asyncio
295     async def test_details_no_params(self):
296         a = FakeAdaptor()
297
298         with pytest.raises(FakeError, match='^400 -- .*Missing'):
299             await glue.details_endpoint(napi.NominatimAPIAsync(), a)
300
301     @pytest.mark.asyncio
302     async def test_details_by_place_id(self):
303         a = FakeAdaptor(params={'place_id': '4573'})
304
305         await glue.details_endpoint(napi.NominatimAPIAsync(), a)
306
307         assert self.lookup_args[0].place_id == 4573
308
309     @pytest.mark.asyncio
310     async def test_details_by_osm_id(self):
311         a = FakeAdaptor(params={'osmtype': 'N', 'osmid': '45'})
312
313         await glue.details_endpoint(napi.NominatimAPIAsync(), a)
314
315         assert self.lookup_args[0].osm_type == 'N'
316         assert self.lookup_args[0].osm_id == 45
317         assert self.lookup_args[0].osm_class is None
318
319     @pytest.mark.asyncio
320     async def test_details_by_postcode(self):
321         a = FakeAdaptor(params={'postcode': 'us:94110'})
322
323         await glue.details_endpoint(napi.NominatimAPIAsync(), a)
324
325         assert self.lookup_args[0].country_code == 'us'
326         assert self.lookup_args[0].postcode == '94110'
327
328     @pytest.mark.asyncio
329     async def test_details_by_postcode_id(self):
330         a = FakeAdaptor(params={'postcode': 'Pus:94110'})
331
332         await glue.details_endpoint(napi.NominatimAPIAsync(), a)
333
334         assert self.lookup_args[0].country_code == 'us'
335         assert self.lookup_args[0].postcode == '94110'
336
337     @pytest.mark.asyncio
338     async def test_details_with_debugging(self):
339         a = FakeAdaptor(params={'osmtype': 'N', 'osmid': '45', 'debug': '1'})
340
341         resp = await glue.details_endpoint(napi.NominatimAPIAsync(), a)
342         content = ET.fromstring(resp.output)
343
344         assert resp.content_type == 'text/html; charset=utf-8'
345         assert content.tag == 'html'
346
347     @pytest.mark.asyncio
348     async def test_details_no_result(self):
349         a = FakeAdaptor(params={'place_id': '4573'})
350         self.result = None
351
352         with pytest.raises(FakeError, match='^404 -- .*found'):
353             await glue.details_endpoint(napi.NominatimAPIAsync(), a)
354
355
356 # reverse_endpoint()
357 class TestReverseEndPoint:
358
359     @pytest.fixture(autouse=True)
360     def patch_reverse_func(self, monkeypatch):
361         self.result = napi.ReverseResult(napi.SourceTable.PLACEX,
362                                          ('place', 'thing'),
363                                          napi.Point(1.0, 2.0))
364
365         async def _reverse(*args, **kwargs):
366             return self.result
367
368         monkeypatch.setattr(napi.NominatimAPIAsync, 'reverse', _reverse)
369
370     @pytest.mark.asyncio
371     @pytest.mark.parametrize('params', [{}, {'lat': '3.4'}, {'lon': '6.7'}])
372     async def test_reverse_no_params(self, params):
373         a = FakeAdaptor()
374         a.params = params
375         a.params['format'] = 'xml'
376
377         with pytest.raises(FakeError, match='^400 -- (?s:.*)missing'):
378             await glue.reverse_endpoint(napi.NominatimAPIAsync(), a)
379
380     @pytest.mark.asyncio
381     async def test_reverse_success(self):
382         a = FakeAdaptor()
383         a.params['lat'] = '56.3'
384         a.params['lon'] = '6.8'
385
386         assert await glue.reverse_endpoint(napi.NominatimAPIAsync(), a)
387
388     @pytest.mark.asyncio
389     async def test_reverse_from_search(self):
390         a = FakeAdaptor()
391         a.params['q'] = '34.6 2.56'
392         a.params['format'] = 'json'
393
394         res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
395
396         assert len(json.loads(res.output)) == 1
397
398
399 # lookup_endpoint()
400
401 class TestLookupEndpoint:
402
403     @pytest.fixture(autouse=True)
404     def patch_lookup_func(self, monkeypatch):
405         self.results = [napi.SearchResult(napi.SourceTable.PLACEX,
406                                           ('place', 'thing'),
407                                           napi.Point(1.0, 2.0))]
408
409         async def _lookup(*args, **kwargs):
410             return napi.SearchResults(self.results)
411
412         monkeypatch.setattr(napi.NominatimAPIAsync, 'lookup', _lookup)
413
414     @pytest.mark.asyncio
415     async def test_lookup_no_params(self):
416         a = FakeAdaptor()
417         a.params['format'] = 'json'
418
419         res = await glue.lookup_endpoint(napi.NominatimAPIAsync(), a)
420
421         assert res.output == '[]'
422
423     @pytest.mark.asyncio
424     @pytest.mark.parametrize('param', ['w', 'bad', ''])
425     async def test_lookup_bad_params(self, param):
426         a = FakeAdaptor()
427         a.params['format'] = 'json'
428         a.params['osm_ids'] = f'W34,{param},N33333'
429
430         res = await glue.lookup_endpoint(napi.NominatimAPIAsync(), a)
431
432         assert len(json.loads(res.output)) == 1
433
434     @pytest.mark.asyncio
435     @pytest.mark.parametrize('param', ['p234234', '4563'])
436     async def test_lookup_bad_osm_type(self, param):
437         a = FakeAdaptor()
438         a.params['format'] = 'json'
439         a.params['osm_ids'] = f'W34,{param},N33333'
440
441         res = await glue.lookup_endpoint(napi.NominatimAPIAsync(), a)
442
443         assert len(json.loads(res.output)) == 1
444
445     @pytest.mark.asyncio
446     async def test_lookup_working(self):
447         a = FakeAdaptor()
448         a.params['format'] = 'json'
449         a.params['osm_ids'] = 'N23,W34'
450
451         res = await glue.lookup_endpoint(napi.NominatimAPIAsync(), a)
452
453         assert len(json.loads(res.output)) == 1
454
455
456 # search_endpoint()
457
458 class TestSearchEndPointSearch:
459
460     @pytest.fixture(autouse=True)
461     def patch_lookup_func(self, monkeypatch):
462         self.results = [napi.SearchResult(napi.SourceTable.PLACEX,
463                                           ('place', 'thing'),
464                                           napi.Point(1.0, 2.0))]
465
466         async def _search(*args, **kwargs):
467             return napi.SearchResults(self.results)
468
469         monkeypatch.setattr(napi.NominatimAPIAsync, 'search', _search)
470
471     @pytest.mark.asyncio
472     async def test_search_free_text(self):
473         a = FakeAdaptor()
474         a.params['q'] = 'something'
475
476         res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
477
478         assert len(json.loads(res.output)) == 1
479
480     @pytest.mark.asyncio
481     async def test_search_free_text_xml(self):
482         a = FakeAdaptor()
483         a.params['q'] = 'something'
484         a.params['format'] = 'xml'
485
486         res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
487
488         assert res.status == 200
489         assert res.output.index('something') > 0
490
491     @pytest.mark.asyncio
492     async def test_search_free_text_xml_uses_stable_postcode_exclude_ids(self):
493         self.results = [napi.SearchResult(napi.SourceTable.POSTCODE,
494                                           ('place', 'postcode'),
495                                           napi.Point(1.0, 2.0),
496                                           place_id=123,
497                                           names={'ref': 'EH4 7EA'},
498                                           country_code='gb')]
499         a = FakeAdaptor(params={'q': 'something', 'format': 'xml'})
500
501         res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
502
503         assert 'exclude_place_ids="Pgb:EH4_7EA"' in res.output
504
505     @pytest.mark.asyncio
506     async def test_search_free_text_jsonv2_emits_postcode_id(self):
507         self.results = [napi.SearchResult(napi.SourceTable.POSTCODE,
508                                           ('place', 'postcode'),
509                                           napi.Point(1.0, 2.0),
510                                           place_id=123,
511                                           names={'ref': 'EH4 7EA'},
512                                           country_code='gb')]
513         a = FakeAdaptor(params={'q': 'something'})
514
515         res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
516
517         assert '"postcode_id":"Pgb:EH4_7EA"' in res.output
518
519     @pytest.mark.asyncio
520     async def test_search_free_and_structured(self):
521         a = FakeAdaptor()
522         a.params['q'] = 'something'
523         a.params['city'] = 'ignored'
524
525         with pytest.raises(FakeError, match='^400 -- .*cannot be used together'):
526             await glue.search_endpoint(napi.NominatimAPIAsync(), a)
527
528     @pytest.mark.asyncio
529     @pytest.mark.parametrize('dedupe,numres', [(True, 1), (False, 2)])
530     async def test_search_dedupe(self, dedupe, numres):
531         self.results = self.results * 2
532         a = FakeAdaptor()
533         a.params['q'] = 'something'
534         if not dedupe:
535             a.params['dedupe'] = '0'
536
537         res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
538
539         assert len(json.loads(res.output)) == numres
540
541
542 class TestSearchEndPointSearchAddress:
543
544     @pytest.fixture(autouse=True)
545     def patch_lookup_func(self, monkeypatch):
546         self.results = [napi.SearchResult(napi.SourceTable.PLACEX,
547                                           ('place', 'thing'),
548                                           napi.Point(1.0, 2.0))]
549
550         async def _search(*args, **kwargs):
551             return napi.SearchResults(self.results)
552
553         monkeypatch.setattr(napi.NominatimAPIAsync, 'search_address', _search)
554
555     @pytest.mark.asyncio
556     async def test_search_structured(self):
557         a = FakeAdaptor()
558         a.params['street'] = 'something'
559
560         res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
561
562         assert len(json.loads(res.output)) == 1
563
564
565 class TestSearchEndPointSearchCategory:
566
567     @pytest.fixture(autouse=True)
568     def patch_lookup_func(self, monkeypatch):
569         self.results = [napi.SearchResult(napi.SourceTable.PLACEX,
570                                           ('place', 'thing'),
571                                           napi.Point(1.0, 2.0))]
572
573         async def _search(*args, **kwargs):
574             return napi.SearchResults(self.results)
575
576         monkeypatch.setattr(napi.NominatimAPIAsync, 'search_category', _search)
577
578     @pytest.mark.asyncio
579     async def test_search_category(self):
580         a = FakeAdaptor()
581         a.params['q'] = '[shop=fog]'
582
583         res = await glue.search_endpoint(napi.NominatimAPIAsync(), a)
584
585         assert len(json.loads(res.output)) == 1