1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Tests for running the postcode searcher.
12 import nominatim.api as napi
13 from nominatim.api.types import SearchDetails
14 from nominatim.api.search.db_searches import PostcodeSearch
15 from nominatim.api.search.db_search_fields import WeightedStrings, FieldLookup, \
16 FieldRanking, RankedTokens
18 def run_search(apiobj, global_penalty, pcs, pc_penalties=None,
19 ccodes=[], lookup=[], ranking=[], details=SearchDetails()):
20 if pc_penalties is None:
21 pc_penalties = [0.0] * len(pcs)
24 penalty = global_penalty
25 postcodes = WeightedStrings(pcs, pc_penalties)
26 countries = WeightedStrings(ccodes, [0.0] * len(ccodes))
30 search = PostcodeSearch(0.0, MySearchData())
33 async with apiobj.api._async_api.begin() as conn:
34 return await search.lookup(conn, details)
36 return apiobj.async_to_sync(run())
39 def test_postcode_only_search(apiobj):
40 apiobj.add_postcode(place_id=100, country_code='ch', postcode='12345')
41 apiobj.add_postcode(place_id=101, country_code='pl', postcode='12 345')
43 results = run_search(apiobj, 0.3, ['12345', '12 345'], [0.0, 0.1])
45 assert len(results) == 2
46 assert [r.place_id for r in results] == [100, 101]
49 def test_postcode_with_country(apiobj):
50 apiobj.add_postcode(place_id=100, country_code='ch', postcode='12345')
51 apiobj.add_postcode(place_id=101, country_code='pl', postcode='12 345')
53 results = run_search(apiobj, 0.3, ['12345', '12 345'], [0.0, 0.1],
56 assert len(results) == 1
57 assert results[0].place_id == 101
60 class TestPostcodeSearchWithAddress:
62 @pytest.fixture(autouse=True)
63 def fill_database(self, apiobj):
64 apiobj.add_postcode(place_id=100, country_code='ch',
65 parent_place_id=1000, postcode='12345')
66 apiobj.add_postcode(place_id=101, country_code='pl',
67 parent_place_id=2000, postcode='12345')
68 apiobj.add_placex(place_id=1000, class_='place', type='village',
69 rank_search=22, rank_address=22,
71 apiobj.add_search_name(1000, names=[1,2,10,11],
72 search_rank=22, address_rank=22,
74 apiobj.add_placex(place_id=2000, class_='place', type='village',
75 rank_search=22, rank_address=22,
77 apiobj.add_search_name(2000, names=[1,2,20,21],
78 search_rank=22, address_rank=22,
82 def test_lookup_both(self, apiobj):
83 lookup = FieldLookup('name_vector', [1,2], 'restrict')
84 ranking = FieldRanking('name_vector', 0.3, [RankedTokens(0.0, [10])])
86 results = run_search(apiobj, 0.1, ['12345'], lookup=[lookup], ranking=[ranking])
88 assert [r.place_id for r in results] == [100, 101]
91 def test_restrict_by_name(self, apiobj):
92 lookup = FieldLookup('name_vector', [10], 'restrict')
94 results = run_search(apiobj, 0.1, ['12345'], lookup=[lookup])
96 assert [r.place_id for r in results] == [100]