1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Tests for ICU tokenizer.
16 from nominatim.tokenizer import icu_tokenizer
17 import nominatim.tokenizer.icu_rule_loader
18 from nominatim.db import properties
19 from nominatim.db.sql_preprocessor import SQLPreprocessor
20 from nominatim.indexer.place_info import PlaceInfo
22 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'")
35 shutil.copy(str(project_env.lib_dir.sql / 'tokenizer' / 'icu_tokenizer_tables.sql'),
36 str(sqldir / 'tokenizer' / 'icu_tokenizer_tables.sql'))
38 project_env.lib_dir.sql = sqldir
44 def tokenizer_factory(dsn, tmp_path, property_table,
45 sql_preprocessor, place_table, word_table):
46 (tmp_path / 'tokenizer').mkdir()
49 return icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
55 def db_prop(temp_db_conn):
56 def _get_db_property(name):
57 return properties.get_property(temp_db_conn, name)
59 return _get_db_property
63 def analyzer(tokenizer_factory, test_config, monkeypatch,
64 temp_db_with_extensions, tmp_path):
65 sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
66 sql.write_text("SELECT 'a';")
68 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
69 tok = tokenizer_factory()
70 tok.init_new_db(test_config)
73 def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
74 variants=('~gasse -> gasse', 'street => st', ),
75 sanitizers=[], with_housenumber=False):
76 cfgstr = {'normalization': list(norm),
77 'sanitizers': sanitizers,
78 'transliteration': list(trans),
79 'token-analysis': [{'analyzer': 'generic',
80 'variants': [{'words': list(variants)}]}]}
82 cfgstr['token-analysis'].append({'id': '@housenumber',
83 'analyzer': 'housenumbers'})
84 (test_config.project_dir / 'icu_tokenizer.yaml').write_text(yaml.dump(cfgstr))
85 tok.loader = nominatim.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
87 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;
155 def test_init_new(tokenizer_factory, test_config, db_prop):
156 tok = tokenizer_factory()
157 tok.init_new_db(test_config)
159 assert db_prop(nominatim.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES) \
160 .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_conn,
202 temp_db_cursor, test_config, sql_preprocessor_cfg):
203 func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer_indices.sql'
204 func_file.write_text("""CREATE FUNCTION test() RETURNS TEXT
205 AS $$ SELECT 'b'::text $$ LANGUAGE SQL""")
207 tok = tokenizer_factory()
208 tok.init_new_db(test_config)
210 tok.finalize_import(test_config)
212 temp_db_cursor.scalar('SELECT test()') == 'b'
215 def test_check_database(test_config, tokenizer_factory,
216 temp_db_cursor, sql_preprocessor_cfg):
217 tok = tokenizer_factory()
218 tok.init_new_db(test_config)
220 assert tok.check_database(test_config) is None
223 def test_update_statistics_reverse_only(word_table, tokenizer_factory):
224 tok = tokenizer_factory()
225 tok.update_statistics()
228 def test_update_statistics(word_table, table_factory, temp_db_cursor, tokenizer_factory):
229 word_table.add_full_word(1000, 'hello')
230 table_factory('search_name',
231 'place_id BIGINT, name_vector INT[]',
233 tok = tokenizer_factory()
235 tok.update_statistics()
237 assert temp_db_cursor.scalar("""SELECT count(*) FROM word
239 (info->>'count')::int > 0""") > 0
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 Б'
249 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
250 table_factory('location_postcode', 'postcode TEXT',
251 content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
253 with analyzer() as anl:
254 anl.update_postcodes_from_db()
256 assert word_table.count() == 3
257 assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
260 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
261 table_factory('location_postcode', 'postcode TEXT',
262 content=(('1234',), ('45BC', ), ('XX45', )))
263 word_table.add_postcode(' 1234', '1234')
264 word_table.add_postcode(' 5678', '5678')
266 with analyzer() as anl:
267 anl.update_postcodes_from_db()
269 assert word_table.count() == 3
270 assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
273 def test_update_special_phrase_empty_table(analyzer, word_table):
274 with analyzer() as anl:
275 anl.update_special_phrases([
276 ("König bei", "amenity", "royal", "near"),
277 ("Könige ", "amenity", "royal", "-"),
278 ("street", "highway", "primary", "in")
281 assert word_table.get_special() \
282 == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
283 ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
284 ('STREET', 'street', 'highway', 'primary', 'in')}
287 def test_update_special_phrase_delete_all(analyzer, word_table):
288 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
289 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
291 assert word_table.count_special() == 2
293 with analyzer() as anl:
294 anl.update_special_phrases([], True)
296 assert word_table.count_special() == 0
299 def test_update_special_phrases_no_replace(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([], False)
308 assert word_table.count_special() == 2
311 def test_update_special_phrase_modify(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([
319 ('prison', 'amenity', 'prison', 'in'),
320 ('bar', 'highway', 'road', '-'),
321 ('garden', 'leisure', 'garden', 'near')
324 assert word_table.get_special() \
325 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
326 ('BAR', 'bar', 'highway', 'road', None),
327 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
330 def test_add_country_names_new(analyzer, word_table):
331 with analyzer() as anl:
332 anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
334 assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
337 def test_add_country_names_extend(analyzer, word_table):
338 word_table.add_country('ch', 'SCHWEIZ')
340 with analyzer() as anl:
341 anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
343 assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
346 class TestPlaceNames:
348 @pytest.fixture(autouse=True)
349 def setup(self, analyzer, sql_functions):
350 sanitizers = [{'step': 'split-name-list'},
351 {'step': 'strip-brace-terms'}]
352 with analyzer(sanitizers=sanitizers) as anl:
357 def expect_name_terms(self, info, *expected_terms):
358 tokens = self.analyzer.get_word_token_info(expected_terms)
360 assert token[2] is not None, "No token for {0}".format(token)
362 assert eval(info['names']) == set((t[2] for t in tokens))
365 def process_named_place(self, names):
366 return self.analyzer.process_place(PlaceInfo({'name': names}))
369 def test_simple_names(self):
370 info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
372 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
375 @pytest.mark.parametrize('sep', [',' , ';'])
376 def test_names_with_separator(self, sep):
377 info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
379 self.expect_name_terms(info, '#New York', '#Big Apple',
380 'new', 'york', 'big', 'apple')
383 def test_full_names_with_bracket(self):
384 info = self.process_named_place({'name': 'Houseboat (left)'})
386 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
390 def test_country_name(self, word_table):
391 place = PlaceInfo({'name' : {'name': 'Norge'},
392 'country_code': 'no',
395 'type': 'administrative'})
397 info = self.analyzer.process_place(place)
399 self.expect_name_terms(info, '#norge', 'norge')
400 assert word_table.get_country() == {('no', 'NORGE')}
403 class TestPlaceAddress:
405 @pytest.fixture(autouse=True)
406 def setup(self, analyzer, sql_functions):
407 hnr = {'step': 'clean-housenumbers',
408 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
409 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr]) as anl:
415 def getorcreate_hnr_id(self, temp_db_cursor):
416 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
417 RETURNS INTEGER AS $$
418 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
421 def process_address(self, **kwargs):
422 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
425 def name_token_set(self, *expected_terms):
426 tokens = self.analyzer.get_word_token_info(expected_terms)
428 assert token[2] is not None, "No token for {0}".format(token)
430 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 self.process_address(postcode=pcode)
437 assert word_table.get_postcodes() == {pcode, }
440 @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
441 def test_process_place_bad_postcode(self, word_table, pcode):
442 self.process_address(postcode=pcode)
444 assert not word_table.get_postcodes()
447 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
448 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
449 info = self.process_address(housenumber=hnr)
451 assert info['hnr'] == hnr.upper()
452 assert info['hnr_tokens'] == "{-1}"
455 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
456 info = self.process_address(housenumber='134',
457 conscriptionnumber='134',
460 assert set(info['hnr'].split(';')) == set(('134', '99A'))
461 assert info['hnr_tokens'] == "{-1,-2}"
464 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
465 info = self.process_address(housenumber="45")
466 assert info['hnr_tokens'] == "{-1}"
468 info = self.process_address(housenumber="46")
469 assert info['hnr_tokens'] == "{-2}"
471 info = self.process_address(housenumber="41;45")
472 assert eval(info['hnr_tokens']) == {-1, -3}
474 info = self.process_address(housenumber="41")
475 assert eval(info['hnr_tokens']) == {-3}
478 def test_process_place_street(self):
479 self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road'}}))
480 info = self.process_address(street='Grand Road')
482 assert eval(info['street']) == self.name_token_set('#Grand Road')
485 def test_process_place_nonexisting_street(self):
486 info = self.process_address(street='Grand Road')
488 assert 'street' not in info
491 def test_process_place_multiple_street_tags(self):
492 self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road',
494 info = self.process_address(**{'street': 'Grand Road',
495 'street:sym_ul': '05989'})
497 assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
500 def test_process_place_street_empty(self):
501 info = self.process_address(street='🜵')
503 assert 'street' not in info
506 def test_process_place_street_from_cache(self):
507 self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road'}}))
508 self.process_address(street='Grand Road')
510 # request address again
511 info = self.process_address(street='Grand Road')
513 assert eval(info['street']) == self.name_token_set('#Grand Road')
516 def test_process_place_place(self):
517 info = self.process_address(place='Honu Lulu')
519 assert eval(info['place']) == self.name_token_set('HONU', 'LULU')
522 def test_process_place_place_extra(self):
523 info = self.process_address(**{'place:en': 'Honu Lulu'})
525 assert 'place' not in info
528 def test_process_place_place_empty(self):
529 info = self.process_address(place='🜵')
531 assert 'place' not in info
534 def test_process_place_address_terms(self):
535 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
536 suburb='Zwickau', street='Hauptstr',
537 full='right behind the church')
539 city = self.name_token_set('ZWICKAU')
540 state = self.name_token_set('SACHSEN')
542 result = {k: eval(v) for k,v in info['addr'].items()}
544 assert result == {'city': city, 'suburb': city, 'state': state}
547 def test_process_place_multiple_address_terms(self):
548 info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
550 result = {k: eval(v) for k,v in info['addr'].items()}
552 assert result == {'city': self.name_token_set('Bruxelles')}
555 def test_process_place_address_terms_empty(self):
556 info = self.process_address(country='de', city=' ', street='Hauptstr',
557 full='right behind the church')
559 assert 'addr' not in info
562 class TestPlaceHousenumberWithAnalyser:
564 @pytest.fixture(autouse=True)
565 def setup(self, analyzer, sql_functions):
566 hnr = {'step': 'clean-housenumbers',
567 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
568 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr], with_housenumber=True) as anl:
574 def getorcreate_hnr_id(self, temp_db_cursor):
575 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION create_analyzed_hnr_id(norm_term TEXT, lookup_terms TEXT[])
576 RETURNS INTEGER AS $$
577 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
580 def process_address(self, **kwargs):
581 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
584 def name_token_set(self, *expected_terms):
585 tokens = self.analyzer.get_word_token_info(expected_terms)
587 assert token[2] is not None, "No token for {0}".format(token)
589 return set((t[2] for t in tokens))
592 @pytest.mark.parametrize('hnr', ['123 a', '1', '101'])
593 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
594 info = self.process_address(housenumber=hnr)
596 assert info['hnr'] == hnr.upper()
597 assert info['hnr_tokens'] == "{-1}"
600 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
601 info = self.process_address(housenumber='134',
602 conscriptionnumber='134',
605 assert set(info['hnr'].split(';')) == set(('134', '99 A'))
606 assert info['hnr_tokens'] == "{-1,-2}"
609 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
610 info = self.process_address(housenumber="45")
611 assert info['hnr_tokens'] == "{-1}"
613 info = self.process_address(housenumber="46")
614 assert info['hnr_tokens'] == "{-2}"
616 info = self.process_address(housenumber="41;45")
617 assert eval(info['hnr_tokens']) == {-1, -3}
619 info = self.process_address(housenumber="41")
620 assert eval(info['hnr_tokens']) == {-3}
623 class TestUpdateWordTokens:
625 @pytest.fixture(autouse=True)
626 def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
627 table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
628 self.tok = tokenizer_factory()
632 def search_entry(self, temp_db_cursor):
633 place_id = itertools.count(1000)
636 temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
637 (next(place_id), list(args)))
642 @pytest.fixture(params=['simple', 'analyzed'])
643 def add_housenumber(self, request, word_table):
644 if request.param == 'simple':
646 word_table.add_housenumber(hid, hnr)
647 elif request.param == 'analyzed':
649 word_table.add_housenumber(hid, [hnr])
654 @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
655 def test_remove_unused_housenumbers(self, add_housenumber, word_table, hnr):
656 word_table.add_housenumber(1000, hnr)
658 assert word_table.count_housenumbers() == 1
659 self.tok.update_word_tokens()
660 assert word_table.count_housenumbers() == 0
663 def test_keep_unused_numeral_housenumbers(self, add_housenumber, word_table):
664 add_housenumber(1000, '5432')
666 assert word_table.count_housenumbers() == 1
667 self.tok.update_word_tokens()
668 assert word_table.count_housenumbers() == 1
671 def test_keep_housenumbers_from_search_name_table(self, add_housenumber, word_table, search_entry):
672 add_housenumber(9999, '5432a')
673 add_housenumber(9991, '9 a')
674 search_entry(123, 9999, 34)
676 assert word_table.count_housenumbers() == 2
677 self.tok.update_word_tokens()
678 assert word_table.count_housenumbers() == 1
681 def test_keep_housenumbers_from_placex_table(self, add_housenumber, word_table, placex_table):
682 add_housenumber(9999, '5432a')
683 add_housenumber(9990, '34z')
684 placex_table.add(housenumber='34z')
685 placex_table.add(housenumber='25432a')
687 assert word_table.count_housenumbers() == 2
688 self.tok.update_word_tokens()
689 assert word_table.count_housenumbers() == 1
692 def test_keep_housenumbers_from_placex_table_hnr_list(self, add_housenumber, word_table, placex_table):
693 add_housenumber(9991, '9 b')
694 add_housenumber(9990, '34z')
695 placex_table.add(housenumber='9 a;9 b;9 c')
697 assert word_table.count_housenumbers() == 2
698 self.tok.update_word_tokens()
699 assert word_table.count_housenumbers() == 1