2 Tests for Legacy ICU tokenizer.
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
16 def test_config(def_config, tmp_path):
17 def_config.project_dir = tmp_path / 'project'
18 def_config.project_dir.mkdir()
20 sqldir = tmp_path / 'sql'
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'))
27 def_config.lib_dir.sql = sqldir
33 def tokenizer_factory(dsn, tmp_path, property_table,
34 sql_preprocessor, place_table, word_table):
35 (tmp_path / 'tokenizer').mkdir()
38 return legacy_icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
44 def db_prop(temp_db_conn):
45 def _get_db_property(name):
46 return properties.get_property(temp_db_conn, name)
48 return _get_db_property
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';")
57 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
58 tok = tokenizer_factory()
59 tok.init_new_db(test_config)
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))
73 return tok.name_analyzer()
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[],
83 OUT partial_tokens INT[])
86 partial_terms TEXT[] = '{}'::TEXT[];
91 SELECT min(word_id) INTO full_token
92 FROM word WHERE word = norm_term and class is null and country_code is null;
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;
100 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
102 IF NOT (ARRAY[term] <@ partial_terms) THEN
103 partial_terms := partial_terms || term;
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;
112 IF term_id IS NULL THEN
113 term_id := nextval('seq_word');
115 INSERT INTO word (word_id, word_token, search_name_count)
116 VALUES (term_id, term, 0);
119 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
120 partial_tokens := partial_tokens || term_id;
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""")
136 def test_init_new(tokenizer_factory, test_config, monkeypatch, db_prop):
137 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
139 tok = tokenizer_factory()
140 tok.init_new_db(test_config)
142 assert db_prop(legacy_icu_tokenizer.DBCFG_TERM_NORMALIZATION) == ':: lower();'
143 assert db_prop(legacy_icu_tokenizer.DBCFG_MAXWORDFREQ) is not None
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)
153 tok = tokenizer_factory()
154 tok.init_from_project()
156 assert tok.naming_rules is not None
157 assert tok.term_normalization == ':: lower();'
158 assert tok.max_word_frequency == '90300'
161 def test_update_sql_functions(db_prop, temp_db_cursor,
162 tokenizer_factory, test_config, table_factory,
164 monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '1133')
165 tok = tokenizer_factory()
166 tok.init_new_db(test_config)
169 assert db_prop(legacy_icu_tokenizer.DBCFG_MAXWORDFREQ) == '1133'
171 table_factory('test', 'txt TEXT')
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}}')""")
176 tok.update_sql_functions(test_config)
178 test_content = temp_db_cursor.row_set('SELECT * FROM test')
179 assert test_content == set((('1133', ), ))
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'
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',)))
192 with analyzer() as anl:
193 anl.update_postcodes_from_db()
195 assert word_table.count() == 3
196 assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
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')
205 with analyzer() as anl:
206 anl.update_postcodes_from_db()
208 assert word_table.count() == 3
209 assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
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")
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')}
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)
230 assert word_table.count_special() == 2
232 with analyzer() as anl:
233 anl.update_special_phrases([], True)
235 assert word_table.count_special() == 0
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)
242 assert word_table.count_special() == 2
244 with analyzer() as anl:
245 anl.update_special_phrases([], False)
247 assert word_table.count_special() == 2
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)
254 assert word_table.count_special() == 2
256 with analyzer() as anl:
257 anl.update_special_phrases([
258 ('prison', 'amenity', 'prison', 'in'),
259 ('bar', 'highway', 'road', '-'),
260 ('garden', 'leisure', 'garden', 'near')
263 assert word_table.get_special() \
264 == {(' PRISON', 'prison', 'amenity', 'prison', 'in'),
265 (' BAR', 'bar', 'highway', 'road', None),
266 (' GARDEN', 'garden', 'leisure', 'garden', 'near')}
269 class TestPlaceNames:
271 @pytest.fixture(autouse=True)
272 def setup(self, analyzer, getorcreate_full_word):
273 with analyzer() as anl:
278 def expect_name_terms(self, info, *expected_terms):
279 tokens = self.analyzer.get_word_token_info(expected_terms)
281 assert token[2] is not None, "No token for {0}".format(token)
283 assert eval(info['names']) == set((t[2] for t in tokens))
286 def test_simple_names(self):
287 info = self.analyzer.process_place({'name' : {'name' : 'Soft bAr', 'ref': '34'}})
289 self.expect_name_terms(info, '#Soft bAr', '#34','Soft', 'bAr', '34')
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'))}})
296 self.expect_name_terms(info, '#New York', '#Big Apple',
297 'new', 'york', 'big', 'apple')
300 def test_full_names_with_bracket(self):
301 info = self.analyzer.process_place({'name' : {'name' : 'Houseboat (left)'}})
303 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
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}})
312 assert word_table.get_postcodes() == {pcode, }
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}})
320 assert not word_table.get_postcodes()
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}})
328 assert info['hnr'] == hnr.upper()
329 assert info['hnr_tokens'] == "{-1}"
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'}})
336 assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
337 assert info['hnr_tokens'] == "{-1,-2,-3}"
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'}})
346 assert set(info['hnr'].split(';')) == set(('134', '99A'))
347 assert info['hnr_tokens'] == "{-1,-2}"