]> git.openstreetmap.org Git - nominatim.git/blob - test/python/test_tokenizer_legacy_icu.py
adapt tests for ICU tokenizer
[nominatim.git] / test / python / test_tokenizer_legacy_icu.py
1 """
2 Tests for Legacy ICU tokenizer.
3 """
4 import shutil
5 import yaml
6
7 import pytest
8
9 from nominatim.tokenizer import legacy_icu_tokenizer
10 from nominatim.tokenizer.icu_name_processor import ICUNameProcessorRules
11 from nominatim.tokenizer.icu_rule_loader import ICURuleLoader
12 from nominatim.db import properties
13
14
15 @pytest.fixture
16 def test_config(def_config, tmp_path):
17     def_config.project_dir = tmp_path / 'project'
18     def_config.project_dir.mkdir()
19
20     sqldir = tmp_path / 'sql'
21     sqldir.mkdir()
22     (sqldir / 'tokenizer').mkdir()
23     (sqldir / 'tokenizer' / 'legacy_icu_tokenizer.sql').write_text("SELECT 'a'")
24     shutil.copy(str(def_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer_tables.sql'),
25                 str(sqldir / 'tokenizer' / 'legacy_tokenizer_tables.sql'))
26
27     def_config.lib_dir.sql = sqldir
28
29     return def_config
30
31
32 @pytest.fixture
33 def tokenizer_factory(dsn, tmp_path, property_table,
34                       sql_preprocessor, place_table, word_table):
35     (tmp_path / 'tokenizer').mkdir()
36
37     def _maker():
38         return legacy_icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
39
40     return _maker
41
42
43 @pytest.fixture
44 def db_prop(temp_db_conn):
45     def _get_db_property(name):
46         return properties.get_property(temp_db_conn, name)
47
48     return _get_db_property
49
50
51 @pytest.fixture
52 def analyzer(tokenizer_factory, test_config, monkeypatch,
53              temp_db_with_extensions, tmp_path):
54     sql = tmp_path / 'sql' / 'tokenizer' / 'legacy_icu_tokenizer.sql'
55     sql.write_text("SELECT 'a';")
56
57     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
58     tok = tokenizer_factory()
59     tok.init_new_db(test_config)
60     monkeypatch.undo()
61
62     def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
63                      suffixes=('gasse', ), abbr=('street => st', )):
64         cfgfile = tmp_path / 'analyser_test_config.yaml'
65         with cfgfile.open('w') as stream:
66             cfgstr = {'normalization' : list(norm),
67                        'transliteration' : list(trans),
68                        'compound_suffixes' : list(suffixes),
69                        'abbreviations' : list(abbr)}
70             yaml.dump(cfgstr, stream)
71         tok.naming_rules = ICUNameProcessorRules(loader=ICURuleLoader(cfgfile))
72
73         return tok.name_analyzer()
74
75     return _mk_analyser
76
77
78 @pytest.fixture
79 def getorcreate_full_word(temp_db_cursor):
80     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
81                                                  norm_term TEXT, lookup_terms TEXT[],
82                                                  OUT full_token INT,
83                                                  OUT partial_tokens INT[])
84   AS $$
85 DECLARE
86   partial_terms TEXT[] = '{}'::TEXT[];
87   term TEXT;
88   term_id INTEGER;
89   term_count INTEGER;
90 BEGIN
91   SELECT min(word_id) INTO full_token
92     FROM word WHERE word = norm_term and class is null and country_code is null;
93
94   IF full_token IS NULL THEN
95     full_token := nextval('seq_word');
96     INSERT INTO word (word_id, word_token, word, search_name_count)
97       SELECT full_token, ' ' || lookup_term, norm_term, 0 FROM unnest(lookup_terms) as lookup_term;
98   END IF;
99
100   FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
101     term := trim(term);
102     IF NOT (ARRAY[term] <@ partial_terms) THEN
103       partial_terms := partial_terms || term;
104     END IF;
105   END LOOP;
106
107   partial_tokens := '{}'::INT[];
108   FOR term IN SELECT unnest(partial_terms) LOOP
109     SELECT min(word_id), max(search_name_count) INTO term_id, term_count
110       FROM word WHERE word_token = term and class is null and country_code is null;
111
112     IF term_id IS NULL THEN
113       term_id := nextval('seq_word');
114       term_count := 0;
115       INSERT INTO word (word_id, word_token, search_name_count)
116         VALUES (term_id, term, 0);
117     END IF;
118
119     IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
120         partial_tokens := partial_tokens || term_id;
121     END IF;
122   END LOOP;
123 END;
124 $$
125 LANGUAGE plpgsql;
126                               """)
127
128
129 @pytest.fixture
130 def getorcreate_hnr_id(temp_db_cursor):
131     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
132                               RETURNS INTEGER AS $$
133                                 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
134
135
136 def test_init_new(tokenizer_factory, test_config, monkeypatch, db_prop):
137     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
138
139     tok = tokenizer_factory()
140     tok.init_new_db(test_config)
141
142     assert db_prop(legacy_icu_tokenizer.DBCFG_TERM_NORMALIZATION) == ':: lower();'
143     assert db_prop(legacy_icu_tokenizer.DBCFG_MAXWORDFREQ) is not None
144
145
146 def test_init_from_project(monkeypatch, test_config, tokenizer_factory):
147     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
148     monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '90300')
149     tok = tokenizer_factory()
150     tok.init_new_db(test_config)
151     monkeypatch.undo()
152
153     tok = tokenizer_factory()
154     tok.init_from_project()
155
156     assert tok.naming_rules is not None
157     assert tok.term_normalization == ':: lower();'
158     assert tok.max_word_frequency == '90300'
159
160
161 def test_update_sql_functions(db_prop, temp_db_cursor,
162                               tokenizer_factory, test_config, table_factory,
163                               monkeypatch):
164     monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '1133')
165     tok = tokenizer_factory()
166     tok.init_new_db(test_config)
167     monkeypatch.undo()
168
169     assert db_prop(legacy_icu_tokenizer.DBCFG_MAXWORDFREQ) == '1133'
170
171     table_factory('test', 'txt TEXT')
172
173     func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_icu_tokenizer.sql'
174     func_file.write_text("""INSERT INTO test VALUES ('{{max_word_freq}}')""")
175
176     tok.update_sql_functions(test_config)
177
178     test_content = temp_db_cursor.row_set('SELECT * FROM test')
179     assert test_content == set((('1133', ), ))
180
181
182 def test_make_standard_hnr(analyzer):
183     with analyzer(abbr=('IV => 4',)) as anl:
184         assert anl._make_standard_hnr('345') == '345'
185         assert anl._make_standard_hnr('iv') == 'IV'
186
187
188 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
189     table_factory('location_postcode', 'postcode TEXT',
190                   content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
191
192     with analyzer() as anl:
193         anl.update_postcodes_from_db()
194
195     assert word_table.count() == 3
196     assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
197
198
199 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
200     table_factory('location_postcode', 'postcode TEXT',
201                   content=(('1234',), ('45BC', ), ('XX45', )))
202     word_table.add_postcode(' 1234', '1234')
203     word_table.add_postcode(' 5678', '5678')
204
205     with analyzer() as anl:
206         anl.update_postcodes_from_db()
207
208     assert word_table.count() == 3
209     assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
210
211
212 def test_update_special_phrase_empty_table(analyzer, word_table):
213     with analyzer() as anl:
214         anl.update_special_phrases([
215             ("König bei", "amenity", "royal", "near"),
216             ("Könige", "amenity", "royal", "-"),
217             ("street", "highway", "primary", "in")
218         ], True)
219
220     assert word_table.get_special() \
221                == {(' KÖNIG BEI', 'könig bei', 'amenity', 'royal', 'near'),
222                    (' KÖNIGE', 'könige', 'amenity', 'royal', None),
223                    (' STREET', 'street', 'highway', 'primary', 'in')}
224
225
226 def test_update_special_phrase_delete_all(analyzer, word_table):
227     word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
228     word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
229
230     assert word_table.count_special() == 2
231
232     with analyzer() as anl:
233         anl.update_special_phrases([], True)
234
235     assert word_table.count_special() == 0
236
237
238 def test_update_special_phrases_no_replace(analyzer, word_table):
239     word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
240     word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
241
242     assert word_table.count_special() == 2
243
244     with analyzer() as anl:
245         anl.update_special_phrases([], False)
246
247     assert word_table.count_special() == 2
248
249
250 def test_update_special_phrase_modify(analyzer, word_table):
251     word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
252     word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
253
254     assert word_table.count_special() == 2
255
256     with analyzer() as anl:
257         anl.update_special_phrases([
258             ('prison', 'amenity', 'prison', 'in'),
259             ('bar', 'highway', 'road', '-'),
260             ('garden', 'leisure', 'garden', 'near')
261         ], True)
262
263     assert word_table.get_special() \
264                == {(' PRISON', 'prison', 'amenity', 'prison', 'in'),
265                    (' BAR', 'bar', 'highway', 'road', None),
266                    (' GARDEN', 'garden', 'leisure', 'garden', 'near')}
267
268
269 class TestPlaceNames:
270
271     @pytest.fixture(autouse=True)
272     def setup(self, analyzer, getorcreate_full_word):
273         with analyzer() as anl:
274             self.analyzer = anl
275             yield anl
276
277
278     def expect_name_terms(self, info, *expected_terms):
279         tokens = self.analyzer.get_word_token_info(expected_terms)
280         for token in tokens:
281             assert token[2] is not None, "No token for {0}".format(token)
282
283         assert eval(info['names']) == set((t[2] for t in tokens))
284
285
286     def test_simple_names(self):
287         info = self.analyzer.process_place({'name' : {'name' : 'Soft bAr', 'ref': '34'}})
288
289         self.expect_name_terms(info, '#Soft bAr', '#34','Soft', 'bAr', '34')
290
291
292     @pytest.mark.parametrize('sep', [',' , ';'])
293     def test_names_with_separator(self, sep):
294         info = self.analyzer.process_place({'name' : {'name' : sep.join(('New York', 'Big Apple'))}})
295
296         self.expect_name_terms(info, '#New York', '#Big Apple',
297                                      'new', 'york', 'big', 'apple')
298
299
300     def test_full_names_with_bracket(self):
301         info = self.analyzer.process_place({'name' : {'name' : 'Houseboat (left)'}})
302
303         self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
304                                      'houseboat', 'left')
305
306
307 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
308 def test_process_place_postcode(analyzer, word_table, pcode):
309     with analyzer() as anl:
310         anl.process_place({'address': {'postcode' : pcode}})
311
312     assert word_table.get_postcodes() == {pcode, }
313
314
315 @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
316 def test_process_place_bad_postcode(analyzer, word_table, pcode):
317     with analyzer() as anl:
318         anl.process_place({'address': {'postcode' : pcode}})
319
320     assert not word_table.get_postcodes()
321
322
323 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
324 def test_process_place_housenumbers_simple(analyzer, hnr, getorcreate_hnr_id):
325     with analyzer() as anl:
326         info = anl.process_place({'address': {'housenumber' : hnr}})
327
328     assert info['hnr'] == hnr.upper()
329     assert info['hnr_tokens'] == "{-1}"
330
331
332 def test_process_place_housenumbers_lists(analyzer, getorcreate_hnr_id):
333     with analyzer() as anl:
334         info = anl.process_place({'address': {'conscriptionnumber' : '1; 2;3'}})
335
336     assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
337     assert info['hnr_tokens'] == "{-1,-2,-3}"
338
339
340 def test_process_place_housenumbers_duplicates(analyzer, getorcreate_hnr_id):
341     with analyzer() as anl:
342         info = anl.process_place({'address': {'housenumber' : '134',
343                                               'conscriptionnumber' : '134',
344                                               'streetnumber' : '99a'}})
345
346     assert set(info['hnr'].split(';')) == set(('134', '99A'))
347     assert info['hnr_tokens'] == "{-1,-2}"