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):
72 cfgstr = {'normalization': list(norm),
73 'transliteration': list(trans),
74 'token-analysis': [{'analyzer': 'generic',
75 'variants': [{'words': list(variants)}]}]}
77 cfgstr['token-analysis'].append({'id': '@housenumber',
78 'analyzer': 'housenumbers'})
79 (test_config.project_dir / 'icu_tokenizer.yaml').write_text(
80 yaml.dump(cfgstr), encoding='utf-8')
81 tok.loader = nominatim_db.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
83 return tok.name_analyzer()
89 def sql_functions(load_sql):
90 load_sql('functions/utils.sql')
91 load_sql('tokenizer/icu_tokenizer.sql')
95 def getorcreate_full_word(temp_db_cursor):
96 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
97 norm_term TEXT, lookup_terms TEXT[],
99 OUT partial_tokens INT[])
102 partial_terms TEXT[] = '{}'::TEXT[];
107 SELECT min(word_id) INTO full_token
108 FROM word WHERE info->>'word' = norm_term and type = 'W';
110 IF full_token IS NULL THEN
111 full_token := nextval('seq_word');
112 INSERT INTO word (word_id, word_token, type, info)
113 SELECT full_token, lookup_term, 'W',
114 json_build_object('word', norm_term, 'count', 0)
115 FROM unnest(lookup_terms) as lookup_term;
118 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
120 IF NOT (ARRAY[term] <@ partial_terms) THEN
121 partial_terms := partial_terms || term;
125 partial_tokens := '{}'::INT[];
126 FOR term IN SELECT unnest(partial_terms) LOOP
127 SELECT min(word_id), max(info->>'count') INTO term_id, term_count
128 FROM word WHERE word_token = term and type = 'w';
130 IF term_id IS NULL THEN
131 term_id := nextval('seq_word');
133 INSERT INTO word (word_id, word_token, type, info)
134 VALUES (term_id, term, 'w', json_build_object('count', term_count));
137 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
138 partial_tokens := partial_tokens || term_id;
147 def test_init_new(tokenizer_factory, test_config, db_prop):
148 tok = tokenizer_factory()
149 tok.init_new_db(test_config)
151 prop = db_prop(nominatim_db.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES)
153 assert prop.startswith(':: lower ();')
156 def test_init_word_table(tokenizer_factory, test_config, place_row, temp_db_cursor):
157 place_row(names={'name': 'Test Area', 'ref': '52'})
158 place_row(names={'name': 'No Area'})
159 place_row(names={'name': 'Holzstrasse'})
161 tok = tokenizer_factory()
162 tok.init_new_db(test_config)
164 assert temp_db_cursor.table_exists('word')
167 def test_init_from_project(test_config, tokenizer_factory):
168 tok = tokenizer_factory()
169 tok.init_new_db(test_config)
171 tok = tokenizer_factory()
172 tok.init_from_project(test_config)
174 assert tok.loader is not None
177 def test_update_sql_functions(db_prop, temp_db_cursor,
178 tokenizer_factory, test_config, table_factory,
180 tok = tokenizer_factory()
181 tok.init_new_db(test_config)
183 table_factory('test', 'txt TEXT')
185 func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
186 func_file.write_text("""INSERT INTO test VALUES (1133)""", encoding='utf-8')
188 tok.update_sql_functions(test_config)
190 test_content = temp_db_cursor.row_set('SELECT * FROM test')
191 assert test_content == set((('1133', ), ))
194 def test_finalize_import(tokenizer_factory, temp_db_cursor,
195 test_config, sql_preprocessor_cfg):
196 tok = tokenizer_factory()
197 tok.init_new_db(test_config)
199 assert not temp_db_cursor.index_exists('word', 'idx_word_word_id')
201 tok.finalize_import(test_config)
203 assert temp_db_cursor.index_exists('word', 'idx_word_word_id')
206 def test_check_database(test_config, tokenizer_factory,
207 temp_db_cursor, sql_preprocessor_cfg):
208 tok = tokenizer_factory()
209 tok.init_new_db(test_config)
211 assert tok.check_database(test_config) is None
214 def test_update_statistics_reverse_only(word_table, tokenizer_factory, test_config):
215 tok = tokenizer_factory()
216 tok.update_statistics(test_config)
219 def test_update_statistics(word_table, table_factory, temp_db_cursor,
220 tokenizer_factory, test_config):
221 word_table.add_full_word(1000, 'hello')
222 word_table.add_full_word(1001, 'bye')
223 word_table.add_full_word(1002, 'town')
224 table_factory('search_name',
225 'place_id BIGINT, name_vector INT[], nameaddress_vector INT[]',
226 [(12, [1000], [1001]), (13, [1001], [1002]), (14, [1000, 1001], [1002])])
227 tok = tokenizer_factory()
229 tok.update_statistics(test_config)
231 assert temp_db_cursor.row_set("""SELECT word_id,
232 (info->>'count')::int,
233 (info->>'addr_count')::int
235 WHERE type = 'W'""") == \
236 {(1000, 2, None), (1001, 2, None), (1002, None, 2)}
239 def test_normalize_postcode(analyzer):
240 with analyzer() as anl:
241 anl.normalize_postcode('123') == '123'
242 anl.normalize_postcode('ab-34 ') == 'AB-34'
243 anl.normalize_postcode('38 Б') == '38 Б'
248 @pytest.fixture(autouse=True)
249 def setup(self, analyzer, sql_functions, def_config):
250 self.sanitizer = PlaceSanitizer([{'step': 'clean-postcodes'}], def_config)
251 with analyzer() as anl:
255 def process_postcode(self, cc, postcode):
256 place = PlaceInfo({'country_code': cc,
257 'address': {'postcode': postcode}})
258 self.sanitizer.process_names(place)
259 return self.analyzer.process_place(place)
261 def test_update_postcodes_deleted(self, word_table):
262 word_table.add_postcode(' 1234', '1234')
263 word_table.add_postcode(' 5678', '5678')
265 self.analyzer.update_postcodes_from_db()
267 assert word_table.count() == 0
269 def test_process_place_postcode_simple(self, word_table):
270 info = self.process_postcode('de', '12345')
272 assert info['postcode'] == '12345'
274 def test_process_place_postcode_with_space(self, word_table):
275 info = self.process_postcode('in', '123 567')
277 assert info['postcode'] == '123567'
280 def test_update_special_phrase_empty_table(analyzer, word_table):
281 with analyzer() as anl:
282 anl.update_special_phrases([
283 ("König bei", "amenity", "royal", "near"),
284 ("Könige ", "amenity", "royal", "-"),
285 ("street", "highway", "primary", "in")
288 assert word_table.get_special() \
289 == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
290 ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
291 ('STREET', 'street', 'highway', 'primary', 'in')}
294 def test_update_special_phrase_delete_all(analyzer, word_table):
295 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
296 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
298 assert word_table.count_special() == 2
300 with analyzer() as anl:
301 anl.update_special_phrases([], True)
303 assert word_table.count_special() == 0
306 def test_update_special_phrases_no_replace(analyzer, word_table):
307 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
308 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
310 assert word_table.count_special() == 2
312 with analyzer() as anl:
313 anl.update_special_phrases([], False)
315 assert word_table.count_special() == 2
318 def test_update_special_phrase_modify(analyzer, word_table):
319 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
320 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
322 assert word_table.count_special() == 2
324 with analyzer() as anl:
325 anl.update_special_phrases([
326 ('prison', 'amenity', 'prison', 'in'),
327 ('bar', 'highway', 'road', '-'),
328 ('garden', 'leisure', 'garden', 'near')
331 assert word_table.get_special() \
332 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
333 ('BAR', 'bar', 'highway', 'road', None),
334 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
337 def test_add_country_names_new(analyzer, word_table):
338 with analyzer() as anl:
339 anl.add_country_names('es', [PlaceName('Espagña', 'name', None),
340 PlaceName('Spain', 'name', 'en')])
342 assert word_table.get_country() == {('es', 'ESPAGÑA', 'Espagña'),
343 ('es', 'SPAIN', 'Spain')}
346 def test_add_country_names_extend(analyzer, word_table):
347 word_table.add_country('ch', 'SCHWEIZ', 'Schweiz')
349 with analyzer() as anl:
350 anl.add_country_names('ch', [PlaceName('Schweiz', 'name', None),
351 PlaceName('Suisse', 'name', 'fr')])
353 assert word_table.get_country() == {('ch', 'SCHWEIZ', 'Schweiz'),
354 ('ch', 'SUISSE', 'Suisse')}
357 class TestPlaceNames:
359 @pytest.fixture(autouse=True)
360 def setup(self, analyzer, sql_functions, def_config):
361 self.sanitizer = PlaceSanitizer([{'step': 'split-name-list'},
362 {'step': 'strip-brace-terms'}], def_config)
363 with analyzer() as anl:
367 def expect_name_terms(self, info, *expected_terms):
368 tokens = self.analyzer.get_word_token_info(expected_terms)
370 assert token[2] is not None, "No token for {0}".format(token)
372 assert eval(info['names']) == set((t[2] for t in tokens))
374 def process_named_place(self, names):
375 place = PlaceInfo({'name': names})
376 self.sanitizer.process_names(place)
377 return self.analyzer.process_place(place)
379 def test_simple_names(self):
380 info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
382 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
384 @pytest.mark.parametrize('sep', [',', ';'])
385 def test_names_with_separator(self, sep):
386 info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
388 self.expect_name_terms(info, '#New York', '#Big Apple',
389 'new', 'york', 'big', 'apple')
391 def test_full_names_with_bracket(self):
392 info = self.process_named_place({'name': 'Houseboat (left)'})
394 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
397 def test_country_name(self, word_table):
398 place = PlaceInfo({'name': {'name': 'Norge'},
399 'country_code': 'no',
402 'type': 'administrative'})
403 self.sanitizer.process_names(place)
404 info = self.analyzer.process_place(place)
406 self.expect_name_terms(info, '#norge', 'norge')
407 assert word_table.get_country() == {('no', 'NORGE', 'Norge')}
410 class TestPlaceAddress:
412 @pytest.fixture(autouse=True)
413 def setup(self, analyzer, sql_functions, def_config):
414 hnr = {'step': 'clean-housenumbers',
415 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
416 self.sanitizer = PlaceSanitizer([hnr], def_config)
417 with analyzer(trans=(":: upper()", "'🜵' > ' '")) as anl:
422 def getorcreate_hnr_id(self, temp_db_cursor):
423 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
424 RETURNS INTEGER AS $$
425 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
427 def process_address(self, **kwargs):
428 place = PlaceInfo({'address': kwargs})
429 self.sanitizer.process_names(place)
430 return self.analyzer.process_place(place)
432 def name_token_set(self, *expected_terms):
433 tokens = self.analyzer.get_word_token_info(expected_terms)
435 assert token[2] is not None, "No token for {0}".format(token)
437 return set((t[2] for t in tokens))
439 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
440 def test_process_place_postcode(self, word_table, pcode):
441 info = self.process_address(postcode=pcode)
443 assert info['postcode'] == pcode
445 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
446 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
447 info = self.process_address(housenumber=hnr)
449 assert info['hnr'] == hnr.upper()
450 assert info['hnr_tokens'] == "{-1}"
452 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
453 info = self.process_address(housenumber='134',
454 conscriptionnumber='134',
457 assert set(info['hnr'].split(';')) == set(('134', '99A'))
458 assert info['hnr_tokens'] == "{-1,-2}"
460 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
461 info = self.process_address(housenumber="45")
462 assert info['hnr_tokens'] == "{-1}"
464 info = self.process_address(housenumber="46")
465 assert info['hnr_tokens'] == "{-2}"
467 info = self.process_address(housenumber="41;45")
468 assert eval(info['hnr_tokens']) == {-1, -3}
470 info = self.process_address(housenumber="41")
471 assert eval(info['hnr_tokens']) == {-3}
473 def test_process_place_street(self):
474 place = PlaceInfo({'name': {'name': 'Grand Road'}})
475 self.sanitizer.process_names(place)
476 self.analyzer.process_place(place)
477 info = self.process_address(street='Grand Road')
479 assert eval(info['street']) == self.name_token_set('#Grand Road')
481 def test_process_place_nonexisting_street(self):
482 info = self.process_address(street='Grand Road')
484 assert info['street'] == '{}'
486 def test_process_place_multiple_street_tags(self):
487 place = PlaceInfo({'name': {'name': 'Grand Road', 'ref': '05989'}})
488 self.sanitizer.process_names(place)
489 self.analyzer.process_place(place)
490 info = self.process_address(**{'street': 'Grand Road',
491 'street:sym_ul': '05989'})
493 assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
495 def test_process_place_street_empty(self):
496 info = self.process_address(street='🜵')
498 assert info['street'] == '{}'
500 def test_process_place_street_from_cache(self):
501 place = PlaceInfo({'name': {'name': 'Grand Road'}})
502 self.sanitizer.process_names(place)
503 self.analyzer.process_place(place)
504 self.process_address(street='Grand Road')
506 # request address again
507 info = self.process_address(street='Grand Road')
509 assert eval(info['street']) == self.name_token_set('#Grand Road')
511 def test_process_place_place(self):
512 info = self.process_address(place='Honu Lulu')
514 assert eval(info['place']) == self.name_token_set('HONU', 'LULU', '#HONU LULU')
516 def test_process_place_place_extra(self):
517 info = self.process_address(**{'place:en': 'Honu Lulu'})
519 assert 'place' not in info
521 def test_process_place_place_empty(self):
522 info = self.process_address(place='🜵')
524 assert 'place' not in info
526 def test_process_place_address_terms(self):
527 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
528 suburb='Zwickau', street='Hauptstr',
529 full='right behind the church')
531 city = self.name_token_set('ZWICKAU', '#ZWICKAU')
532 state = self.name_token_set('SACHSEN', '#SACHSEN')
534 result = {k: eval(v) for k, v in info['addr'].items()}
536 assert result == {'city': city, 'suburb': city, 'state': state}
538 def test_process_place_multiple_address_terms(self):
539 info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
541 result = {k: eval(v) for k, v in info['addr'].items()}
543 assert result == {'city': self.name_token_set('Bruxelles', '#Bruxelles')}
545 def test_process_place_address_terms_empty(self):
546 info = self.process_address(country='de', city=' ', street='Hauptstr',
547 full='right behind the church')
549 assert 'addr' not in info
552 class TestPlaceHousenumberWithAnalyser:
554 @pytest.fixture(autouse=True)
555 def setup(self, analyzer, sql_functions, def_config):
556 hnr = {'step': 'clean-housenumbers',
557 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
558 self.sanitizer = PlaceSanitizer([hnr], def_config)
559 with analyzer(trans=(":: upper()", "'🜵' > ' '"), with_housenumber=True) as anl:
564 def getorcreate_hnr_id(self, temp_db_cursor):
565 temp_db_cursor.execute("""
566 CREATE OR REPLACE FUNCTION create_analyzed_hnr_id(norm_term TEXT, lookup_terms TEXT[])
567 RETURNS INTEGER AS $$
568 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
570 def process_address(self, **kwargs):
571 place = PlaceInfo({'address': kwargs})
572 self.sanitizer.process_names(place)
573 return self.analyzer.process_place(place)
575 def name_token_set(self, *expected_terms):
576 tokens = self.analyzer.get_word_token_info(expected_terms)
578 assert token[2] is not None, "No token for {0}".format(token)
580 return set((t[2] for t in tokens))
582 @pytest.mark.parametrize('hnr', ['123 a', '1', '101'])
583 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
584 info = self.process_address(housenumber=hnr)
586 assert info['hnr'] == hnr.upper()
587 assert info['hnr_tokens'] == "{-1}"
589 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
590 info = self.process_address(housenumber='134',
591 conscriptionnumber='134',
594 assert set(info['hnr'].split(';')) == set(('134', '99 A'))
595 assert info['hnr_tokens'] == "{-1,-2}"
597 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
598 info = self.process_address(housenumber="45")
599 assert info['hnr_tokens'] == "{-1}"
601 info = self.process_address(housenumber="46")
602 assert info['hnr_tokens'] == "{-2}"
604 info = self.process_address(housenumber="41;45")
605 assert eval(info['hnr_tokens']) == {-1, -3}
607 info = self.process_address(housenumber="41")
608 assert eval(info['hnr_tokens']) == {-3}
611 class TestUpdateWordTokens:
613 @pytest.fixture(autouse=True)
614 def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
615 table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
616 self.tok = tokenizer_factory()
619 def search_entry(self, temp_db_cursor):
620 place_id = itertools.count(1000)
623 temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
624 (next(place_id), list(args)))
628 @pytest.fixture(params=['simple', 'analyzed'])
629 def add_housenumber(self, request, word_table):
630 if request.param == 'simple':
632 word_table.add_housenumber(hid, hnr)
633 elif request.param == 'analyzed':
635 word_table.add_housenumber(hid, [hnr])
639 @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
640 def test_remove_unused_housenumbers(self, add_housenumber, word_table, hnr):
641 word_table.add_housenumber(1000, hnr)
643 assert word_table.count_housenumbers() == 1
644 self.tok.update_word_tokens()
645 assert word_table.count_housenumbers() == 0
647 def test_keep_unused_numeral_housenumbers(self, add_housenumber, word_table):
648 add_housenumber(1000, '5432')
650 assert word_table.count_housenumbers() == 1
651 self.tok.update_word_tokens()
652 assert word_table.count_housenumbers() == 1
654 def test_keep_housenumbers_from_search_name_table(self, add_housenumber,
655 word_table, search_entry):
656 add_housenumber(9999, '5432a')
657 add_housenumber(9991, '9 a')
658 search_entry(123, 9999, 34)
660 assert word_table.count_housenumbers() == 2
661 self.tok.update_word_tokens()
662 assert word_table.count_housenumbers() == 1
664 def test_keep_housenumbers_from_placex_table(self, add_housenumber, word_table, placex_row):
665 add_housenumber(9999, '5432a')
666 add_housenumber(9990, '34z')
667 placex_row(housenumber='34z')
668 placex_row(housenumber='25432a')
670 assert word_table.count_housenumbers() == 2
671 self.tok.update_word_tokens()
672 assert word_table.count_housenumbers() == 1
674 def test_keep_housenumbers_from_placex_table_hnr_list(self, add_housenumber,
675 word_table, placex_row):
676 add_housenumber(9991, '9 b')
677 add_housenumber(9990, '34z')
678 placex_row(housenumber='9 a;9 b;9 c')
680 assert word_table.count_housenumbers() == 2
681 self.tok.update_word_tokens()
682 assert word_table.count_housenumbers() == 1