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
20 from mock_icu_word_table import MockIcuWordTable
24 def word_table(temp_db_conn):
25 return MockIcuWordTable(temp_db_conn)
29 def test_config(project_env, tmp_path):
30 sqldir = tmp_path / 'sql'
32 (sqldir / 'tokenizer').mkdir()
33 (sqldir / 'tokenizer' / 'icu_tokenizer.sql').write_text("SELECT 'a'", encoding='utf-8')
35 project_env.lib_dir.sql = sqldir
41 def tokenizer_factory(dsn, property_table, sql_preprocessor, place_table, word_table):
43 return icu_tokenizer.create(dsn)
49 def db_prop(temp_db_conn):
50 def _get_db_property(name):
51 return properties.get_property(temp_db_conn, name)
53 return _get_db_property
57 def analyzer(tokenizer_factory, test_config, monkeypatch,
58 temp_db_with_extensions, tmp_path):
59 sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
60 sql.write_text("SELECT 'a';", encoding='utf-8')
62 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
63 tok = tokenizer_factory()
64 tok.init_new_db(test_config)
67 def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
68 variants=('~gasse -> gasse', 'street => st', ),
69 sanitizers=[], with_housenumber=False,
71 cfgstr = {'normalization': list(norm),
72 'sanitizers': sanitizers,
73 'transliteration': list(trans),
74 'token-analysis': [{'analyzer': 'generic',
75 'variants': [{'words': list(variants)}]}]}
77 cfgstr['token-analysis'].append({'id': '@housenumber',
78 'analyzer': 'housenumbers'})
80 cfgstr['token-analysis'].append({'id': '@postcode',
81 'analyzer': 'postcodes'})
82 (test_config.project_dir / 'icu_tokenizer.yaml').write_text(
83 yaml.dump(cfgstr), encoding='utf-8')
84 tok.loader = nominatim_db.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
86 return tok.name_analyzer()
92 def sql_functions(load_sql):
93 load_sql('functions/utils.sql')
94 load_sql('tokenizer/icu_tokenizer.sql')
98 def getorcreate_full_word(temp_db_cursor):
99 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
100 norm_term TEXT, lookup_terms TEXT[],
102 OUT partial_tokens INT[])
105 partial_terms TEXT[] = '{}'::TEXT[];
110 SELECT min(word_id) INTO full_token
111 FROM word WHERE info->>'word' = norm_term and type = 'W';
113 IF full_token IS NULL THEN
114 full_token := nextval('seq_word');
115 INSERT INTO word (word_id, word_token, type, info)
116 SELECT full_token, lookup_term, 'W',
117 json_build_object('word', norm_term, 'count', 0)
118 FROM unnest(lookup_terms) as lookup_term;
121 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
123 IF NOT (ARRAY[term] <@ partial_terms) THEN
124 partial_terms := partial_terms || term;
128 partial_tokens := '{}'::INT[];
129 FOR term IN SELECT unnest(partial_terms) LOOP
130 SELECT min(word_id), max(info->>'count') INTO term_id, term_count
131 FROM word WHERE word_token = term and type = 'w';
133 IF term_id IS NULL THEN
134 term_id := nextval('seq_word');
136 INSERT INTO word (word_id, word_token, type, info)
137 VALUES (term_id, term, 'w', json_build_object('count', term_count));
140 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
141 partial_tokens := partial_tokens || term_id;
150 def test_init_new(tokenizer_factory, test_config, db_prop):
151 tok = tokenizer_factory()
152 tok.init_new_db(test_config)
154 prop = db_prop(nominatim_db.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES)
156 assert prop.startswith(':: lower ();')
159 def test_init_word_table(tokenizer_factory, test_config, place_row, temp_db_cursor):
160 place_row(names={'name': 'Test Area', 'ref': '52'})
161 place_row(names={'name': 'No Area'})
162 place_row(names={'name': 'Holzstrasse'})
164 tok = tokenizer_factory()
165 tok.init_new_db(test_config)
167 assert temp_db_cursor.table_exists('word')
170 def test_init_from_project(test_config, tokenizer_factory):
171 tok = tokenizer_factory()
172 tok.init_new_db(test_config)
174 tok = tokenizer_factory()
175 tok.init_from_project(test_config)
177 assert tok.loader is not None
180 def test_update_sql_functions(db_prop, temp_db_cursor,
181 tokenizer_factory, test_config, table_factory,
183 tok = tokenizer_factory()
184 tok.init_new_db(test_config)
186 table_factory('test', 'txt TEXT')
188 func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
189 func_file.write_text("""INSERT INTO test VALUES (1133)""", encoding='utf-8')
191 tok.update_sql_functions(test_config)
193 test_content = temp_db_cursor.row_set('SELECT * FROM test')
194 assert test_content == set((('1133', ), ))
197 def test_finalize_import(tokenizer_factory, temp_db_cursor,
198 test_config, sql_preprocessor_cfg):
199 tok = tokenizer_factory()
200 tok.init_new_db(test_config)
202 assert not temp_db_cursor.index_exists('word', 'idx_word_word_id')
204 tok.finalize_import(test_config)
206 assert temp_db_cursor.index_exists('word', 'idx_word_word_id')
209 def test_check_database(test_config, tokenizer_factory,
210 temp_db_cursor, sql_preprocessor_cfg):
211 tok = tokenizer_factory()
212 tok.init_new_db(test_config)
214 assert tok.check_database(test_config) is None
217 def test_update_statistics_reverse_only(word_table, tokenizer_factory, test_config):
218 tok = tokenizer_factory()
219 tok.update_statistics(test_config)
222 def test_update_statistics(word_table, table_factory, temp_db_cursor,
223 tokenizer_factory, test_config):
224 word_table.add_full_word(1000, 'hello')
225 word_table.add_full_word(1001, 'bye')
226 word_table.add_full_word(1002, 'town')
227 table_factory('search_name',
228 'place_id BIGINT, name_vector INT[], nameaddress_vector INT[]',
229 [(12, [1000], [1001]), (13, [1001], [1002]), (14, [1000, 1001], [1002])])
230 tok = tokenizer_factory()
232 tok.update_statistics(test_config)
234 assert temp_db_cursor.row_set("""SELECT word_id,
235 (info->>'count')::int,
236 (info->>'addr_count')::int
238 WHERE type = 'W'""") == \
239 {(1000, 2, None), (1001, 2, None), (1002, None, 2)}
242 def test_normalize_postcode(analyzer):
243 with analyzer() as anl:
244 anl.normalize_postcode('123') == '123'
245 anl.normalize_postcode('ab-34 ') == 'AB-34'
246 anl.normalize_postcode('38 Б') == '38 Б'
251 @pytest.fixture(autouse=True)
252 def setup(self, analyzer, sql_functions):
253 sanitizers = [{'step': 'clean-postcodes'}]
254 with analyzer(sanitizers=sanitizers, with_postcode=True) as anl:
258 def process_postcode(self, cc, postcode):
259 return self.analyzer.process_place(PlaceInfo({'country_code': cc,
260 'address': {'postcode': postcode}}))
262 def test_update_postcodes_deleted(self, word_table):
263 word_table.add_postcode(' 1234', '1234')
264 word_table.add_postcode(' 5678', '5678')
266 self.analyzer.update_postcodes_from_db()
268 assert word_table.count() == 0
270 def test_process_place_postcode_simple(self, word_table):
271 info = self.process_postcode('de', '12345')
273 assert info['postcode'] == '12345'
275 def test_process_place_postcode_with_space(self, word_table):
276 info = self.process_postcode('in', '123 567')
278 assert info['postcode'] == '123567'
281 def test_update_special_phrase_empty_table(analyzer, word_table):
282 with analyzer() as anl:
283 anl.update_special_phrases([
284 ("König bei", "amenity", "royal", "near"),
285 ("Könige ", "amenity", "royal", "-"),
286 ("street", "highway", "primary", "in")
289 assert word_table.get_special() \
290 == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
291 ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
292 ('STREET', 'street', 'highway', 'primary', 'in')}
295 def test_update_special_phrase_delete_all(analyzer, word_table):
296 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
297 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
299 assert word_table.count_special() == 2
301 with analyzer() as anl:
302 anl.update_special_phrases([], True)
304 assert word_table.count_special() == 0
307 def test_update_special_phrases_no_replace(analyzer, word_table):
308 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
309 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
311 assert word_table.count_special() == 2
313 with analyzer() as anl:
314 anl.update_special_phrases([], False)
316 assert word_table.count_special() == 2
319 def test_update_special_phrase_modify(analyzer, word_table):
320 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
321 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
323 assert word_table.count_special() == 2
325 with analyzer() as anl:
326 anl.update_special_phrases([
327 ('prison', 'amenity', 'prison', 'in'),
328 ('bar', 'highway', 'road', '-'),
329 ('garden', 'leisure', 'garden', 'near')
332 assert word_table.get_special() \
333 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
334 ('BAR', 'bar', 'highway', 'road', None),
335 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
338 def test_add_country_names_new(analyzer, word_table):
339 with analyzer() as anl:
340 anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
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', {'name': 'Schweiz', 'name:fr': 'Suisse'})
352 assert word_table.get_country() == {('ch', 'SCHWEIZ', 'Schweiz'),
353 ('ch', 'SUISSE', 'Suisse')}
356 class TestPlaceNames:
358 @pytest.fixture(autouse=True)
359 def setup(self, analyzer, sql_functions):
360 sanitizers = [{'step': 'split-name-list'},
361 {'step': 'strip-brace-terms'}]
362 with analyzer(sanitizers=sanitizers) as anl:
366 def expect_name_terms(self, info, *expected_terms):
367 tokens = self.analyzer.get_word_token_info(expected_terms)
369 assert token[2] is not None, "No token for {0}".format(token)
371 assert eval(info['names']) == set((t[2] for t in tokens))
373 def process_named_place(self, names):
374 return self.analyzer.process_place(PlaceInfo({'name': names}))
376 def test_simple_names(self):
377 info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
379 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
381 @pytest.mark.parametrize('sep', [',', ';'])
382 def test_names_with_separator(self, sep):
383 info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
385 self.expect_name_terms(info, '#New York', '#Big Apple',
386 'new', 'york', 'big', 'apple')
388 def test_full_names_with_bracket(self):
389 info = self.process_named_place({'name': 'Houseboat (left)'})
391 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
394 def test_country_name(self, word_table):
395 place = PlaceInfo({'name': {'name': 'Norge'},
396 'country_code': 'no',
399 'type': 'administrative'})
401 info = self.analyzer.process_place(place)
403 self.expect_name_terms(info, '#norge', 'norge')
404 assert word_table.get_country() == {('no', 'NORGE', 'Norge')}
407 class TestPlaceAddress:
409 @pytest.fixture(autouse=True)
410 def setup(self, analyzer, sql_functions):
411 hnr = {'step': 'clean-housenumbers',
412 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
413 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr]) as anl:
418 def getorcreate_hnr_id(self, temp_db_cursor):
419 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
420 RETURNS INTEGER AS $$
421 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
423 def process_address(self, **kwargs):
424 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
426 def name_token_set(self, *expected_terms):
427 tokens = self.analyzer.get_word_token_info(expected_terms)
429 assert token[2] is not None, "No token for {0}".format(token)
431 return set((t[2] for t in tokens))
433 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
434 def test_process_place_postcode(self, word_table, pcode):
435 info = self.process_address(postcode=pcode)
437 assert info['postcode'] == pcode
439 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
440 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
441 info = self.process_address(housenumber=hnr)
443 assert info['hnr'] == hnr.upper()
444 assert info['hnr_tokens'] == "{-1}"
446 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
447 info = self.process_address(housenumber='134',
448 conscriptionnumber='134',
451 assert set(info['hnr'].split(';')) == set(('134', '99A'))
452 assert info['hnr_tokens'] == "{-1,-2}"
454 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
455 info = self.process_address(housenumber="45")
456 assert info['hnr_tokens'] == "{-1}"
458 info = self.process_address(housenumber="46")
459 assert info['hnr_tokens'] == "{-2}"
461 info = self.process_address(housenumber="41;45")
462 assert eval(info['hnr_tokens']) == {-1, -3}
464 info = self.process_address(housenumber="41")
465 assert eval(info['hnr_tokens']) == {-3}
467 def test_process_place_street(self):
468 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
469 info = self.process_address(street='Grand Road')
471 assert eval(info['street']) == self.name_token_set('#Grand Road')
473 def test_process_place_nonexisting_street(self):
474 info = self.process_address(street='Grand Road')
476 assert info['street'] == '{}'
478 def test_process_place_multiple_street_tags(self):
479 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road',
481 info = self.process_address(**{'street': 'Grand Road',
482 'street:sym_ul': '05989'})
484 assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
486 def test_process_place_street_empty(self):
487 info = self.process_address(street='🜵')
489 assert info['street'] == '{}'
491 def test_process_place_street_from_cache(self):
492 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
493 self.process_address(street='Grand Road')
495 # request address again
496 info = self.process_address(street='Grand Road')
498 assert eval(info['street']) == self.name_token_set('#Grand Road')
500 def test_process_place_place(self):
501 info = self.process_address(place='Honu Lulu')
503 assert eval(info['place']) == self.name_token_set('HONU', 'LULU', '#HONU LULU')
505 def test_process_place_place_extra(self):
506 info = self.process_address(**{'place:en': 'Honu Lulu'})
508 assert 'place' not in info
510 def test_process_place_place_empty(self):
511 info = self.process_address(place='🜵')
513 assert 'place' not in info
515 def test_process_place_address_terms(self):
516 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
517 suburb='Zwickau', street='Hauptstr',
518 full='right behind the church')
520 city = self.name_token_set('ZWICKAU', '#ZWICKAU')
521 state = self.name_token_set('SACHSEN', '#SACHSEN')
523 result = {k: eval(v) for k, v in info['addr'].items()}
525 assert result == {'city': city, 'suburb': city, 'state': state}
527 def test_process_place_multiple_address_terms(self):
528 info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
530 result = {k: eval(v) for k, v in info['addr'].items()}
532 assert result == {'city': self.name_token_set('Bruxelles', '#Bruxelles')}
534 def test_process_place_address_terms_empty(self):
535 info = self.process_address(country='de', city=' ', street='Hauptstr',
536 full='right behind the church')
538 assert 'addr' not in info
541 class TestPlaceHousenumberWithAnalyser:
543 @pytest.fixture(autouse=True)
544 def setup(self, analyzer, sql_functions):
545 hnr = {'step': 'clean-housenumbers',
546 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
547 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr],
548 with_housenumber=True) as anl:
553 def getorcreate_hnr_id(self, temp_db_cursor):
554 temp_db_cursor.execute("""
555 CREATE OR REPLACE FUNCTION create_analyzed_hnr_id(norm_term TEXT, lookup_terms TEXT[])
556 RETURNS INTEGER AS $$
557 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
559 def process_address(self, **kwargs):
560 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
562 def name_token_set(self, *expected_terms):
563 tokens = self.analyzer.get_word_token_info(expected_terms)
565 assert token[2] is not None, "No token for {0}".format(token)
567 return set((t[2] for t in tokens))
569 @pytest.mark.parametrize('hnr', ['123 a', '1', '101'])
570 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
571 info = self.process_address(housenumber=hnr)
573 assert info['hnr'] == hnr.upper()
574 assert info['hnr_tokens'] == "{-1}"
576 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
577 info = self.process_address(housenumber='134',
578 conscriptionnumber='134',
581 assert set(info['hnr'].split(';')) == set(('134', '99 A'))
582 assert info['hnr_tokens'] == "{-1,-2}"
584 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
585 info = self.process_address(housenumber="45")
586 assert info['hnr_tokens'] == "{-1}"
588 info = self.process_address(housenumber="46")
589 assert info['hnr_tokens'] == "{-2}"
591 info = self.process_address(housenumber="41;45")
592 assert eval(info['hnr_tokens']) == {-1, -3}
594 info = self.process_address(housenumber="41")
595 assert eval(info['hnr_tokens']) == {-3}
598 class TestUpdateWordTokens:
600 @pytest.fixture(autouse=True)
601 def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
602 table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
603 self.tok = tokenizer_factory()
606 def search_entry(self, temp_db_cursor):
607 place_id = itertools.count(1000)
610 temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
611 (next(place_id), list(args)))
615 @pytest.fixture(params=['simple', 'analyzed'])
616 def add_housenumber(self, request, word_table):
617 if request.param == 'simple':
619 word_table.add_housenumber(hid, hnr)
620 elif request.param == 'analyzed':
622 word_table.add_housenumber(hid, [hnr])
626 @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
627 def test_remove_unused_housenumbers(self, add_housenumber, word_table, hnr):
628 word_table.add_housenumber(1000, hnr)
630 assert word_table.count_housenumbers() == 1
631 self.tok.update_word_tokens()
632 assert word_table.count_housenumbers() == 0
634 def test_keep_unused_numeral_housenumbers(self, add_housenumber, word_table):
635 add_housenumber(1000, '5432')
637 assert word_table.count_housenumbers() == 1
638 self.tok.update_word_tokens()
639 assert word_table.count_housenumbers() == 1
641 def test_keep_housenumbers_from_search_name_table(self, add_housenumber,
642 word_table, search_entry):
643 add_housenumber(9999, '5432a')
644 add_housenumber(9991, '9 a')
645 search_entry(123, 9999, 34)
647 assert word_table.count_housenumbers() == 2
648 self.tok.update_word_tokens()
649 assert word_table.count_housenumbers() == 1
651 def test_keep_housenumbers_from_placex_table(self, add_housenumber, word_table, placex_row):
652 add_housenumber(9999, '5432a')
653 add_housenumber(9990, '34z')
654 placex_row(housenumber='34z')
655 placex_row(housenumber='25432a')
657 assert word_table.count_housenumbers() == 2
658 self.tok.update_word_tokens()
659 assert word_table.count_housenumbers() == 1
661 def test_keep_housenumbers_from_placex_table_hnr_list(self, add_housenumber,
662 word_table, placex_row):
663 add_housenumber(9991, '9 b')
664 add_housenumber(9990, '34z')
665 placex_row(housenumber='9 a;9 b;9 c')
667 assert word_table.count_housenumbers() == 2
668 self.tok.update_word_tokens()
669 assert word_table.count_housenumbers() == 1