1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2026 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Tests for ICU tokenizer.
15 from nominatim_db.tokenizer import icu_tokenizer
16 import nominatim_db.tokenizer.icu_rule_loader
17 from nominatim_db.db import properties
18 from nominatim_db.data.place_info import PlaceInfo
19 from nominatim_db.data.place_name import PlaceName
20 from nominatim_db.tokenizer.place_sanitizer import PlaceSanitizer
22 from mock_icu_word_table import MockIcuWordTable
26 def word_table(temp_db_conn):
27 return MockIcuWordTable(temp_db_conn)
31 def test_config(project_env, tmp_path):
32 sqldir = tmp_path / 'sql'
34 (sqldir / 'tokenizer').mkdir()
35 (sqldir / 'tokenizer' / 'icu_tokenizer.sql').write_text("SELECT 'a'", encoding='utf-8')
37 project_env.lib_dir.sql = sqldir
43 def tokenizer_factory(dsn, property_table, sql_preprocessor, place_table, word_table):
45 return icu_tokenizer.create(dsn)
51 def db_prop(temp_db_conn):
52 def _get_db_property(name):
53 return properties.get_property(temp_db_conn, name)
55 return _get_db_property
59 def analyzer(tokenizer_factory, test_config, monkeypatch,
60 temp_db_with_extensions, tmp_path):
61 sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
62 sql.write_text("SELECT 'a';", encoding='utf-8')
64 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
65 tok = tokenizer_factory()
66 tok.init_new_db(test_config)
69 def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
70 variants=('~gasse -> gasse', 'street => st', ),
71 with_housenumber=False,
73 cfgstr = {'normalization': list(norm),
74 'transliteration': list(trans),
75 'token-analysis': [{'analyzer': 'generic',
76 'variants': [{'words': list(variants)}]}]}
78 cfgstr['token-analysis'].append({'id': '@housenumber',
79 'analyzer': 'housenumbers'})
81 cfgstr['token-analysis'].append({'id': '@postcode',
82 'analyzer': 'postcodes'})
83 (test_config.project_dir / 'icu_tokenizer.yaml').write_text(
84 yaml.dump(cfgstr), encoding='utf-8')
85 tok.loader = nominatim_db.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
87 return tok.name_analyzer()
93 def sql_functions(load_sql):
94 load_sql('functions/utils.sql')
95 load_sql('tokenizer/icu_tokenizer.sql')
99 def getorcreate_full_word(temp_db_cursor):
100 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
101 norm_term TEXT, lookup_terms TEXT[],
103 OUT partial_tokens INT[])
106 partial_terms TEXT[] = '{}'::TEXT[];
111 SELECT min(word_id) INTO full_token
112 FROM word WHERE info->>'word' = norm_term and type = 'W';
114 IF full_token IS NULL THEN
115 full_token := nextval('seq_word');
116 INSERT INTO word (word_id, word_token, type, info)
117 SELECT full_token, lookup_term, 'W',
118 json_build_object('word', norm_term, 'count', 0)
119 FROM unnest(lookup_terms) as lookup_term;
122 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
124 IF NOT (ARRAY[term] <@ partial_terms) THEN
125 partial_terms := partial_terms || term;
129 partial_tokens := '{}'::INT[];
130 FOR term IN SELECT unnest(partial_terms) LOOP
131 SELECT min(word_id), max(info->>'count') INTO term_id, term_count
132 FROM word WHERE word_token = term and type = 'w';
134 IF term_id IS NULL THEN
135 term_id := nextval('seq_word');
137 INSERT INTO word (word_id, word_token, type, info)
138 VALUES (term_id, term, 'w', json_build_object('count', term_count));
141 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
142 partial_tokens := partial_tokens || term_id;
151 def test_init_new(tokenizer_factory, test_config, db_prop):
152 tok = tokenizer_factory()
153 tok.init_new_db(test_config)
155 prop = db_prop(nominatim_db.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES)
157 assert prop.startswith(':: lower ();')
160 def test_init_word_table(tokenizer_factory, test_config, place_row, temp_db_cursor):
161 place_row(names={'name': 'Test Area', 'ref': '52'})
162 place_row(names={'name': 'No Area'})
163 place_row(names={'name': 'Holzstrasse'})
165 tok = tokenizer_factory()
166 tok.init_new_db(test_config)
168 assert temp_db_cursor.table_exists('word')
171 def test_init_from_project(test_config, tokenizer_factory):
172 tok = tokenizer_factory()
173 tok.init_new_db(test_config)
175 tok = tokenizer_factory()
176 tok.init_from_project(test_config)
178 assert tok.loader is not None
181 def test_update_sql_functions(db_prop, temp_db_cursor,
182 tokenizer_factory, test_config, table_factory,
184 tok = tokenizer_factory()
185 tok.init_new_db(test_config)
187 table_factory('test', 'txt TEXT')
189 func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
190 func_file.write_text("""INSERT INTO test VALUES (1133)""", encoding='utf-8')
192 tok.update_sql_functions(test_config)
194 test_content = temp_db_cursor.row_set('SELECT * FROM test')
195 assert test_content == set((('1133', ), ))
198 def test_finalize_import(tokenizer_factory, temp_db_cursor,
199 test_config, sql_preprocessor_cfg):
200 tok = tokenizer_factory()
201 tok.init_new_db(test_config)
203 assert not temp_db_cursor.index_exists('word', 'idx_word_word_id')
205 tok.finalize_import(test_config)
207 assert temp_db_cursor.index_exists('word', 'idx_word_word_id')
210 def test_check_database(test_config, tokenizer_factory,
211 temp_db_cursor, sql_preprocessor_cfg):
212 tok = tokenizer_factory()
213 tok.init_new_db(test_config)
215 assert tok.check_database(test_config) is None
218 def test_update_statistics_reverse_only(word_table, tokenizer_factory, test_config):
219 tok = tokenizer_factory()
220 tok.update_statistics(test_config)
223 def test_update_statistics(word_table, table_factory, temp_db_cursor,
224 tokenizer_factory, test_config):
225 word_table.add_full_word(1000, 'hello')
226 word_table.add_full_word(1001, 'bye')
227 word_table.add_full_word(1002, 'town')
228 table_factory('search_name',
229 'place_id BIGINT, name_vector INT[], nameaddress_vector INT[]',
230 [(12, [1000], [1001]), (13, [1001], [1002]), (14, [1000, 1001], [1002])])
231 tok = tokenizer_factory()
233 tok.update_statistics(test_config)
235 assert temp_db_cursor.row_set("""SELECT word_id,
236 (info->>'count')::int,
237 (info->>'addr_count')::int
239 WHERE type = 'W'""") == \
240 {(1000, 2, None), (1001, 2, None), (1002, None, 2)}
243 def test_normalize_postcode(analyzer):
244 with analyzer() as anl:
245 anl.normalize_postcode('123') == '123'
246 anl.normalize_postcode('ab-34 ') == 'AB-34'
247 anl.normalize_postcode('38 Б') == '38 Б'
252 @pytest.fixture(autouse=True)
253 def setup(self, analyzer, sql_functions, def_config):
254 self.sanitizer = PlaceSanitizer([{'step': 'clean-postcodes'}], def_config)
255 with analyzer(with_postcode=True) as anl:
259 def process_postcode(self, cc, postcode):
260 place = PlaceInfo({'country_code': cc,
261 'address': {'postcode': postcode}})
262 self.sanitizer.process_names(place)
263 return self.analyzer.process_place(place)
265 def test_update_postcodes_deleted(self, word_table):
266 word_table.add_postcode(' 1234', '1234')
267 word_table.add_postcode(' 5678', '5678')
269 self.analyzer.update_postcodes_from_db()
271 assert word_table.count() == 0
273 def test_process_place_postcode_simple(self, word_table):
274 info = self.process_postcode('de', '12345')
276 assert info['postcode'] == '12345'
278 def test_process_place_postcode_with_space(self, word_table):
279 info = self.process_postcode('in', '123 567')
281 assert info['postcode'] == '123567'
284 def test_update_special_phrase_empty_table(analyzer, word_table):
285 with analyzer() as anl:
286 anl.update_special_phrases([
287 ("König bei", "amenity", "royal", "near"),
288 ("Könige ", "amenity", "royal", "-"),
289 ("street", "highway", "primary", "in")
292 assert word_table.get_special() \
293 == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
294 ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
295 ('STREET', 'street', 'highway', 'primary', 'in')}
298 def test_update_special_phrase_delete_all(analyzer, word_table):
299 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
300 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
302 assert word_table.count_special() == 2
304 with analyzer() as anl:
305 anl.update_special_phrases([], True)
307 assert word_table.count_special() == 0
310 def test_update_special_phrases_no_replace(analyzer, word_table):
311 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
312 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
314 assert word_table.count_special() == 2
316 with analyzer() as anl:
317 anl.update_special_phrases([], False)
319 assert word_table.count_special() == 2
322 def test_update_special_phrase_modify(analyzer, word_table):
323 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
324 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
326 assert word_table.count_special() == 2
328 with analyzer() as anl:
329 anl.update_special_phrases([
330 ('prison', 'amenity', 'prison', 'in'),
331 ('bar', 'highway', 'road', '-'),
332 ('garden', 'leisure', 'garden', 'near')
335 assert word_table.get_special() \
336 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
337 ('BAR', 'bar', 'highway', 'road', None),
338 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
341 def test_add_country_names_new(analyzer, word_table):
342 with analyzer() as anl:
343 anl.add_country_names('es', [PlaceName('Espagña', 'name', None),
344 PlaceName('Spain', 'name', 'en')])
346 assert word_table.get_country() == {('es', 'ESPAGÑA', 'Espagña'),
347 ('es', 'SPAIN', 'Spain')}
350 def test_add_country_names_extend(analyzer, word_table):
351 word_table.add_country('ch', 'SCHWEIZ', 'Schweiz')
353 with analyzer() as anl:
354 anl.add_country_names('ch', [PlaceName('Schweiz', 'name', None),
355 PlaceName('Suisse', 'name', 'fr')])
357 assert word_table.get_country() == {('ch', 'SCHWEIZ', 'Schweiz'),
358 ('ch', 'SUISSE', 'Suisse')}
361 class TestPlaceNames:
363 @pytest.fixture(autouse=True)
364 def setup(self, analyzer, sql_functions, def_config):
365 self.sanitizer = PlaceSanitizer([{'step': 'split-name-list'},
366 {'step': 'strip-brace-terms'}], def_config)
367 with analyzer() as anl:
371 def expect_name_terms(self, info, *expected_terms):
372 tokens = self.analyzer.get_word_token_info(expected_terms)
374 assert token[2] is not None, "No token for {0}".format(token)
376 assert eval(info['names']) == set((t[2] for t in tokens))
378 def process_named_place(self, names):
379 place = PlaceInfo({'name': names})
380 self.sanitizer.process_names(place)
381 return self.analyzer.process_place(place)
383 def test_simple_names(self):
384 info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
386 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
388 @pytest.mark.parametrize('sep', [',', ';'])
389 def test_names_with_separator(self, sep):
390 info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
392 self.expect_name_terms(info, '#New York', '#Big Apple',
393 'new', 'york', 'big', 'apple')
395 def test_full_names_with_bracket(self):
396 info = self.process_named_place({'name': 'Houseboat (left)'})
398 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
401 def test_country_name(self, word_table):
402 place = PlaceInfo({'name': {'name': 'Norge'},
403 'country_code': 'no',
406 'type': 'administrative'})
407 self.sanitizer.process_names(place)
408 info = self.analyzer.process_place(place)
410 self.expect_name_terms(info, '#norge', 'norge')
411 assert word_table.get_country() == {('no', 'NORGE', 'Norge')}
414 class TestPlaceAddress:
416 @pytest.fixture(autouse=True)
417 def setup(self, analyzer, sql_functions, def_config):
418 hnr = {'step': 'clean-housenumbers',
419 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
420 self.sanitizer = PlaceSanitizer([hnr], def_config)
421 with analyzer(trans=(":: upper()", "'🜵' > ' '")) as anl:
426 def getorcreate_hnr_id(self, temp_db_cursor):
427 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
428 RETURNS INTEGER AS $$
429 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
431 def process_address(self, **kwargs):
432 place = PlaceInfo({'address': kwargs})
433 self.sanitizer.process_names(place)
434 return self.analyzer.process_place(place)
436 def name_token_set(self, *expected_terms):
437 tokens = self.analyzer.get_word_token_info(expected_terms)
439 assert token[2] is not None, "No token for {0}".format(token)
441 return set((t[2] for t in tokens))
443 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
444 def test_process_place_postcode(self, word_table, pcode):
445 info = self.process_address(postcode=pcode)
447 assert info['postcode'] == pcode
449 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
450 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
451 info = self.process_address(housenumber=hnr)
453 assert info['hnr'] == hnr.upper()
454 assert info['hnr_tokens'] == "{-1}"
456 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
457 info = self.process_address(housenumber='134',
458 conscriptionnumber='134',
461 assert set(info['hnr'].split(';')) == set(('134', '99A'))
462 assert info['hnr_tokens'] == "{-1,-2}"
464 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
465 info = self.process_address(housenumber="45")
466 assert info['hnr_tokens'] == "{-1}"
468 info = self.process_address(housenumber="46")
469 assert info['hnr_tokens'] == "{-2}"
471 info = self.process_address(housenumber="41;45")
472 assert eval(info['hnr_tokens']) == {-1, -3}
474 info = self.process_address(housenumber="41")
475 assert eval(info['hnr_tokens']) == {-3}
477 def test_process_place_street(self):
478 place = PlaceInfo({'name': {'name': 'Grand Road'}})
479 self.sanitizer.process_names(place)
480 self.analyzer.process_place(place)
481 info = self.process_address(street='Grand Road')
483 assert eval(info['street']) == self.name_token_set('#Grand Road')
485 def test_process_place_nonexisting_street(self):
486 info = self.process_address(street='Grand Road')
488 assert info['street'] == '{}'
490 def test_process_place_multiple_street_tags(self):
491 place = PlaceInfo({'name': {'name': 'Grand Road', 'ref': '05989'}})
492 self.sanitizer.process_names(place)
493 self.analyzer.process_place(place)
494 info = self.process_address(**{'street': 'Grand Road',
495 'street:sym_ul': '05989'})
497 assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
499 def test_process_place_street_empty(self):
500 info = self.process_address(street='🜵')
502 assert info['street'] == '{}'
504 def test_process_place_street_from_cache(self):
505 place = PlaceInfo({'name': {'name': 'Grand Road'}})
506 self.sanitizer.process_names(place)
507 self.analyzer.process_place(place)
508 self.process_address(street='Grand Road')
510 # request address again
511 info = self.process_address(street='Grand Road')
513 assert eval(info['street']) == self.name_token_set('#Grand Road')
515 def test_process_place_place(self):
516 info = self.process_address(place='Honu Lulu')
518 assert eval(info['place']) == self.name_token_set('HONU', 'LULU', '#HONU LULU')
520 def test_process_place_place_extra(self):
521 info = self.process_address(**{'place:en': 'Honu Lulu'})
523 assert 'place' not in info
525 def test_process_place_place_empty(self):
526 info = self.process_address(place='🜵')
528 assert 'place' not in info
530 def test_process_place_address_terms(self):
531 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
532 suburb='Zwickau', street='Hauptstr',
533 full='right behind the church')
535 city = self.name_token_set('ZWICKAU', '#ZWICKAU')
536 state = self.name_token_set('SACHSEN', '#SACHSEN')
538 result = {k: eval(v) for k, v in info['addr'].items()}
540 assert result == {'city': city, 'suburb': city, 'state': state}
542 def test_process_place_multiple_address_terms(self):
543 info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
545 result = {k: eval(v) for k, v in info['addr'].items()}
547 assert result == {'city': self.name_token_set('Bruxelles', '#Bruxelles')}
549 def test_process_place_address_terms_empty(self):
550 info = self.process_address(country='de', city=' ', street='Hauptstr',
551 full='right behind the church')
553 assert 'addr' not in info
556 class TestPlaceHousenumberWithAnalyser:
558 @pytest.fixture(autouse=True)
559 def setup(self, analyzer, sql_functions, def_config):
560 hnr = {'step': 'clean-housenumbers',
561 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
562 self.sanitizer = PlaceSanitizer([hnr], def_config)
563 with analyzer(trans=(":: upper()", "'🜵' > ' '"), with_housenumber=True) as anl:
568 def getorcreate_hnr_id(self, temp_db_cursor):
569 temp_db_cursor.execute("""
570 CREATE OR REPLACE FUNCTION create_analyzed_hnr_id(norm_term TEXT, lookup_terms TEXT[])
571 RETURNS INTEGER AS $$
572 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
574 def process_address(self, **kwargs):
575 place = PlaceInfo({'address': kwargs})
576 self.sanitizer.process_names(place)
577 return self.analyzer.process_place(place)
579 def name_token_set(self, *expected_terms):
580 tokens = self.analyzer.get_word_token_info(expected_terms)
582 assert token[2] is not None, "No token for {0}".format(token)
584 return set((t[2] for t in tokens))
586 @pytest.mark.parametrize('hnr', ['123 a', '1', '101'])
587 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
588 info = self.process_address(housenumber=hnr)
590 assert info['hnr'] == hnr.upper()
591 assert info['hnr_tokens'] == "{-1}"
593 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
594 info = self.process_address(housenumber='134',
595 conscriptionnumber='134',
598 assert set(info['hnr'].split(';')) == set(('134', '99 A'))
599 assert info['hnr_tokens'] == "{-1,-2}"
601 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
602 info = self.process_address(housenumber="45")
603 assert info['hnr_tokens'] == "{-1}"
605 info = self.process_address(housenumber="46")
606 assert info['hnr_tokens'] == "{-2}"
608 info = self.process_address(housenumber="41;45")
609 assert eval(info['hnr_tokens']) == {-1, -3}
611 info = self.process_address(housenumber="41")
612 assert eval(info['hnr_tokens']) == {-3}
615 class TestUpdateWordTokens:
617 @pytest.fixture(autouse=True)
618 def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
619 table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
620 self.tok = tokenizer_factory()
623 def search_entry(self, temp_db_cursor):
624 place_id = itertools.count(1000)
627 temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
628 (next(place_id), list(args)))
632 @pytest.fixture(params=['simple', 'analyzed'])
633 def add_housenumber(self, request, word_table):
634 if request.param == 'simple':
636 word_table.add_housenumber(hid, hnr)
637 elif request.param == 'analyzed':
639 word_table.add_housenumber(hid, [hnr])
643 @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
644 def test_remove_unused_housenumbers(self, add_housenumber, word_table, hnr):
645 word_table.add_housenumber(1000, hnr)
647 assert word_table.count_housenumbers() == 1
648 self.tok.update_word_tokens()
649 assert word_table.count_housenumbers() == 0
651 def test_keep_unused_numeral_housenumbers(self, add_housenumber, word_table):
652 add_housenumber(1000, '5432')
654 assert word_table.count_housenumbers() == 1
655 self.tok.update_word_tokens()
656 assert word_table.count_housenumbers() == 1
658 def test_keep_housenumbers_from_search_name_table(self, add_housenumber,
659 word_table, search_entry):
660 add_housenumber(9999, '5432a')
661 add_housenumber(9991, '9 a')
662 search_entry(123, 9999, 34)
664 assert word_table.count_housenumbers() == 2
665 self.tok.update_word_tokens()
666 assert word_table.count_housenumbers() == 1
668 def test_keep_housenumbers_from_placex_table(self, add_housenumber, word_table, placex_row):
669 add_housenumber(9999, '5432a')
670 add_housenumber(9990, '34z')
671 placex_row(housenumber='34z')
672 placex_row(housenumber='25432a')
674 assert word_table.count_housenumbers() == 2
675 self.tok.update_word_tokens()
676 assert word_table.count_housenumbers() == 1
678 def test_keep_housenumbers_from_placex_table_hnr_list(self, add_housenumber,
679 word_table, placex_row):
680 add_housenumber(9991, '9 b')
681 add_housenumber(9990, '34z')
682 placex_row(housenumber='9 a;9 b;9 c')
684 assert word_table.count_housenumbers() == 2
685 self.tok.update_word_tokens()
686 assert word_table.count_housenumbers() == 1