]> git.openstreetmap.org Git - nominatim.git/blob - test/python/tools/test_postcodes.py
release 5.1.0.post6
[nominatim.git] / test / python / tools / test_postcodes.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 functions to maintain the artificial postcode table.
9 """
10 import subprocess
11
12 import pytest
13
14 from nominatim_db.tools import postcodes
15 from nominatim_db.data import country_info
16 import dummy_tokenizer
17
18
19 class MockPostcodeTable:
20     """ A location_postcode table for testing.
21     """
22     def __init__(self, conn):
23         self.conn = conn
24         with conn.cursor() as cur:
25             cur.execute("""CREATE TABLE location_postcode (
26                                place_id BIGINT,
27                                parent_place_id BIGINT,
28                                rank_search SMALLINT,
29                                rank_address SMALLINT,
30                                indexed_status SMALLINT,
31                                indexed_date TIMESTAMP,
32                                country_code varchar(2),
33                                postcode TEXT,
34                                geometry GEOMETRY(Geometry, 4326))""")
35             cur.execute("""CREATE OR REPLACE FUNCTION token_normalized_postcode(postcode TEXT)
36                            RETURNS TEXT AS $$ BEGIN RETURN postcode; END; $$ LANGUAGE plpgsql;
37
38                            CREATE OR REPLACE FUNCTION get_country_code(place geometry)
39                            RETURNS TEXT AS $$ BEGIN
40                            RETURN null;
41                            END; $$ LANGUAGE plpgsql;
42                         """)
43         conn.commit()
44
45     def add(self, country, postcode, x, y):
46         with self.conn.cursor() as cur:
47             cur.execute("""INSERT INTO location_postcode (place_id, indexed_status,
48                                                           country_code, postcode,
49                                                           geometry)
50                            VALUES (nextval('seq_place'), 1, %s, %s,
51                                    ST_SetSRID(ST_MakePoint(%s, %s), 4326))""",
52                         (country, postcode, x, y))
53         self.conn.commit()
54
55     @property
56     def row_set(self):
57         with self.conn.cursor() as cur:
58             cur.execute("""SELECT country_code, postcode,
59                                   ST_X(geometry), ST_Y(geometry)
60                            FROM location_postcode""")
61             return set((tuple(row) for row in cur))
62
63
64 @pytest.fixture
65 def tokenizer():
66     return dummy_tokenizer.DummyTokenizer(None)
67
68
69 @pytest.fixture
70 def postcode_table(def_config, temp_db_conn, placex_table):
71     country_info.setup_country_config(def_config)
72     return MockPostcodeTable(temp_db_conn)
73
74
75 @pytest.fixture
76 def insert_implicit_postcode(placex_table, place_row):
77     """
78         Inserts data into the placex and place table
79         which can then be used to compute one postcode.
80     """
81     def _insert_implicit_postcode(osm_id, country, geometry, address):
82         placex_table.add(osm_id=osm_id, country=country, geom=geometry)
83         place_row(osm_id=osm_id, geom='SRID=4326;'+geometry, address=address)
84
85     return _insert_implicit_postcode
86
87
88 def test_postcodes_empty(dsn, postcode_table, place_table, tokenizer):
89     postcodes.update_postcodes(dsn, None, tokenizer)
90
91     assert not postcode_table.row_set
92
93
94 def test_postcodes_add_new(dsn, postcode_table, insert_implicit_postcode, tokenizer):
95     insert_implicit_postcode(1, 'xx', 'POINT(10 12)', dict(postcode='9486'))
96     postcode_table.add('yy', '9486', 99, 34)
97
98     postcodes.update_postcodes(dsn, None, tokenizer)
99
100     assert postcode_table.row_set == {('xx', '9486', 10, 12), }
101
102
103 def test_postcodes_replace_coordinates(dsn, postcode_table, tmp_path,
104                                        insert_implicit_postcode, tokenizer):
105     insert_implicit_postcode(1, 'xx', 'POINT(10 12)', dict(postcode='AB 4511'))
106     postcode_table.add('xx', 'AB 4511', 99, 34)
107
108     postcodes.update_postcodes(dsn, tmp_path, tokenizer)
109
110     assert postcode_table.row_set == {('xx', 'AB 4511', 10, 12)}
111
112
113 def test_postcodes_replace_coordinates_close(dsn, postcode_table,
114                                              insert_implicit_postcode, tokenizer):
115     insert_implicit_postcode(1, 'xx', 'POINT(10 12)', dict(postcode='AB 4511'))
116     postcode_table.add('xx', 'AB 4511', 10, 11.99999)
117
118     postcodes.update_postcodes(dsn, None, tokenizer)
119
120     assert postcode_table.row_set == {('xx', 'AB 4511', 10, 11.99999)}
121
122
123 def test_postcodes_remove(dsn, postcode_table,
124                           insert_implicit_postcode, tokenizer):
125     insert_implicit_postcode(1, 'xx', 'POINT(10 12)', dict(postcode='AB 4511'))
126     postcode_table.add('xx', 'badname', 10, 12)
127
128     postcodes.update_postcodes(dsn, None, tokenizer)
129
130     assert postcode_table.row_set == {('xx', 'AB 4511', 10, 12)}
131
132
133 def test_postcodes_ignore_empty_country(dsn, postcode_table,
134                                         insert_implicit_postcode, tokenizer):
135     insert_implicit_postcode(1, None, 'POINT(10 12)', dict(postcode='AB 4511'))
136     postcodes.update_postcodes(dsn, None, tokenizer)
137     assert not postcode_table.row_set
138
139
140 def test_postcodes_remove_all(dsn, postcode_table, place_table, tokenizer):
141     postcode_table.add('ch', '5613', 10, 12)
142     postcodes.update_postcodes(dsn, None, tokenizer)
143
144     assert not postcode_table.row_set
145
146
147 def test_postcodes_multi_country(dsn, postcode_table,
148                                  insert_implicit_postcode, tokenizer):
149     insert_implicit_postcode(1, 'de', 'POINT(10 12)', dict(postcode='54451'))
150     insert_implicit_postcode(2, 'cc', 'POINT(100 56)', dict(postcode='DD23 T'))
151     insert_implicit_postcode(3, 'de', 'POINT(10.3 11.0)', dict(postcode='54452'))
152     insert_implicit_postcode(4, 'cc', 'POINT(10.3 11.0)', dict(postcode='54452'))
153
154     postcodes.update_postcodes(dsn, None, tokenizer)
155
156     assert postcode_table.row_set == {('de', '54451', 10, 12),
157                                       ('de', '54452', 10.3, 11.0),
158                                       ('cc', '54452', 10.3, 11.0),
159                                       ('cc', 'DD23 T', 100, 56)}
160
161
162 @pytest.mark.parametrize("gzipped", [True, False])
163 def test_postcodes_extern(dsn, postcode_table, tmp_path,
164                           insert_implicit_postcode, tokenizer, gzipped):
165     insert_implicit_postcode(1, 'xx', 'POINT(10 12)', dict(postcode='AB 4511'))
166
167     extfile = tmp_path / 'xx_postcodes.csv'
168     extfile.write_text("postcode,lat,lon\nAB 4511,-4,-1\nCD 4511,-5, -10")
169
170     if gzipped:
171         subprocess.run(['gzip', str(extfile)])
172         assert not extfile.is_file()
173
174     postcodes.update_postcodes(dsn, tmp_path, tokenizer)
175
176     assert postcode_table.row_set == {('xx', 'AB 4511', 10, 12),
177                                       ('xx', 'CD 4511', -10, -5)}
178
179
180 def test_postcodes_extern_bad_column(dsn, postcode_table, tmp_path,
181                                      insert_implicit_postcode, tokenizer):
182     insert_implicit_postcode(1, 'xx', 'POINT(10 12)', dict(postcode='AB 4511'))
183
184     extfile = tmp_path / 'xx_postcodes.csv'
185     extfile.write_text("postode,lat,lon\nAB 4511,-4,-1\nCD 4511,-5, -10")
186
187     postcodes.update_postcodes(dsn, tmp_path, tokenizer)
188
189     assert postcode_table.row_set == {('xx', 'AB 4511', 10, 12)}
190
191
192 def test_postcodes_extern_bad_number(dsn, insert_implicit_postcode,
193                                      postcode_table, tmp_path, tokenizer):
194     insert_implicit_postcode(1, 'xx', 'POINT(10 12)', dict(postcode='AB 4511'))
195
196     extfile = tmp_path / 'xx_postcodes.csv'
197     extfile.write_text("postcode,lat,lon\nXX 4511,-4,NaN\nCD 4511,-5, -10\n34,200,0")
198
199     postcodes.update_postcodes(dsn, tmp_path, tokenizer)
200
201     assert postcode_table.row_set == {('xx', 'AB 4511', 10, 12),
202                                       ('xx', 'CD 4511', -10, -5)}
203
204
205 def test_can_compute(dsn, table_factory):
206     assert not postcodes.can_compute(dsn)
207     table_factory('place')
208     assert postcodes.can_compute(dsn)
209
210
211 def test_no_placex_entry(dsn, temp_db_cursor, place_row, postcode_table, tokenizer):
212     # Rewrite the get_country_code function to verify its execution.
213     temp_db_cursor.execute("""
214         CREATE OR REPLACE FUNCTION get_country_code(place geometry)
215         RETURNS TEXT AS $$ BEGIN
216         RETURN 'yy';
217         END; $$ LANGUAGE plpgsql;
218     """)
219     place_row(geom='SRID=4326;POINT(10 12)', address=dict(postcode='AB 4511'))
220     postcodes.update_postcodes(dsn, None, tokenizer)
221
222     assert postcode_table.row_set == {('yy', 'AB 4511', 10, 12)}
223
224
225 def test_discard_badly_formatted_postcodes(dsn, temp_db_cursor, place_row,
226                                            postcode_table, tokenizer):
227     # Rewrite the get_country_code function to verify its execution.
228     temp_db_cursor.execute("""
229         CREATE OR REPLACE FUNCTION get_country_code(place geometry)
230         RETURNS TEXT AS $$ BEGIN
231         RETURN 'fr';
232         END; $$ LANGUAGE plpgsql;
233     """)
234     place_row(geom='SRID=4326;POINT(10 12)', address=dict(postcode='AB 4511'))
235     postcodes.update_postcodes(dsn, None, tokenizer)
236
237     assert not postcode_table.row_set