]> git.openstreetmap.org Git - nominatim.git/blob - test/python/test_tokenizer_legacy_icu.py
Merge pull request #2324 from lonvia/generic-external-postcodes
[nominatim.git] / test / python / test_tokenizer_legacy_icu.py
1 """
2 Tests for Legacy ICU tokenizer.
3 """
4 import shutil
5
6 import pytest
7
8 from nominatim.tokenizer import legacy_icu_tokenizer
9 from nominatim.db import properties
10
11
12 @pytest.fixture
13 def test_config(def_config, tmp_path):
14     def_config.project_dir = tmp_path / 'project'
15     def_config.project_dir.mkdir()
16
17     sqldir = tmp_path / 'sql'
18     sqldir.mkdir()
19     (sqldir / 'tokenizer').mkdir()
20     (sqldir / 'tokenizer' / 'legacy_icu_tokenizer.sql').write_text("SELECT 'a'")
21     shutil.copy(str(def_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer_tables.sql'),
22                 str(sqldir / 'tokenizer' / 'legacy_tokenizer_tables.sql'))
23
24     def_config.lib_dir.sql = sqldir
25
26     return def_config
27
28
29 @pytest.fixture
30 def tokenizer_factory(dsn, tmp_path, property_table,
31                       sql_preprocessor, place_table, word_table):
32     (tmp_path / 'tokenizer').mkdir()
33
34     def _maker():
35         return legacy_icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
36
37     return _maker
38
39
40 @pytest.fixture
41 def db_prop(temp_db_conn):
42     def _get_db_property(name):
43         return properties.get_property(temp_db_conn,
44                                        getattr(legacy_icu_tokenizer, name))
45
46     return _get_db_property
47
48 @pytest.fixture
49 def tokenizer_setup(tokenizer_factory, test_config, monkeypatch, sql_preprocessor):
50     tok = tokenizer_factory()
51     tok.init_new_db(test_config)
52
53
54 @pytest.fixture
55 def analyzer(tokenizer_factory, test_config, monkeypatch, sql_preprocessor,
56              word_table, temp_db_with_extensions, tmp_path):
57     sql = tmp_path / 'sql' / 'tokenizer' / 'legacy_icu_tokenizer.sql'
58     sql.write_text("SELECT 'a';")
59
60     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
61     tok = tokenizer_factory()
62     tok.init_new_db(test_config)
63     monkeypatch.undo()
64
65     def _mk_analyser(trans=':: upper();', abbr=(('STREET', 'ST'), )):
66         tok.transliteration = trans
67         tok.abbreviations = abbr
68
69         return tok.name_analyzer()
70
71     return _mk_analyser
72
73
74 @pytest.fixture
75 def getorcreate_term_id(temp_db_cursor):
76     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_term_id(lookup_term TEXT)
77                               RETURNS INTEGER AS $$ SELECT nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
78
79
80 @pytest.fixture
81 def getorcreate_hnr_id(temp_db_cursor):
82     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
83                               RETURNS INTEGER AS $$ SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
84
85
86 def test_init_new(tokenizer_factory, test_config, monkeypatch, db_prop,
87                   sql_preprocessor, place_table, word_table):
88     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
89
90     tok = tokenizer_factory()
91     tok.init_new_db(test_config)
92
93     assert db_prop('DBCFG_NORMALIZATION') == ':: lower();'
94     assert db_prop('DBCFG_TRANSLITERATION') is not None
95     assert db_prop('DBCFG_ABBREVIATIONS') is not None
96
97
98 def test_init_from_project(tokenizer_setup, tokenizer_factory):
99     tok = tokenizer_factory()
100
101     tok.init_from_project()
102
103     assert tok.normalization is not None
104     assert tok.transliteration is not None
105     assert tok.abbreviations is not None
106
107
108 def test_update_sql_functions(temp_db_conn, db_prop, temp_db_cursor,
109                               tokenizer_factory, test_config, table_factory,
110                               monkeypatch,
111                               sql_preprocessor, place_table, word_table):
112     monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '1133')
113     tok = tokenizer_factory()
114     tok.init_new_db(test_config)
115     monkeypatch.undo()
116
117     assert db_prop('DBCFG_MAXWORDFREQ') == '1133'
118
119     table_factory('test', 'txt TEXT')
120
121     func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_icu_tokenizer.sql'
122     func_file.write_text("""INSERT INTO test VALUES ('{{max_word_freq}}')""")
123
124     tok.update_sql_functions(test_config)
125
126     test_content = temp_db_cursor.row_set('SELECT * FROM test')
127     assert test_content == set((('1133', ), ))
128
129
130 def test_make_standard_word(analyzer):
131     with analyzer(abbr=(('STREET', 'ST'), ('tiny', 't'))) as a:
132         assert a.make_standard_word('tiny street') == 'TINY ST'
133
134     with analyzer(abbr=(('STRASSE', 'STR'), ('STR', 'ST'))) as a:
135         assert a.make_standard_word('Hauptstrasse') == 'HAUPTST'
136
137
138 def test_make_standard_hnr(analyzer):
139     with analyzer(abbr=(('IV', '4'),)) as a:
140         assert a._make_standard_hnr('345') == '345'
141         assert a._make_standard_hnr('iv') == 'IV'
142
143
144 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
145     table_factory('location_postcode', 'postcode TEXT',
146                   content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
147
148     with analyzer() as a:
149         a.update_postcodes_from_db()
150
151     assert word_table.count() == 3
152     assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
153
154
155 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
156     table_factory('location_postcode', 'postcode TEXT',
157                   content=(('1234',), ('45BC', ), ('XX45', )))
158     word_table.add_postcode(' 1234', '1234')
159     word_table.add_postcode(' 5678', '5678')
160
161     with analyzer() as a:
162         a.update_postcodes_from_db()
163
164     assert word_table.count() == 3
165     assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
166
167
168 def test_update_special_phrase_empty_table(analyzer, word_table, temp_db_cursor):
169     with analyzer() as a:
170         a.update_special_phrases([
171             ("König bei", "amenity", "royal", "near"),
172             ("Könige", "amenity", "royal", "-"),
173             ("street", "highway", "primary", "in")
174         ])
175
176     assert temp_db_cursor.row_set("""SELECT word_token, word, class, type, operator
177                                      FROM word WHERE class != 'place'""") \
178                == set(((' KÖNIG BEI', 'könig bei', 'amenity', 'royal', 'near'),
179                        (' KÖNIGE', 'könige', 'amenity', 'royal', None),
180                        (' ST', 'street', 'highway', 'primary', 'in')))
181
182
183 def test_update_special_phrase_delete_all(analyzer, word_table, temp_db_cursor):
184     temp_db_cursor.execute("""INSERT INTO word (word_token, word, class, type, operator)
185                               VALUES (' FOO', 'foo', 'amenity', 'prison', 'in'),
186                                      (' BAR', 'bar', 'highway', 'road', null)""")
187
188     assert 2 == temp_db_cursor.scalar("SELECT count(*) FROM word WHERE class != 'place'""")
189
190     with analyzer() as a:
191         a.update_special_phrases([])
192
193     assert 0 == temp_db_cursor.scalar("SELECT count(*) FROM word WHERE class != 'place'""")
194
195
196 def test_update_special_phrase_modify(analyzer, word_table, temp_db_cursor):
197     temp_db_cursor.execute("""INSERT INTO word (word_token, word, class, type, operator)
198                               VALUES (' FOO', 'foo', 'amenity', 'prison', 'in'),
199                                      (' BAR', 'bar', 'highway', 'road', null)""")
200
201     assert 2 == temp_db_cursor.scalar("SELECT count(*) FROM word WHERE class != 'place'""")
202
203     with analyzer() as a:
204         a.update_special_phrases([
205           ('prison', 'amenity', 'prison', 'in'),
206           ('bar', 'highway', 'road', '-'),
207           ('garden', 'leisure', 'garden', 'near')
208         ])
209
210     assert temp_db_cursor.row_set("""SELECT word_token, word, class, type, operator
211                                      FROM word WHERE class != 'place'""") \
212                == set(((' PRISON', 'prison', 'amenity', 'prison', 'in'),
213                        (' BAR', 'bar', 'highway', 'road', None),
214                        (' GARDEN', 'garden', 'leisure', 'garden', 'near')))
215
216
217 def test_process_place_names(analyzer, getorcreate_term_id):
218
219     with analyzer() as a:
220         info = a.process_place({'name' : {'name' : 'Soft bAr', 'ref': '34'}})
221
222     assert info['names'] == '{1,2,3,4,5,6}'
223
224
225 @pytest.mark.parametrize('pc', ['12345', 'AB 123', '34-345'])
226 def test_process_place_postcode(analyzer, word_table, pc):
227     with analyzer() as a:
228         info = a.process_place({'address': {'postcode' : pc}})
229
230     assert word_table.get_postcodes() == {pc, }
231
232
233 @pytest.mark.parametrize('pc', ['12:23', 'ab;cd;f', '123;836'])
234 def test_process_place_bad_postcode(analyzer, word_table, pc):
235     with analyzer() as a:
236         info = a.process_place({'address': {'postcode' : pc}})
237
238     assert not word_table.get_postcodes()
239
240
241 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
242 def test_process_place_housenumbers_simple(analyzer, hnr, getorcreate_hnr_id):
243     with analyzer() as a:
244         info = a.process_place({'address': {'housenumber' : hnr}})
245
246     assert info['hnr'] == hnr.upper()
247     assert info['hnr_tokens'] == "{-1}"
248
249
250 def test_process_place_housenumbers_lists(analyzer, getorcreate_hnr_id):
251     with analyzer() as a:
252         info = a.process_place({'address': {'conscriptionnumber' : '1; 2;3'}})
253
254     assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
255     assert info['hnr_tokens'] == "{-1,-2,-3}"
256
257
258 def test_process_place_housenumbers_duplicates(analyzer, getorcreate_hnr_id):
259     with analyzer() as a:
260         info = a.process_place({'address': {'housenumber' : '134',
261                                                'conscriptionnumber' : '134',
262                                                'streetnumber' : '99a'}})
263
264     assert set(info['hnr'].split(';')) == set(('134', '99A'))
265     assert info['hnr_tokens'] == "{-1,-2}"