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 table_factory('search_name',
234 'place_id BIGINT, name_vector INT[], nameaddress_vector INT[]',
235 [(12, [1000], [1001])])
236 tok = tokenizer_factory()
238 tok.update_statistics(test_config)
240 assert temp_db_cursor.scalar("""SELECT count(*) FROM word
241 WHERE type = 'W' and word_id = 1000 and
242 (info->>'count')::int > 0""") == 1
243 assert temp_db_cursor.scalar("""SELECT count(*) FROM word
244 WHERE type = 'W' and word_id = 1001 and
245 (info->>'addr_count')::int > 0""") == 1
248 def test_normalize_postcode(analyzer):
249 with analyzer() as anl:
250 anl.normalize_postcode('123') == '123'
251 anl.normalize_postcode('ab-34 ') == 'AB-34'
252 anl.normalize_postcode('38 Б') == '38 Б'
257 @pytest.fixture(autouse=True)
258 def setup(self, analyzer, sql_functions):
259 sanitizers = [{'step': 'clean-postcodes'}]
260 with analyzer(sanitizers=sanitizers, with_postcode=True) as anl:
264 def process_postcode(self, cc, postcode):
265 return self.analyzer.process_place(PlaceInfo({'country_code': cc,
266 'address': {'postcode': postcode}}))
268 def test_update_postcodes_deleted(self, word_table):
269 word_table.add_postcode(' 1234', '1234')
270 word_table.add_postcode(' 5678', '5678')
272 self.analyzer.update_postcodes_from_db()
274 assert word_table.count() == 0
276 def test_process_place_postcode_simple(self, word_table):
277 info = self.process_postcode('de', '12345')
279 assert info['postcode'] == '12345'
281 def test_process_place_postcode_with_space(self, word_table):
282 info = self.process_postcode('in', '123 567')
284 assert info['postcode'] == '123567'
287 def test_update_special_phrase_empty_table(analyzer, word_table):
288 with analyzer() as anl:
289 anl.update_special_phrases([
290 ("König bei", "amenity", "royal", "near"),
291 ("Könige ", "amenity", "royal", "-"),
292 ("street", "highway", "primary", "in")
295 assert word_table.get_special() \
296 == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
297 ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
298 ('STREET', 'street', 'highway', 'primary', 'in')}
301 def test_update_special_phrase_delete_all(analyzer, word_table):
302 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
303 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
305 assert word_table.count_special() == 2
307 with analyzer() as anl:
308 anl.update_special_phrases([], True)
310 assert word_table.count_special() == 0
313 def test_update_special_phrases_no_replace(analyzer, word_table):
314 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
315 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
317 assert word_table.count_special() == 2
319 with analyzer() as anl:
320 anl.update_special_phrases([], False)
322 assert word_table.count_special() == 2
325 def test_update_special_phrase_modify(analyzer, word_table):
326 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
327 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
329 assert word_table.count_special() == 2
331 with analyzer() as anl:
332 anl.update_special_phrases([
333 ('prison', 'amenity', 'prison', 'in'),
334 ('bar', 'highway', 'road', '-'),
335 ('garden', 'leisure', 'garden', 'near')
338 assert word_table.get_special() \
339 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
340 ('BAR', 'bar', 'highway', 'road', None),
341 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
344 def test_add_country_names_new(analyzer, word_table):
345 with analyzer() as anl:
346 anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
348 assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
351 def test_add_country_names_extend(analyzer, word_table):
352 word_table.add_country('ch', 'SCHWEIZ')
354 with analyzer() as anl:
355 anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
357 assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
360 class TestPlaceNames:
362 @pytest.fixture(autouse=True)
363 def setup(self, analyzer, sql_functions):
364 sanitizers = [{'step': 'split-name-list'},
365 {'step': 'strip-brace-terms'}]
366 with analyzer(sanitizers=sanitizers) as anl:
370 def expect_name_terms(self, info, *expected_terms):
371 tokens = self.analyzer.get_word_token_info(expected_terms)
373 assert token[2] is not None, "No token for {0}".format(token)
375 assert eval(info['names']) == set((t[2] for t in tokens))
377 def process_named_place(self, names):
378 return self.analyzer.process_place(PlaceInfo({'name': names}))
380 def test_simple_names(self):
381 info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
383 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
385 @pytest.mark.parametrize('sep', [',', ';'])
386 def test_names_with_separator(self, sep):
387 info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
389 self.expect_name_terms(info, '#New York', '#Big Apple',
390 'new', 'york', 'big', 'apple')
392 def test_full_names_with_bracket(self):
393 info = self.process_named_place({'name': 'Houseboat (left)'})
395 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
398 def test_country_name(self, word_table):
399 place = PlaceInfo({'name': {'name': 'Norge'},
400 'country_code': 'no',
403 'type': 'administrative'})
405 info = self.analyzer.process_place(place)
407 self.expect_name_terms(info, '#norge', 'norge')
408 assert word_table.get_country() == {('no', 'NORGE')}
411 class TestPlaceAddress:
413 @pytest.fixture(autouse=True)
414 def setup(self, analyzer, sql_functions):
415 hnr = {'step': 'clean-housenumbers',
416 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
417 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr]) 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 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
430 def name_token_set(self, *expected_terms):
431 tokens = self.analyzer.get_word_token_info(expected_terms)
433 assert token[2] is not None, "No token for {0}".format(token)
435 return set((t[2] for t in tokens))
437 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
438 def test_process_place_postcode(self, word_table, pcode):
439 info = self.process_address(postcode=pcode)
441 assert info['postcode'] == pcode
443 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
444 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
445 info = self.process_address(housenumber=hnr)
447 assert info['hnr'] == hnr.upper()
448 assert info['hnr_tokens'] == "{-1}"
450 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
451 info = self.process_address(housenumber='134',
452 conscriptionnumber='134',
455 assert set(info['hnr'].split(';')) == set(('134', '99A'))
456 assert info['hnr_tokens'] == "{-1,-2}"
458 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
459 info = self.process_address(housenumber="45")
460 assert info['hnr_tokens'] == "{-1}"
462 info = self.process_address(housenumber="46")
463 assert info['hnr_tokens'] == "{-2}"
465 info = self.process_address(housenumber="41;45")
466 assert eval(info['hnr_tokens']) == {-1, -3}
468 info = self.process_address(housenumber="41")
469 assert eval(info['hnr_tokens']) == {-3}
471 def test_process_place_street(self):
472 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
473 info = self.process_address(street='Grand Road')
475 assert eval(info['street']) == self.name_token_set('#Grand Road')
477 def test_process_place_nonexisting_street(self):
478 info = self.process_address(street='Grand Road')
480 assert info['street'] == '{}'
482 def test_process_place_multiple_street_tags(self):
483 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road',
485 info = self.process_address(**{'street': 'Grand Road',
486 'street:sym_ul': '05989'})
488 assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
490 def test_process_place_street_empty(self):
491 info = self.process_address(street='🜵')
493 assert info['street'] == '{}'
495 def test_process_place_street_from_cache(self):
496 self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
497 self.process_address(street='Grand Road')
499 # request address again
500 info = self.process_address(street='Grand Road')
502 assert eval(info['street']) == self.name_token_set('#Grand Road')
504 def test_process_place_place(self):
505 info = self.process_address(place='Honu Lulu')
507 assert eval(info['place']) == self.name_token_set('HONU', 'LULU', '#HONU LULU')
509 def test_process_place_place_extra(self):
510 info = self.process_address(**{'place:en': 'Honu Lulu'})
512 assert 'place' not in info
514 def test_process_place_place_empty(self):
515 info = self.process_address(place='🜵')
517 assert 'place' not in info
519 def test_process_place_address_terms(self):
520 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
521 suburb='Zwickau', street='Hauptstr',
522 full='right behind the church')
524 city = self.name_token_set('ZWICKAU', '#ZWICKAU')
525 state = self.name_token_set('SACHSEN', '#SACHSEN')
527 result = {k: eval(v) for k, v in info['addr'].items()}
529 assert result == {'city': city, 'suburb': city, 'state': state}
531 def test_process_place_multiple_address_terms(self):
532 info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
534 result = {k: eval(v) for k, v in info['addr'].items()}
536 assert result == {'city': self.name_token_set('Bruxelles', '#Bruxelles')}
538 def test_process_place_address_terms_empty(self):
539 info = self.process_address(country='de', city=' ', street='Hauptstr',
540 full='right behind the church')
542 assert 'addr' not in info
545 class TestPlaceHousenumberWithAnalyser:
547 @pytest.fixture(autouse=True)
548 def setup(self, analyzer, sql_functions):
549 hnr = {'step': 'clean-housenumbers',
550 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
551 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr],
552 with_housenumber=True) as anl:
557 def getorcreate_hnr_id(self, temp_db_cursor):
558 temp_db_cursor.execute("""
559 CREATE OR REPLACE FUNCTION create_analyzed_hnr_id(norm_term TEXT, lookup_terms TEXT[])
560 RETURNS INTEGER AS $$
561 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
563 def process_address(self, **kwargs):
564 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
566 def name_token_set(self, *expected_terms):
567 tokens = self.analyzer.get_word_token_info(expected_terms)
569 assert token[2] is not None, "No token for {0}".format(token)
571 return set((t[2] for t in tokens))
573 @pytest.mark.parametrize('hnr', ['123 a', '1', '101'])
574 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
575 info = self.process_address(housenumber=hnr)
577 assert info['hnr'] == hnr.upper()
578 assert info['hnr_tokens'] == "{-1}"
580 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
581 info = self.process_address(housenumber='134',
582 conscriptionnumber='134',
585 assert set(info['hnr'].split(';')) == set(('134', '99 A'))
586 assert info['hnr_tokens'] == "{-1,-2}"
588 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
589 info = self.process_address(housenumber="45")
590 assert info['hnr_tokens'] == "{-1}"
592 info = self.process_address(housenumber="46")
593 assert info['hnr_tokens'] == "{-2}"
595 info = self.process_address(housenumber="41;45")
596 assert eval(info['hnr_tokens']) == {-1, -3}
598 info = self.process_address(housenumber="41")
599 assert eval(info['hnr_tokens']) == {-3}
602 class TestUpdateWordTokens:
604 @pytest.fixture(autouse=True)
605 def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
606 table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
607 self.tok = tokenizer_factory()
610 def search_entry(self, temp_db_cursor):
611 place_id = itertools.count(1000)
614 temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
615 (next(place_id), list(args)))
619 @pytest.fixture(params=['simple', 'analyzed'])
620 def add_housenumber(self, request, word_table):
621 if request.param == 'simple':
623 word_table.add_housenumber(hid, hnr)
624 elif request.param == 'analyzed':
626 word_table.add_housenumber(hid, [hnr])
630 @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
631 def test_remove_unused_housenumbers(self, add_housenumber, word_table, hnr):
632 word_table.add_housenumber(1000, hnr)
634 assert word_table.count_housenumbers() == 1
635 self.tok.update_word_tokens()
636 assert word_table.count_housenumbers() == 0
638 def test_keep_unused_numeral_housenumbers(self, add_housenumber, word_table):
639 add_housenumber(1000, '5432')
641 assert word_table.count_housenumbers() == 1
642 self.tok.update_word_tokens()
643 assert word_table.count_housenumbers() == 1
645 def test_keep_housenumbers_from_search_name_table(self, add_housenumber,
646 word_table, search_entry):
647 add_housenumber(9999, '5432a')
648 add_housenumber(9991, '9 a')
649 search_entry(123, 9999, 34)
651 assert word_table.count_housenumbers() == 2
652 self.tok.update_word_tokens()
653 assert word_table.count_housenumbers() == 1
655 def test_keep_housenumbers_from_placex_table(self, add_housenumber, word_table,
657 add_housenumber(9999, '5432a')
658 add_housenumber(9990, '34z')
659 placex_table.add(housenumber='34z')
660 placex_table.add(housenumber='25432a')
662 assert word_table.count_housenumbers() == 2
663 self.tok.update_word_tokens()
664 assert word_table.count_housenumbers() == 1
666 def test_keep_housenumbers_from_placex_table_hnr_list(self, add_housenumber,
667 word_table, placex_table):
668 add_housenumber(9991, '9 b')
669 add_housenumber(9990, '34z')
670 placex_table.add(housenumber='9 a;9 b;9 c')
672 assert word_table.count_housenumbers() == 2
673 self.tok.update_word_tokens()
674 assert word_table.count_housenumbers() == 1