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.
15 from nominatim.tokenizer import icu_tokenizer
16 import nominatim.tokenizer.icu_rule_loader
17 from nominatim.db import properties
18 from nominatim.db.sql_preprocessor import SQLPreprocessor
19 from nominatim.data.place_info import PlaceInfo
21 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'")
35 project_env.lib_dir.sql = sqldir
41 def tokenizer_factory(dsn, tmp_path, property_table,
42 sql_preprocessor, place_table, word_table):
43 (tmp_path / 'tokenizer').mkdir()
46 return icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
52 def db_prop(temp_db_conn):
53 def _get_db_property(name):
54 return properties.get_property(temp_db_conn, name)
56 return _get_db_property
60 def analyzer(tokenizer_factory, test_config, monkeypatch,
61 temp_db_with_extensions, tmp_path):
62 sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
63 sql.write_text("SELECT 'a';")
65 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
66 tok = tokenizer_factory()
67 tok.init_new_db(test_config)
70 def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
71 variants=('~gasse -> gasse', 'street => st', ),
72 sanitizers=[], with_housenumber=False,
74 cfgstr = {'normalization': list(norm),
75 'sanitizers': sanitizers,
76 'transliteration': list(trans),
77 'token-analysis': [{'analyzer': 'generic',
78 'variants': [{'words': list(variants)}]}]}
80 cfgstr['token-analysis'].append({'id': '@housenumber',
81 'analyzer': 'housenumbers'})
83 cfgstr['token-analysis'].append({'id': '@postcode',
84 'analyzer': 'postcodes'})
85 (test_config.project_dir / 'icu_tokenizer.yaml').write_text(yaml.dump(cfgstr))
86 tok.loader = nominatim.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
88 return tok.name_analyzer()
93 def sql_functions(temp_db_conn, def_config, src_dir):
94 orig_sql = def_config.lib_dir.sql
95 def_config.lib_dir.sql = src_dir / 'lib-sql'
96 sqlproc = SQLPreprocessor(temp_db_conn, def_config)
97 sqlproc.run_sql_file(temp_db_conn, 'functions/utils.sql')
98 sqlproc.run_sql_file(temp_db_conn, 'tokenizer/icu_tokenizer.sql')
99 def_config.lib_dir.sql = orig_sql
103 def getorcreate_full_word(temp_db_cursor):
104 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
105 norm_term TEXT, lookup_terms TEXT[],
107 OUT partial_tokens INT[])
110 partial_terms TEXT[] = '{}'::TEXT[];
115 SELECT min(word_id) INTO full_token
116 FROM word WHERE info->>'word' = norm_term and type = 'W';
118 IF full_token IS NULL THEN
119 full_token := nextval('seq_word');
120 INSERT INTO word (word_id, word_token, type, info)
121 SELECT full_token, lookup_term, 'W',
122 json_build_object('word', norm_term, 'count', 0)
123 FROM unnest(lookup_terms) as lookup_term;
126 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
128 IF NOT (ARRAY[term] <@ partial_terms) THEN
129 partial_terms := partial_terms || term;
133 partial_tokens := '{}'::INT[];
134 FOR term IN SELECT unnest(partial_terms) LOOP
135 SELECT min(word_id), max(info->>'count') INTO term_id, term_count
136 FROM word WHERE word_token = term and type = 'w';
138 IF term_id IS NULL THEN
139 term_id := nextval('seq_word');
141 INSERT INTO word (word_id, word_token, type, info)
142 VALUES (term_id, term, 'w', json_build_object('count', term_count));
145 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
146 partial_tokens := partial_tokens || term_id;
156 def test_init_new(tokenizer_factory, test_config, db_prop):
157 tok = tokenizer_factory()
158 tok.init_new_db(test_config)
160 assert db_prop(nominatim.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES) \
161 .startswith(':: lower ();')
164 def test_init_word_table(tokenizer_factory, test_config, place_row, temp_db_cursor):
165 place_row(names={'name' : 'Test Area', 'ref' : '52'})
166 place_row(names={'name' : 'No Area'})
167 place_row(names={'name' : 'Holzstrasse'})
169 tok = tokenizer_factory()
170 tok.init_new_db(test_config)
172 assert temp_db_cursor.table_exists('word')
175 def test_init_from_project(test_config, tokenizer_factory):
176 tok = tokenizer_factory()
177 tok.init_new_db(test_config)
179 tok = tokenizer_factory()
180 tok.init_from_project(test_config)
182 assert tok.loader is not None
185 def test_update_sql_functions(db_prop, temp_db_cursor,
186 tokenizer_factory, test_config, table_factory,
188 tok = tokenizer_factory()
189 tok.init_new_db(test_config)
191 table_factory('test', 'txt TEXT')
193 func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
194 func_file.write_text("""INSERT INTO test VALUES (1133)""")
196 tok.update_sql_functions(test_config)
198 test_content = temp_db_cursor.row_set('SELECT * FROM test')
199 assert test_content == set((('1133', ), ))
202 def test_finalize_import(tokenizer_factory, temp_db_conn,
203 temp_db_cursor, test_config, sql_preprocessor_cfg):
204 tok = tokenizer_factory()
205 tok.init_new_db(test_config)
207 assert not temp_db_conn.index_exists('idx_word_word_id')
209 tok.finalize_import(test_config)
211 assert temp_db_conn.index_exists('idx_word_word_id')
214 def test_check_database(test_config, tokenizer_factory,
215 temp_db_cursor, sql_preprocessor_cfg):
216 tok = tokenizer_factory()
217 tok.init_new_db(test_config)
219 assert tok.check_database(test_config) is None
222 def test_update_statistics_reverse_only(word_table, tokenizer_factory, test_config):
223 tok = tokenizer_factory()
224 tok.update_statistics(test_config)
227 def test_update_statistics(word_table, table_factory, temp_db_cursor,
228 tokenizer_factory, test_config):
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(test_config)
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 Б'
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:
259 def process_postcode(self, cc, postcode):
260 return self.analyzer.process_place(PlaceInfo({'country_code': cc,
261 'address': {'postcode': postcode}}))
264 def test_update_postcodes_from_db_empty(self, table_factory, word_table):
265 table_factory('location_postcode', 'country_code TEXT, postcode TEXT',
266 content=(('de', '12345'), ('se', '132 34'),
267 ('bm', 'AB23'), ('fr', '12345')))
269 self.analyzer.update_postcodes_from_db()
271 assert word_table.count() == 5
272 assert word_table.get_postcodes() == {'12345', '132 34@132 34', 'AB 23@AB 23'}
275 def test_update_postcodes_from_db_ambigious(self, table_factory, word_table):
276 table_factory('location_postcode', 'country_code TEXT, postcode TEXT',
277 content=(('in', '123456'), ('sg', '123456')))
279 self.analyzer.update_postcodes_from_db()
281 assert word_table.count() == 3
282 assert word_table.get_postcodes() == {'123456', '123456@123 456'}
285 def test_update_postcodes_from_db_add_and_remove(self, table_factory, word_table):
286 table_factory('location_postcode', 'country_code TEXT, postcode TEXT',
287 content=(('ch', '1234'), ('bm', 'BC 45'), ('bm', 'XX45')))
288 word_table.add_postcode(' 1234', '1234')
289 word_table.add_postcode(' 5678', '5678')
291 self.analyzer.update_postcodes_from_db()
293 assert word_table.count() == 5
294 assert word_table.get_postcodes() == {'1234', 'BC 45@BC 45', 'XX 45@XX 45'}
297 def test_process_place_postcode_simple(self, word_table):
298 info = self.process_postcode('de', '12345')
300 assert info['postcode'] == '12345'
302 assert word_table.get_postcodes() == {'12345', }
305 def test_process_place_postcode_with_space(self, word_table):
306 info = self.process_postcode('in', '123 567')
308 assert info['postcode'] == '123567'
310 assert word_table.get_postcodes() == {'123567@123 567', }
314 def test_update_special_phrase_empty_table(analyzer, word_table):
315 with analyzer() as anl:
316 anl.update_special_phrases([
317 ("König bei", "amenity", "royal", "near"),
318 ("Könige ", "amenity", "royal", "-"),
319 ("street", "highway", "primary", "in")
322 assert word_table.get_special() \
323 == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
324 ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
325 ('STREET', 'street', 'highway', 'primary', 'in')}
328 def test_update_special_phrase_delete_all(analyzer, word_table):
329 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
330 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
332 assert word_table.count_special() == 2
334 with analyzer() as anl:
335 anl.update_special_phrases([], True)
337 assert word_table.count_special() == 0
340 def test_update_special_phrases_no_replace(analyzer, word_table):
341 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
342 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
344 assert word_table.count_special() == 2
346 with analyzer() as anl:
347 anl.update_special_phrases([], False)
349 assert word_table.count_special() == 2
352 def test_update_special_phrase_modify(analyzer, word_table):
353 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
354 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
356 assert word_table.count_special() == 2
358 with analyzer() as anl:
359 anl.update_special_phrases([
360 ('prison', 'amenity', 'prison', 'in'),
361 ('bar', 'highway', 'road', '-'),
362 ('garden', 'leisure', 'garden', 'near')
365 assert word_table.get_special() \
366 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
367 ('BAR', 'bar', 'highway', 'road', None),
368 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
371 def test_add_country_names_new(analyzer, word_table):
372 with analyzer() as anl:
373 anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
375 assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
378 def test_add_country_names_extend(analyzer, word_table):
379 word_table.add_country('ch', 'SCHWEIZ')
381 with analyzer() as anl:
382 anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
384 assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
387 class TestPlaceNames:
389 @pytest.fixture(autouse=True)
390 def setup(self, analyzer, sql_functions):
391 sanitizers = [{'step': 'split-name-list'},
392 {'step': 'strip-brace-terms'}]
393 with analyzer(sanitizers=sanitizers) as anl:
398 def expect_name_terms(self, info, *expected_terms):
399 tokens = self.analyzer.get_word_token_info(expected_terms)
401 assert token[2] is not None, "No token for {0}".format(token)
403 assert eval(info['names']) == set((t[2] for t in tokens))
406 def process_named_place(self, names):
407 return self.analyzer.process_place(PlaceInfo({'name': names}))
410 def test_simple_names(self):
411 info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
413 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
416 @pytest.mark.parametrize('sep', [',' , ';'])
417 def test_names_with_separator(self, sep):
418 info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
420 self.expect_name_terms(info, '#New York', '#Big Apple',
421 'new', 'york', 'big', 'apple')
424 def test_full_names_with_bracket(self):
425 info = self.process_named_place({'name': 'Houseboat (left)'})
427 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
431 def test_country_name(self, word_table):
432 place = PlaceInfo({'name' : {'name': 'Norge'},
433 'country_code': 'no',
436 'type': 'administrative'})
438 info = self.analyzer.process_place(place)
440 self.expect_name_terms(info, '#norge', 'norge')
441 assert word_table.get_country() == {('no', 'NORGE')}
444 class TestPlaceAddress:
446 @pytest.fixture(autouse=True)
447 def setup(self, analyzer, sql_functions):
448 hnr = {'step': 'clean-housenumbers',
449 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
450 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr]) as anl:
456 def getorcreate_hnr_id(self, temp_db_cursor):
457 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
458 RETURNS INTEGER AS $$
459 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
462 def process_address(self, **kwargs):
463 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
466 def name_token_set(self, *expected_terms):
467 tokens = self.analyzer.get_word_token_info(expected_terms)
469 assert token[2] is not None, "No token for {0}".format(token)
471 return set((t[2] for t in tokens))
474 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
475 def test_process_place_postcode(self, word_table, pcode):
476 self.process_address(postcode=pcode)
478 assert word_table.get_postcodes() == {pcode, }
481 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
482 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
483 info = self.process_address(housenumber=hnr)
485 assert info['hnr'] == hnr.upper()
486 assert info['hnr_tokens'] == "{-1}"
489 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
490 info = self.process_address(housenumber='134',
491 conscriptionnumber='134',
494 assert set(info['hnr'].split(';')) == set(('134', '99A'))
495 assert info['hnr_tokens'] == "{-1,-2}"
498 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
499 info = self.process_address(housenumber="45")
500 assert info['hnr_tokens'] == "{-1}"
502 info = self.process_address(housenumber="46")
503 assert info['hnr_tokens'] == "{-2}"
505 info = self.process_address(housenumber="41;45")
506 assert eval(info['hnr_tokens']) == {-1, -3}
508 info = self.process_address(housenumber="41")
509 assert eval(info['hnr_tokens']) == {-3}
512 def test_process_place_street(self):
513 self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road'}}))
514 info = self.process_address(street='Grand Road')
516 assert eval(info['street']) == self.name_token_set('#Grand Road')
519 def test_process_place_nonexisting_street(self):
520 info = self.process_address(street='Grand Road')
522 assert info['street'] == '{}'
525 def test_process_place_multiple_street_tags(self):
526 self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road',
528 info = self.process_address(**{'street': 'Grand Road',
529 'street:sym_ul': '05989'})
531 assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
534 def test_process_place_street_empty(self):
535 info = self.process_address(street='🜵')
537 assert info['street'] == '{}'
540 def test_process_place_street_from_cache(self):
541 self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road'}}))
542 self.process_address(street='Grand Road')
544 # request address again
545 info = self.process_address(street='Grand Road')
547 assert eval(info['street']) == self.name_token_set('#Grand Road')
550 def test_process_place_place(self):
551 info = self.process_address(place='Honu Lulu')
553 assert eval(info['place']) == self.name_token_set('HONU', 'LULU')
556 def test_process_place_place_extra(self):
557 info = self.process_address(**{'place:en': 'Honu Lulu'})
559 assert 'place' not in info
562 def test_process_place_place_empty(self):
563 info = self.process_address(place='🜵')
565 assert 'place' not in info
568 def test_process_place_address_terms(self):
569 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
570 suburb='Zwickau', street='Hauptstr',
571 full='right behind the church')
573 city = self.name_token_set('ZWICKAU')
574 state = self.name_token_set('SACHSEN')
576 result = {k: eval(v) for k,v in info['addr'].items()}
578 assert result == {'city': city, 'suburb': city, 'state': state}
581 def test_process_place_multiple_address_terms(self):
582 info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
584 result = {k: eval(v) for k,v in info['addr'].items()}
586 assert result == {'city': self.name_token_set('Bruxelles')}
589 def test_process_place_address_terms_empty(self):
590 info = self.process_address(country='de', city=' ', street='Hauptstr',
591 full='right behind the church')
593 assert 'addr' not in info
596 class TestPlaceHousenumberWithAnalyser:
598 @pytest.fixture(autouse=True)
599 def setup(self, analyzer, sql_functions):
600 hnr = {'step': 'clean-housenumbers',
601 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
602 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr], with_housenumber=True) as anl:
608 def getorcreate_hnr_id(self, temp_db_cursor):
609 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION create_analyzed_hnr_id(norm_term TEXT, lookup_terms TEXT[])
610 RETURNS INTEGER AS $$
611 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
614 def process_address(self, **kwargs):
615 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
618 def name_token_set(self, *expected_terms):
619 tokens = self.analyzer.get_word_token_info(expected_terms)
621 assert token[2] is not None, "No token for {0}".format(token)
623 return set((t[2] for t in tokens))
626 @pytest.mark.parametrize('hnr', ['123 a', '1', '101'])
627 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
628 info = self.process_address(housenumber=hnr)
630 assert info['hnr'] == hnr.upper()
631 assert info['hnr_tokens'] == "{-1}"
634 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
635 info = self.process_address(housenumber='134',
636 conscriptionnumber='134',
639 assert set(info['hnr'].split(';')) == set(('134', '99 A'))
640 assert info['hnr_tokens'] == "{-1,-2}"
643 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
644 info = self.process_address(housenumber="45")
645 assert info['hnr_tokens'] == "{-1}"
647 info = self.process_address(housenumber="46")
648 assert info['hnr_tokens'] == "{-2}"
650 info = self.process_address(housenumber="41;45")
651 assert eval(info['hnr_tokens']) == {-1, -3}
653 info = self.process_address(housenumber="41")
654 assert eval(info['hnr_tokens']) == {-3}
657 class TestUpdateWordTokens:
659 @pytest.fixture(autouse=True)
660 def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
661 table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
662 self.tok = tokenizer_factory()
666 def search_entry(self, temp_db_cursor):
667 place_id = itertools.count(1000)
670 temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
671 (next(place_id), list(args)))
676 @pytest.fixture(params=['simple', 'analyzed'])
677 def add_housenumber(self, request, word_table):
678 if request.param == 'simple':
680 word_table.add_housenumber(hid, hnr)
681 elif request.param == 'analyzed':
683 word_table.add_housenumber(hid, [hnr])
688 @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
689 def test_remove_unused_housenumbers(self, add_housenumber, word_table, hnr):
690 word_table.add_housenumber(1000, hnr)
692 assert word_table.count_housenumbers() == 1
693 self.tok.update_word_tokens()
694 assert word_table.count_housenumbers() == 0
697 def test_keep_unused_numeral_housenumbers(self, add_housenumber, word_table):
698 add_housenumber(1000, '5432')
700 assert word_table.count_housenumbers() == 1
701 self.tok.update_word_tokens()
702 assert word_table.count_housenumbers() == 1
705 def test_keep_housenumbers_from_search_name_table(self, add_housenumber, word_table, search_entry):
706 add_housenumber(9999, '5432a')
707 add_housenumber(9991, '9 a')
708 search_entry(123, 9999, 34)
710 assert word_table.count_housenumbers() == 2
711 self.tok.update_word_tokens()
712 assert word_table.count_housenumbers() == 1
715 def test_keep_housenumbers_from_placex_table(self, add_housenumber, word_table, placex_table):
716 add_housenumber(9999, '5432a')
717 add_housenumber(9990, '34z')
718 placex_table.add(housenumber='34z')
719 placex_table.add(housenumber='25432a')
721 assert word_table.count_housenumbers() == 2
722 self.tok.update_word_tokens()
723 assert word_table.count_housenumbers() == 1
726 def test_keep_housenumbers_from_placex_table_hnr_list(self, add_housenumber, word_table, placex_table):
727 add_housenumber(9991, '9 b')
728 add_housenumber(9990, '34z')
729 placex_table.add(housenumber='9 a;9 b;9 c')
731 assert word_table.count_housenumbers() == 2
732 self.tok.update_word_tokens()
733 assert word_table.count_housenumbers() == 1