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, tmp_path, property_table,
43 sql_preprocessor, place_table, word_table):
44 (tmp_path / 'tokenizer').mkdir()
47 return icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
53 def db_prop(temp_db_conn):
54 def _get_db_property(name):
55 return properties.get_property(temp_db_conn, name)
57 return _get_db_property
61 def analyzer(tokenizer_factory, test_config, monkeypatch,
62 temp_db_with_extensions, tmp_path):
63 sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
64 sql.write_text("SELECT 'a';")
66 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
67 tok = tokenizer_factory()
68 tok.init_new_db(test_config)
71 def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
72 variants=('~gasse -> gasse', 'street => st', ),
73 sanitizers=[], with_housenumber=False,
75 cfgstr = {'normalization': list(norm),
76 'sanitizers': sanitizers,
77 'transliteration': list(trans),
78 'token-analysis': [{'analyzer': 'generic',
79 'variants': [{'words': list(variants)}]}]}
81 cfgstr['token-analysis'].append({'id': '@housenumber',
82 'analyzer': 'housenumbers'})
84 cfgstr['token-analysis'].append({'id': '@postcode',
85 'analyzer': 'postcodes'})
86 (test_config.project_dir / 'icu_tokenizer.yaml').write_text(yaml.dump(cfgstr))
87 tok.loader = nominatim_db.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
89 return tok.name_analyzer()
95 def sql_functions(temp_db_conn, def_config, src_dir):
96 orig_sql = def_config.lib_dir.sql
97 def_config.lib_dir.sql = src_dir / 'lib-sql'
98 sqlproc = SQLPreprocessor(temp_db_conn, def_config)
99 sqlproc.run_sql_file(temp_db_conn, 'functions/utils.sql')
100 sqlproc.run_sql_file(temp_db_conn, 'tokenizer/icu_tokenizer.sql')
101 def_config.lib_dir.sql = orig_sql
105 def getorcreate_full_word(temp_db_cursor):
106 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
107 norm_term TEXT, lookup_terms TEXT[],
109 OUT partial_tokens INT[])
112 partial_terms TEXT[] = '{}'::TEXT[];
117 SELECT min(word_id) INTO full_token
118 FROM word WHERE info->>'word' = norm_term and type = 'W';
120 IF full_token IS NULL THEN
121 full_token := nextval('seq_word');
122 INSERT INTO word (word_id, word_token, type, info)
123 SELECT full_token, lookup_term, 'W',
124 json_build_object('word', norm_term, 'count', 0)
125 FROM unnest(lookup_terms) as lookup_term;
128 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
130 IF NOT (ARRAY[term] <@ partial_terms) THEN
131 partial_terms := partial_terms || term;
135 partial_tokens := '{}'::INT[];
136 FOR term IN SELECT unnest(partial_terms) LOOP
137 SELECT min(word_id), max(info->>'count') INTO term_id, term_count
138 FROM word WHERE word_token = term and type = 'w';
140 IF term_id IS NULL THEN
141 term_id := nextval('seq_word');
143 INSERT INTO word (word_id, word_token, type, info)
144 VALUES (term_id, term, 'w', json_build_object('count', term_count));
147 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
148 partial_tokens := partial_tokens || term_id;
157 def test_init_new(tokenizer_factory, test_config, db_prop):
158 tok = tokenizer_factory()
159 tok.init_new_db(test_config)
161 prop = db_prop(nominatim_db.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES)
163 assert prop.startswith(':: lower ();')
166 def test_init_word_table(tokenizer_factory, test_config, place_row, temp_db_cursor):
167 place_row(names={'name': 'Test Area', 'ref': '52'})
168 place_row(names={'name': 'No Area'})
169 place_row(names={'name': 'Holzstrasse'})
171 tok = tokenizer_factory()
172 tok.init_new_db(test_config)
174 assert temp_db_cursor.table_exists('word')
177 def test_init_from_project(test_config, tokenizer_factory):
178 tok = tokenizer_factory()
179 tok.init_new_db(test_config)
181 tok = tokenizer_factory()
182 tok.init_from_project(test_config)
184 assert tok.loader is not None
187 def test_update_sql_functions(db_prop, temp_db_cursor,
188 tokenizer_factory, test_config, table_factory,
190 tok = tokenizer_factory()
191 tok.init_new_db(test_config)
193 table_factory('test', 'txt TEXT')
195 func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
196 func_file.write_text("""INSERT INTO test VALUES (1133)""")
198 tok.update_sql_functions(test_config)
200 test_content = temp_db_cursor.row_set('SELECT * FROM test')
201 assert test_content == set((('1133', ), ))
204 def test_finalize_import(tokenizer_factory, temp_db_cursor,
205 test_config, sql_preprocessor_cfg):
206 tok = tokenizer_factory()
207 tok.init_new_db(test_config)
209 assert not temp_db_cursor.index_exists('word', 'idx_word_word_id')
211 tok.finalize_import(test_config)
213 assert temp_db_cursor.index_exists('word', 'idx_word_word_id')
216 def test_check_database(test_config, tokenizer_factory,
217 temp_db_cursor, sql_preprocessor_cfg):
218 tok = tokenizer_factory()
219 tok.init_new_db(test_config)
221 assert tok.check_database(test_config) is None
224 def test_update_statistics_reverse_only(word_table, tokenizer_factory, test_config):
225 tok = tokenizer_factory()
226 tok.update_statistics(test_config)
229 def test_update_statistics(word_table, table_factory, temp_db_cursor,
230 tokenizer_factory, test_config):
231 word_table.add_full_word(1000, 'hello')
232 word_table.add_full_word(1001, 'bye')
233 word_table.add_full_word(1002, 'town')
234 table_factory('search_name',
235 'place_id BIGINT, name_vector INT[], nameaddress_vector INT[]',
236 [(12, [1000], [1001]), (13, [1001], [1002]), (14, [1000, 1001], [1002])])
237 tok = tokenizer_factory()
239 tok.update_statistics(test_config)
241 assert temp_db_cursor.row_set("""SELECT word_id,
242 (info->>'count')::int,
243 (info->>'addr_count')::int
245 WHERE type = 'W'""") == \
246 {(1000, 2, None), (1001, 2, None), (1002, None, 2)}
249 def test_normalize_postcode(analyzer):
250 with analyzer() as anl:
251 anl.normalize_postcode('123') == '123'
252 anl.normalize_postcode('ab-34 ') == 'AB-34'
253 anl.normalize_postcode('38 Б') == '38 Б'
258 @pytest.fixture(autouse=True)
259 def setup(self, analyzer, sql_functions):
260 sanitizers = [{'step': 'clean-postcodes'}]
261 with analyzer(sanitizers=sanitizers, with_postcode=True) as anl:
265 def process_postcode(self, cc, postcode):
266 return self.analyzer.process_place(PlaceInfo({'country_code': cc,
267 'address': {'postcode': postcode}}))
269 def test_update_postcodes_deleted(self, word_table):
270 word_table.add_postcode(' 1234', '1234')
271 word_table.add_postcode(' 5678', '5678')
273 self.analyzer.update_postcodes_from_db()
275 assert word_table.count() == 0
277 def test_process_place_postcode_simple(self, word_table):
278 info = self.process_postcode('de', '12345')
280 assert info['postcode'] == '12345'
282 def test_process_place_postcode_with_space(self, word_table):
283 info = self.process_postcode('in', '123 567')
285 assert info['postcode'] == '123567'
288 def test_update_special_phrase_empty_table(analyzer, word_table):
289 with analyzer() as anl:
290 anl.update_special_phrases([
291 ("König bei", "amenity", "royal", "near"),
292 ("Könige ", "amenity", "royal", "-"),
293 ("street", "highway", "primary", "in")
296 assert word_table.get_special() \
297 == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
298 ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
299 ('STREET', 'street', 'highway', 'primary', 'in')}
302 def test_update_special_phrase_delete_all(analyzer, word_table):
303 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
304 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
306 assert word_table.count_special() == 2
308 with analyzer() as anl:
309 anl.update_special_phrases([], True)
311 assert word_table.count_special() == 0
314 def test_update_special_phrases_no_replace(analyzer, word_table):
315 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
316 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
318 assert word_table.count_special() == 2
320 with analyzer() as anl:
321 anl.update_special_phrases([], False)
323 assert word_table.count_special() == 2
326 def test_update_special_phrase_modify(analyzer, word_table):
327 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
328 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
330 assert word_table.count_special() == 2
332 with analyzer() as anl:
333 anl.update_special_phrases([
334 ('prison', 'amenity', 'prison', 'in'),
335 ('bar', 'highway', 'road', '-'),
336 ('garden', 'leisure', 'garden', 'near')
339 assert word_table.get_special() \
340 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
341 ('BAR', 'bar', 'highway', 'road', None),
342 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
345 def test_add_country_names_new(analyzer, word_table):
346 with analyzer() as anl:
347 anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
349 assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
352 def test_add_country_names_extend(analyzer, word_table):
353 word_table.add_country('ch', 'SCHWEIZ')
355 with analyzer() as anl:
356 anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
358 assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
361 class TestPlaceNames:
363 @pytest.fixture(autouse=True)
364 def setup(self, analyzer, sql_functions):
365 sanitizers = [{'step': 'split-name-list'},
366 {'step': 'strip-brace-terms'}]
367 with analyzer(sanitizers=sanitizers) 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 return self.analyzer.process_place(PlaceInfo({'name': names}))
381 def test_simple_names(self):
382 info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
384 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
386 @pytest.mark.parametrize('sep', [',', ';'])
387 def test_names_with_separator(self, sep):
388 info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
390 self.expect_name_terms(info, '#New York', '#Big Apple',
391 'new', 'york', 'big', 'apple')
393 def test_full_names_with_bracket(self):
394 info = self.process_named_place({'name': 'Houseboat (left)'})
396 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
399 def test_country_name(self, word_table):
400 place = PlaceInfo({'name': {'name': 'Norge'},
401 'country_code': 'no',
404 'type': 'administrative'})
406 info = self.analyzer.process_place(place)
408 self.expect_name_terms(info, '#norge', 'norge')
409 assert word_table.get_country() == {('no', 'NORGE')}
412 class TestPlaceAddress:
414 @pytest.fixture(autouse=True)
415 def setup(self, analyzer, sql_functions):
416 hnr = {'step': 'clean-housenumbers',
417 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
418 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr]) as anl:
423 def getorcreate_hnr_id(self, temp_db_cursor):
424 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
425 RETURNS INTEGER AS $$
426 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
428 def process_address(self, **kwargs):
429 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
431 def name_token_set(self, *expected_terms):
432 tokens = self.analyzer.get_word_token_info(expected_terms)
434 assert token[2] is not None, "No token for {0}".format(token)
436 return set((t[2] for t in tokens))
438 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
439 def test_process_place_postcode(self, word_table, pcode):
440 info = self.process_address(postcode=pcode)
442 assert info['postcode'] == pcode
444 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
445 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
446 info = self.process_address(housenumber=hnr)
448 assert info['hnr'] == hnr.upper()
449 assert info['hnr_tokens'] == "{-1}"
451 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
452 info = self.process_address(housenumber='134',
453 conscriptionnumber='134',
456 assert set(info['hnr'].split(';')) == set(('134', '99A'))
457 assert info['hnr_tokens'] == "{-1,-2}"
459 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
460 info = self.process_address(housenumber="45")
461 assert info['hnr_tokens'] == "{-1}"
463 info = self.process_address(housenumber="46")
464 assert info['hnr_tokens'] == "{-2}"
466 info = self.process_address(housenumber="41;45")
467 assert eval(info['hnr_tokens']) == {-1, -3}
469 info = self.process_address(housenumber="41")
470 assert eval(info['hnr_tokens']) == {-3}
472 def test_process_place_street(self):
473 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
474 info = self.process_address(street='Grand Road')
476 assert eval(info['street']) == self.name_token_set('#Grand Road')
478 def test_process_place_nonexisting_street(self):
479 info = self.process_address(street='Grand Road')
481 assert info['street'] == '{}'
483 def test_process_place_multiple_street_tags(self):
484 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road',
486 info = self.process_address(**{'street': 'Grand Road',
487 'street:sym_ul': '05989'})
489 assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
491 def test_process_place_street_empty(self):
492 info = self.process_address(street='🜵')
494 assert info['street'] == '{}'
496 def test_process_place_street_from_cache(self):
497 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
498 self.process_address(street='Grand Road')
500 # request address again
501 info = self.process_address(street='Grand Road')
503 assert eval(info['street']) == self.name_token_set('#Grand Road')
505 def test_process_place_place(self):
506 info = self.process_address(place='Honu Lulu')
508 assert eval(info['place']) == self.name_token_set('HONU', 'LULU', '#HONU LULU')
510 def test_process_place_place_extra(self):
511 info = self.process_address(**{'place:en': 'Honu Lulu'})
513 assert 'place' not in info
515 def test_process_place_place_empty(self):
516 info = self.process_address(place='🜵')
518 assert 'place' not in info
520 def test_process_place_address_terms(self):
521 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
522 suburb='Zwickau', street='Hauptstr',
523 full='right behind the church')
525 city = self.name_token_set('ZWICKAU', '#ZWICKAU')
526 state = self.name_token_set('SACHSEN', '#SACHSEN')
528 result = {k: eval(v) for k, v in info['addr'].items()}
530 assert result == {'city': city, 'suburb': city, 'state': state}
532 def test_process_place_multiple_address_terms(self):
533 info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
535 result = {k: eval(v) for k, v in info['addr'].items()}
537 assert result == {'city': self.name_token_set('Bruxelles', '#Bruxelles')}
539 def test_process_place_address_terms_empty(self):
540 info = self.process_address(country='de', city=' ', street='Hauptstr',
541 full='right behind the church')
543 assert 'addr' not in info
546 class TestPlaceHousenumberWithAnalyser:
548 @pytest.fixture(autouse=True)
549 def setup(self, analyzer, sql_functions):
550 hnr = {'step': 'clean-housenumbers',
551 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
552 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr],
553 with_housenumber=True) as anl:
558 def getorcreate_hnr_id(self, temp_db_cursor):
559 temp_db_cursor.execute("""
560 CREATE OR REPLACE FUNCTION create_analyzed_hnr_id(norm_term TEXT, lookup_terms TEXT[])
561 RETURNS INTEGER AS $$
562 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
564 def process_address(self, **kwargs):
565 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
567 def name_token_set(self, *expected_terms):
568 tokens = self.analyzer.get_word_token_info(expected_terms)
570 assert token[2] is not None, "No token for {0}".format(token)
572 return set((t[2] for t in tokens))
574 @pytest.mark.parametrize('hnr', ['123 a', '1', '101'])
575 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
576 info = self.process_address(housenumber=hnr)
578 assert info['hnr'] == hnr.upper()
579 assert info['hnr_tokens'] == "{-1}"
581 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
582 info = self.process_address(housenumber='134',
583 conscriptionnumber='134',
586 assert set(info['hnr'].split(';')) == set(('134', '99 A'))
587 assert info['hnr_tokens'] == "{-1,-2}"
589 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
590 info = self.process_address(housenumber="45")
591 assert info['hnr_tokens'] == "{-1}"
593 info = self.process_address(housenumber="46")
594 assert info['hnr_tokens'] == "{-2}"
596 info = self.process_address(housenumber="41;45")
597 assert eval(info['hnr_tokens']) == {-1, -3}
599 info = self.process_address(housenumber="41")
600 assert eval(info['hnr_tokens']) == {-3}
603 class TestUpdateWordTokens:
605 @pytest.fixture(autouse=True)
606 def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
607 table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
608 self.tok = tokenizer_factory()
611 def search_entry(self, temp_db_cursor):
612 place_id = itertools.count(1000)
615 temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
616 (next(place_id), list(args)))
620 @pytest.fixture(params=['simple', 'analyzed'])
621 def add_housenumber(self, request, word_table):
622 if request.param == 'simple':
624 word_table.add_housenumber(hid, hnr)
625 elif request.param == 'analyzed':
627 word_table.add_housenumber(hid, [hnr])
631 @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
632 def test_remove_unused_housenumbers(self, add_housenumber, word_table, hnr):
633 word_table.add_housenumber(1000, hnr)
635 assert word_table.count_housenumbers() == 1
636 self.tok.update_word_tokens()
637 assert word_table.count_housenumbers() == 0
639 def test_keep_unused_numeral_housenumbers(self, add_housenumber, word_table):
640 add_housenumber(1000, '5432')
642 assert word_table.count_housenumbers() == 1
643 self.tok.update_word_tokens()
644 assert word_table.count_housenumbers() == 1
646 def test_keep_housenumbers_from_search_name_table(self, add_housenumber,
647 word_table, search_entry):
648 add_housenumber(9999, '5432a')
649 add_housenumber(9991, '9 a')
650 search_entry(123, 9999, 34)
652 assert word_table.count_housenumbers() == 2
653 self.tok.update_word_tokens()
654 assert word_table.count_housenumbers() == 1
656 def test_keep_housenumbers_from_placex_table(self, add_housenumber, word_table,
658 add_housenumber(9999, '5432a')
659 add_housenumber(9990, '34z')
660 placex_table.add(housenumber='34z')
661 placex_table.add(housenumber='25432a')
663 assert word_table.count_housenumbers() == 2
664 self.tok.update_word_tokens()
665 assert word_table.count_housenumbers() == 1
667 def test_keep_housenumbers_from_placex_table_hnr_list(self, add_housenumber,
668 word_table, placex_table):
669 add_housenumber(9991, '9 b')
670 add_housenumber(9990, '34z')
671 placex_table.add(housenumber='9 a;9 b;9 c')
673 assert word_table.count_housenumbers() == 2
674 self.tok.update_word_tokens()
675 assert word_table.count_housenumbers() == 1