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_word_table(tokenizer_factory, test_config, place_row, word_table):
147 place_row(names={'name' : 'Test Area', 'ref' : '52'})
148 place_row(names={'name' : 'No Area'})
149 place_row(names={'name' : 'Holzstrasse'})
151 tok = tokenizer_factory()
152 tok.init_new_db(test_config)
154 assert word_table.get_partial_words() == {('te', 1), ('st', 1), ('52', 1),
155 ('no', 1), ('area', 2),
156 ('holz', 1), ('strasse', 1),
160 def test_init_from_project(monkeypatch, test_config, tokenizer_factory):
161 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
162 monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '90300')
163 tok = tokenizer_factory()
164 tok.init_new_db(test_config)
167 tok = tokenizer_factory()
168 tok.init_from_project()
170 assert tok.naming_rules is not None
171 assert tok.term_normalization == ':: lower();'
172 assert tok.max_word_frequency == '90300'
175 def test_update_sql_functions(db_prop, temp_db_cursor,
176 tokenizer_factory, test_config, table_factory,
178 monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '1133')
179 tok = tokenizer_factory()
180 tok.init_new_db(test_config)
183 assert db_prop(legacy_icu_tokenizer.DBCFG_MAXWORDFREQ) == '1133'
185 table_factory('test', 'txt TEXT')
187 func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_icu_tokenizer.sql'
188 func_file.write_text("""INSERT INTO test VALUES ('{{max_word_freq}}')""")
190 tok.update_sql_functions(test_config)
192 test_content = temp_db_cursor.row_set('SELECT * FROM test')
193 assert test_content == set((('1133', ), ))
196 def test_normalize_postcode(analyzer):
197 with analyzer() as anl:
198 anl.normalize_postcode('123') == '123'
199 anl.normalize_postcode('ab-34 ') == 'AB-34'
200 anl.normalize_postcode('38 Б') == '38 Б'
203 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
204 table_factory('location_postcode', 'postcode TEXT',
205 content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
207 with analyzer() as anl:
208 anl.update_postcodes_from_db()
210 assert word_table.count() == 3
211 assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
214 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
215 table_factory('location_postcode', 'postcode TEXT',
216 content=(('1234',), ('45BC', ), ('XX45', )))
217 word_table.add_postcode(' 1234', '1234')
218 word_table.add_postcode(' 5678', '5678')
220 with analyzer() as anl:
221 anl.update_postcodes_from_db()
223 assert word_table.count() == 3
224 assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
227 def test_update_special_phrase_empty_table(analyzer, word_table):
228 with analyzer() as anl:
229 anl.update_special_phrases([
230 ("König bei", "amenity", "royal", "near"),
231 ("Könige ", "amenity", "royal", "-"),
232 ("street", "highway", "primary", "in")
235 assert word_table.get_special() \
236 == {(' KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
237 (' KÖNIGE', 'Könige', 'amenity', 'royal', None),
238 (' STREET', 'street', 'highway', 'primary', 'in')}
241 def test_update_special_phrase_delete_all(analyzer, word_table):
242 word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
243 word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
245 assert word_table.count_special() == 2
247 with analyzer() as anl:
248 anl.update_special_phrases([], True)
250 assert word_table.count_special() == 0
253 def test_update_special_phrases_no_replace(analyzer, word_table):
254 word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
255 word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
257 assert word_table.count_special() == 2
259 with analyzer() as anl:
260 anl.update_special_phrases([], False)
262 assert word_table.count_special() == 2
265 def test_update_special_phrase_modify(analyzer, word_table):
266 word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
267 word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
269 assert word_table.count_special() == 2
271 with analyzer() as anl:
272 anl.update_special_phrases([
273 ('prison', 'amenity', 'prison', 'in'),
274 ('bar', 'highway', 'road', '-'),
275 ('garden', 'leisure', 'garden', 'near')
278 assert word_table.get_special() \
279 == {(' PRISON', 'prison', 'amenity', 'prison', 'in'),
280 (' BAR', 'bar', 'highway', 'road', None),
281 (' GARDEN', 'garden', 'leisure', 'garden', 'near')}
284 def test_add_country_names_new(analyzer, word_table):
285 with analyzer() as anl:
286 anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
288 assert word_table.get_country() == {('es', ' ESPAGÑA'), ('es', ' SPAIN')}
291 def test_add_country_names_extend(analyzer, word_table):
292 word_table.add_country('ch', ' SCHWEIZ')
294 with analyzer() as anl:
295 anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
297 assert word_table.get_country() == {('ch', ' SCHWEIZ'), ('ch', ' SUISSE')}
300 class TestPlaceNames:
302 @pytest.fixture(autouse=True)
303 def setup(self, analyzer, getorcreate_full_word):
304 with analyzer() as anl:
309 def expect_name_terms(self, info, *expected_terms):
310 tokens = self.analyzer.get_word_token_info(expected_terms)
312 assert token[2] is not None, "No token for {0}".format(token)
314 assert eval(info['names']) == set((t[2] for t in tokens))
317 def test_simple_names(self):
318 info = self.analyzer.process_place({'name': {'name': 'Soft bAr', 'ref': '34'}})
320 self.expect_name_terms(info, '#Soft bAr', '#34','Soft', 'bAr', '34')
323 @pytest.mark.parametrize('sep', [',' , ';'])
324 def test_names_with_separator(self, sep):
325 info = self.analyzer.process_place({'name': {'name': sep.join(('New York', 'Big Apple'))}})
327 self.expect_name_terms(info, '#New York', '#Big Apple',
328 'new', 'york', 'big', 'apple')
331 def test_full_names_with_bracket(self):
332 info = self.analyzer.process_place({'name': {'name': 'Houseboat (left)'}})
334 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
338 def test_country_name(self, word_table):
339 info = self.analyzer.process_place({'name': {'name': 'Norge'},
340 'country_feature': 'no'})
342 self.expect_name_terms(info, '#norge', 'norge')
343 assert word_table.get_country() == {('no', ' NORGE')}
346 class TestPlaceAddress:
348 @pytest.fixture(autouse=True)
349 def setup(self, analyzer, getorcreate_full_word):
350 with analyzer(trans=(":: upper()", "'🜵' > ' '")) as anl:
355 def process_address(self, **kwargs):
356 return self.analyzer.process_place({'address': kwargs})
359 def name_token_set(self, *expected_terms):
360 tokens = self.analyzer.get_word_token_info(expected_terms)
362 assert token[2] is not None, "No token for {0}".format(token)
364 return set((t[2] for t in tokens))
367 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
368 def test_process_place_postcode(self, word_table, pcode):
369 self.process_address(postcode=pcode)
371 assert word_table.get_postcodes() == {pcode, }
374 @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
375 def test_process_place_bad_postcode(self, word_table, pcode):
376 self.process_address(postcode=pcode)
378 assert not word_table.get_postcodes()
381 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
382 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
383 info = self.process_address(housenumber=hnr)
385 assert info['hnr'] == hnr.upper()
386 assert info['hnr_tokens'] == "{-1}"
389 def test_process_place_housenumbers_lists(self, getorcreate_hnr_id):
390 info = self.process_address(conscriptionnumber='1; 2;3')
392 assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
393 assert info['hnr_tokens'] == "{-1,-2,-3}"
396 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
397 info = self.process_address(housenumber='134',
398 conscriptionnumber='134',
401 assert set(info['hnr'].split(';')) == set(('134', '99A'))
402 assert info['hnr_tokens'] == "{-1,-2}"
405 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
406 info = self.process_address(housenumber="45")
407 assert info['hnr_tokens'] == "{-1}"
409 info = self.process_address(housenumber="46")
410 assert info['hnr_tokens'] == "{-2}"
412 info = self.process_address(housenumber="41;45")
413 assert eval(info['hnr_tokens']) == {-1, -3}
415 info = self.process_address(housenumber="41")
416 assert eval(info['hnr_tokens']) == {-3}
419 def test_process_place_street(self):
420 info = self.process_address(street='Grand Road')
422 assert eval(info['street']) == self.name_token_set('#GRAND ROAD')
425 def test_process_place_street_empty(self):
426 info = self.process_address(street='🜵')
428 assert 'street' not in info
431 def test_process_place_place(self):
432 info = self.process_address(place='Honu Lulu')
434 assert eval(info['place_search']) == self.name_token_set('#HONU LULU',
436 assert eval(info['place_match']) == self.name_token_set('#HONU LULU')
439 def test_process_place_place_empty(self):
440 info = self.process_address(place='🜵')
442 assert 'place_search' not in info
443 assert 'place_match' not in info
446 def test_process_place_address_terms(self):
447 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
448 suburb='Zwickau', street='Hauptstr',
449 full='right behind the church')
451 city_full = self.name_token_set('#ZWICKAU')
452 city_all = self.name_token_set('#ZWICKAU', 'ZWICKAU')
453 state_full = self.name_token_set('#SACHSEN')
454 state_all = self.name_token_set('#SACHSEN', 'SACHSEN')
456 result = {k: [eval(v[0]), eval(v[1])] for k,v in info['addr'].items()}
458 assert result == {'city': [city_all, city_full],
459 'suburb': [city_all, city_full],
460 'state': [state_all, state_full]}
463 def test_process_place_address_terms_empty(self):
464 info = self.process_address(country='de', city=' ', street='Hauptstr',
465 full='right behind the church')
467 assert 'addr' not in info