1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2025 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.db.sql_preprocessor import SQLPreprocessor
19 from nominatim_db.data.place_info import PlaceInfo
21 from mock_icu_word_table import MockIcuWordTable
25 def word_table(temp_db_conn):
26 return MockIcuWordTable(temp_db_conn)
30 def test_config(project_env, tmp_path):
31 sqldir = tmp_path / 'sql'
33 (sqldir / 'tokenizer').mkdir()
34 (sqldir / 'tokenizer' / 'icu_tokenizer.sql').write_text("SELECT 'a'")
36 project_env.lib_dir.sql = sqldir
42 def tokenizer_factory(dsn, property_table, sql_preprocessor, place_table, word_table):
44 return icu_tokenizer.create(dsn)
50 def db_prop(temp_db_conn):
51 def _get_db_property(name):
52 return properties.get_property(temp_db_conn, name)
54 return _get_db_property
58 def analyzer(tokenizer_factory, test_config, monkeypatch,
59 temp_db_with_extensions, tmp_path):
60 sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
61 sql.write_text("SELECT 'a';")
63 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
64 tok = tokenizer_factory()
65 tok.init_new_db(test_config)
68 def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
69 variants=('~gasse -> gasse', 'street => st', ),
70 sanitizers=[], with_housenumber=False,
72 cfgstr = {'normalization': list(norm),
73 'sanitizers': sanitizers,
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(yaml.dump(cfgstr))
84 tok.loader = nominatim_db.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
86 return tok.name_analyzer()
92 def sql_functions(temp_db_conn, def_config, src_dir):
93 orig_sql = def_config.lib_dir.sql
94 def_config.lib_dir.sql = src_dir / 'lib-sql'
95 sqlproc = SQLPreprocessor(temp_db_conn, def_config)
96 sqlproc.run_sql_file(temp_db_conn, 'functions/utils.sql')
97 sqlproc.run_sql_file(temp_db_conn, 'tokenizer/icu_tokenizer.sql')
98 def_config.lib_dir.sql = orig_sql
102 def getorcreate_full_word(temp_db_cursor):
103 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
104 norm_term TEXT, lookup_terms TEXT[],
106 OUT partial_tokens INT[])
109 partial_terms TEXT[] = '{}'::TEXT[];
114 SELECT min(word_id) INTO full_token
115 FROM word WHERE info->>'word' = norm_term and type = 'W';
117 IF full_token IS NULL THEN
118 full_token := nextval('seq_word');
119 INSERT INTO word (word_id, word_token, type, info)
120 SELECT full_token, lookup_term, 'W',
121 json_build_object('word', norm_term, 'count', 0)
122 FROM unnest(lookup_terms) as lookup_term;
125 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
127 IF NOT (ARRAY[term] <@ partial_terms) THEN
128 partial_terms := partial_terms || term;
132 partial_tokens := '{}'::INT[];
133 FOR term IN SELECT unnest(partial_terms) LOOP
134 SELECT min(word_id), max(info->>'count') INTO term_id, term_count
135 FROM word WHERE word_token = term and type = 'w';
137 IF term_id IS NULL THEN
138 term_id := nextval('seq_word');
140 INSERT INTO word (word_id, word_token, type, info)
141 VALUES (term_id, term, 'w', json_build_object('count', term_count));
144 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
145 partial_tokens := partial_tokens || term_id;
154 def test_init_new(tokenizer_factory, test_config, db_prop):
155 tok = tokenizer_factory()
156 tok.init_new_db(test_config)
158 prop = db_prop(nominatim_db.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES)
160 assert prop.startswith(':: lower ();')
163 def test_init_word_table(tokenizer_factory, test_config, place_row, temp_db_cursor):
164 place_row(names={'name': 'Test Area', 'ref': '52'})
165 place_row(names={'name': 'No Area'})
166 place_row(names={'name': 'Holzstrasse'})
168 tok = tokenizer_factory()
169 tok.init_new_db(test_config)
171 assert temp_db_cursor.table_exists('word')
174 def test_init_from_project(test_config, tokenizer_factory):
175 tok = tokenizer_factory()
176 tok.init_new_db(test_config)
178 tok = tokenizer_factory()
179 tok.init_from_project(test_config)
181 assert tok.loader is not None
184 def test_update_sql_functions(db_prop, temp_db_cursor,
185 tokenizer_factory, test_config, table_factory,
187 tok = tokenizer_factory()
188 tok.init_new_db(test_config)
190 table_factory('test', 'txt TEXT')
192 func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
193 func_file.write_text("""INSERT INTO test VALUES (1133)""")
195 tok.update_sql_functions(test_config)
197 test_content = temp_db_cursor.row_set('SELECT * FROM test')
198 assert test_content == set((('1133', ), ))
201 def test_finalize_import(tokenizer_factory, temp_db_cursor,
202 test_config, sql_preprocessor_cfg):
203 tok = tokenizer_factory()
204 tok.init_new_db(test_config)
206 assert not temp_db_cursor.index_exists('word', 'idx_word_word_id')
208 tok.finalize_import(test_config)
210 assert temp_db_cursor.index_exists('word', 'idx_word_word_id')
213 def test_check_database(test_config, tokenizer_factory,
214 temp_db_cursor, sql_preprocessor_cfg):
215 tok = tokenizer_factory()
216 tok.init_new_db(test_config)
218 assert tok.check_database(test_config) is None
221 def test_update_statistics_reverse_only(word_table, tokenizer_factory, test_config):
222 tok = tokenizer_factory()
223 tok.update_statistics(test_config)
226 def test_update_statistics(word_table, table_factory, temp_db_cursor,
227 tokenizer_factory, test_config):
228 word_table.add_full_word(1000, 'hello')
229 word_table.add_full_word(1001, 'bye')
230 word_table.add_full_word(1002, 'town')
231 table_factory('search_name',
232 'place_id BIGINT, name_vector INT[], nameaddress_vector INT[]',
233 [(12, [1000], [1001]), (13, [1001], [1002]), (14, [1000, 1001], [1002])])
234 tok = tokenizer_factory()
236 tok.update_statistics(test_config)
238 assert temp_db_cursor.row_set("""SELECT word_id,
239 (info->>'count')::int,
240 (info->>'addr_count')::int
242 WHERE type = 'W'""") == \
243 {(1000, 2, None), (1001, 2, None), (1002, None, 2)}
246 def test_normalize_postcode(analyzer):
247 with analyzer() as anl:
248 anl.normalize_postcode('123') == '123'
249 anl.normalize_postcode('ab-34 ') == 'AB-34'
250 anl.normalize_postcode('38 Б') == '38 Б'
255 @pytest.fixture(autouse=True)
256 def setup(self, analyzer, sql_functions):
257 sanitizers = [{'step': 'clean-postcodes'}]
258 with analyzer(sanitizers=sanitizers, with_postcode=True) as anl:
262 def process_postcode(self, cc, postcode):
263 return self.analyzer.process_place(PlaceInfo({'country_code': cc,
264 'address': {'postcode': postcode}}))
266 def test_update_postcodes_deleted(self, word_table):
267 word_table.add_postcode(' 1234', '1234')
268 word_table.add_postcode(' 5678', '5678')
270 self.analyzer.update_postcodes_from_db()
272 assert word_table.count() == 0
274 def test_process_place_postcode_simple(self, word_table):
275 info = self.process_postcode('de', '12345')
277 assert info['postcode'] == '12345'
279 def test_process_place_postcode_with_space(self, word_table):
280 info = self.process_postcode('in', '123 567')
282 assert info['postcode'] == '123567'
285 def test_update_special_phrase_empty_table(analyzer, word_table):
286 with analyzer() as anl:
287 anl.update_special_phrases([
288 ("König bei", "amenity", "royal", "near"),
289 ("Könige ", "amenity", "royal", "-"),
290 ("street", "highway", "primary", "in")
293 assert word_table.get_special() \
294 == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
295 ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
296 ('STREET', 'street', 'highway', 'primary', 'in')}
299 def test_update_special_phrase_delete_all(analyzer, word_table):
300 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
301 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
303 assert word_table.count_special() == 2
305 with analyzer() as anl:
306 anl.update_special_phrases([], True)
308 assert word_table.count_special() == 0
311 def test_update_special_phrases_no_replace(analyzer, word_table):
312 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
313 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
315 assert word_table.count_special() == 2
317 with analyzer() as anl:
318 anl.update_special_phrases([], False)
320 assert word_table.count_special() == 2
323 def test_update_special_phrase_modify(analyzer, word_table):
324 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
325 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
327 assert word_table.count_special() == 2
329 with analyzer() as anl:
330 anl.update_special_phrases([
331 ('prison', 'amenity', 'prison', 'in'),
332 ('bar', 'highway', 'road', '-'),
333 ('garden', 'leisure', 'garden', 'near')
336 assert word_table.get_special() \
337 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
338 ('BAR', 'bar', 'highway', 'road', None),
339 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
342 def test_add_country_names_new(analyzer, word_table):
343 with analyzer() as anl:
344 anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
346 assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
349 def test_add_country_names_extend(analyzer, word_table):
350 word_table.add_country('ch', 'SCHWEIZ')
352 with analyzer() as anl:
353 anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
355 assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
358 class TestPlaceNames:
360 @pytest.fixture(autouse=True)
361 def setup(self, analyzer, sql_functions):
362 sanitizers = [{'step': 'split-name-list'},
363 {'step': 'strip-brace-terms'}]
364 with analyzer(sanitizers=sanitizers) as anl:
368 def expect_name_terms(self, info, *expected_terms):
369 tokens = self.analyzer.get_word_token_info(expected_terms)
371 assert token[2] is not None, "No token for {0}".format(token)
373 assert eval(info['names']) == set((t[2] for t in tokens))
375 def process_named_place(self, names):
376 return self.analyzer.process_place(PlaceInfo({'name': names}))
378 def test_simple_names(self):
379 info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
381 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
383 @pytest.mark.parametrize('sep', [',', ';'])
384 def test_names_with_separator(self, sep):
385 info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
387 self.expect_name_terms(info, '#New York', '#Big Apple',
388 'new', 'york', 'big', 'apple')
390 def test_full_names_with_bracket(self):
391 info = self.process_named_place({'name': 'Houseboat (left)'})
393 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
396 def test_country_name(self, word_table):
397 place = PlaceInfo({'name': {'name': 'Norge'},
398 'country_code': 'no',
401 'type': 'administrative'})
403 info = self.analyzer.process_place(place)
405 self.expect_name_terms(info, '#norge', 'norge')
406 assert word_table.get_country() == {('no', 'NORGE')}
409 class TestPlaceAddress:
411 @pytest.fixture(autouse=True)
412 def setup(self, analyzer, sql_functions):
413 hnr = {'step': 'clean-housenumbers',
414 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
415 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr]) as anl:
420 def getorcreate_hnr_id(self, temp_db_cursor):
421 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
422 RETURNS INTEGER AS $$
423 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
425 def process_address(self, **kwargs):
426 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
428 def name_token_set(self, *expected_terms):
429 tokens = self.analyzer.get_word_token_info(expected_terms)
431 assert token[2] is not None, "No token for {0}".format(token)
433 return set((t[2] for t in tokens))
435 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
436 def test_process_place_postcode(self, word_table, pcode):
437 info = self.process_address(postcode=pcode)
439 assert info['postcode'] == pcode
441 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
442 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
443 info = self.process_address(housenumber=hnr)
445 assert info['hnr'] == hnr.upper()
446 assert info['hnr_tokens'] == "{-1}"
448 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
449 info = self.process_address(housenumber='134',
450 conscriptionnumber='134',
453 assert set(info['hnr'].split(';')) == set(('134', '99A'))
454 assert info['hnr_tokens'] == "{-1,-2}"
456 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
457 info = self.process_address(housenumber="45")
458 assert info['hnr_tokens'] == "{-1}"
460 info = self.process_address(housenumber="46")
461 assert info['hnr_tokens'] == "{-2}"
463 info = self.process_address(housenumber="41;45")
464 assert eval(info['hnr_tokens']) == {-1, -3}
466 info = self.process_address(housenumber="41")
467 assert eval(info['hnr_tokens']) == {-3}
469 def test_process_place_street(self):
470 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
471 info = self.process_address(street='Grand Road')
473 assert eval(info['street']) == self.name_token_set('#Grand Road')
475 def test_process_place_nonexisting_street(self):
476 info = self.process_address(street='Grand Road')
478 assert info['street'] == '{}'
480 def test_process_place_multiple_street_tags(self):
481 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road',
483 info = self.process_address(**{'street': 'Grand Road',
484 'street:sym_ul': '05989'})
486 assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
488 def test_process_place_street_empty(self):
489 info = self.process_address(street='🜵')
491 assert info['street'] == '{}'
493 def test_process_place_street_from_cache(self):
494 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
495 self.process_address(street='Grand Road')
497 # request address again
498 info = self.process_address(street='Grand Road')
500 assert eval(info['street']) == self.name_token_set('#Grand Road')
502 def test_process_place_place(self):
503 info = self.process_address(place='Honu Lulu')
505 assert eval(info['place']) == self.name_token_set('HONU', 'LULU', '#HONU LULU')
507 def test_process_place_place_extra(self):
508 info = self.process_address(**{'place:en': 'Honu Lulu'})
510 assert 'place' not in info
512 def test_process_place_place_empty(self):
513 info = self.process_address(place='🜵')
515 assert 'place' not in info
517 def test_process_place_address_terms(self):
518 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
519 suburb='Zwickau', street='Hauptstr',
520 full='right behind the church')
522 city = self.name_token_set('ZWICKAU', '#ZWICKAU')
523 state = self.name_token_set('SACHSEN', '#SACHSEN')
525 result = {k: eval(v) for k, v in info['addr'].items()}
527 assert result == {'city': city, 'suburb': city, 'state': state}
529 def test_process_place_multiple_address_terms(self):
530 info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
532 result = {k: eval(v) for k, v in info['addr'].items()}
534 assert result == {'city': self.name_token_set('Bruxelles', '#Bruxelles')}
536 def test_process_place_address_terms_empty(self):
537 info = self.process_address(country='de', city=' ', street='Hauptstr',
538 full='right behind the church')
540 assert 'addr' not in info
543 class TestPlaceHousenumberWithAnalyser:
545 @pytest.fixture(autouse=True)
546 def setup(self, analyzer, sql_functions):
547 hnr = {'step': 'clean-housenumbers',
548 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
549 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr],
550 with_housenumber=True) as anl:
555 def getorcreate_hnr_id(self, temp_db_cursor):
556 temp_db_cursor.execute("""
557 CREATE OR REPLACE FUNCTION create_analyzed_hnr_id(norm_term TEXT, lookup_terms TEXT[])
558 RETURNS INTEGER AS $$
559 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
561 def process_address(self, **kwargs):
562 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
564 def name_token_set(self, *expected_terms):
565 tokens = self.analyzer.get_word_token_info(expected_terms)
567 assert token[2] is not None, "No token for {0}".format(token)
569 return set((t[2] for t in tokens))
571 @pytest.mark.parametrize('hnr', ['123 a', '1', '101'])
572 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
573 info = self.process_address(housenumber=hnr)
575 assert info['hnr'] == hnr.upper()
576 assert info['hnr_tokens'] == "{-1}"
578 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
579 info = self.process_address(housenumber='134',
580 conscriptionnumber='134',
583 assert set(info['hnr'].split(';')) == set(('134', '99 A'))
584 assert info['hnr_tokens'] == "{-1,-2}"
586 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
587 info = self.process_address(housenumber="45")
588 assert info['hnr_tokens'] == "{-1}"
590 info = self.process_address(housenumber="46")
591 assert info['hnr_tokens'] == "{-2}"
593 info = self.process_address(housenumber="41;45")
594 assert eval(info['hnr_tokens']) == {-1, -3}
596 info = self.process_address(housenumber="41")
597 assert eval(info['hnr_tokens']) == {-3}
600 class TestUpdateWordTokens:
602 @pytest.fixture(autouse=True)
603 def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
604 table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
605 self.tok = tokenizer_factory()
608 def search_entry(self, temp_db_cursor):
609 place_id = itertools.count(1000)
612 temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
613 (next(place_id), list(args)))
617 @pytest.fixture(params=['simple', 'analyzed'])
618 def add_housenumber(self, request, word_table):
619 if request.param == 'simple':
621 word_table.add_housenumber(hid, hnr)
622 elif request.param == 'analyzed':
624 word_table.add_housenumber(hid, [hnr])
628 @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
629 def test_remove_unused_housenumbers(self, add_housenumber, word_table, hnr):
630 word_table.add_housenumber(1000, hnr)
632 assert word_table.count_housenumbers() == 1
633 self.tok.update_word_tokens()
634 assert word_table.count_housenumbers() == 0
636 def test_keep_unused_numeral_housenumbers(self, add_housenumber, word_table):
637 add_housenumber(1000, '5432')
639 assert word_table.count_housenumbers() == 1
640 self.tok.update_word_tokens()
641 assert word_table.count_housenumbers() == 1
643 def test_keep_housenumbers_from_search_name_table(self, add_housenumber,
644 word_table, search_entry):
645 add_housenumber(9999, '5432a')
646 add_housenumber(9991, '9 a')
647 search_entry(123, 9999, 34)
649 assert word_table.count_housenumbers() == 2
650 self.tok.update_word_tokens()
651 assert word_table.count_housenumbers() == 1
653 def test_keep_housenumbers_from_placex_table(self, add_housenumber, word_table,
655 add_housenumber(9999, '5432a')
656 add_housenumber(9990, '34z')
657 placex_table.add(housenumber='34z')
658 placex_table.add(housenumber='25432a')
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_hnr_list(self, add_housenumber,
665 word_table, placex_table):
666 add_housenumber(9991, '9 b')
667 add_housenumber(9990, '34z')
668 placex_table.add(housenumber='9 a;9 b;9 c')
670 assert word_table.count_housenumbers() == 2
671 self.tok.update_word_tokens()
672 assert word_table.count_housenumbers() == 1