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', ),
 
  76         cfgstr = {'normalization': list(norm),
 
  77                   'sanitizers': sanitizers,
 
  78                   'transliteration': list(trans),
 
  79                   'token-analysis': [{'analyzer': 'generic',
 
  80                                       'variants': [{'words': list(variants)}]}]}
 
  81         (test_config.project_dir / 'icu_tokenizer.yaml').write_text(yaml.dump(cfgstr))
 
  82         tok.loader = nominatim.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
 
  84         return tok.name_analyzer()
 
  89 def sql_functions(temp_db_conn, def_config, src_dir):
 
  90     orig_sql = def_config.lib_dir.sql
 
  91     def_config.lib_dir.sql = src_dir / 'lib-sql'
 
  92     sqlproc = SQLPreprocessor(temp_db_conn, def_config)
 
  93     sqlproc.run_sql_file(temp_db_conn, 'functions/utils.sql')
 
  94     sqlproc.run_sql_file(temp_db_conn, 'tokenizer/icu_tokenizer.sql')
 
  95     def_config.lib_dir.sql = orig_sql
 
  99 def getorcreate_full_word(temp_db_cursor):
 
 100     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
 
 101                                                  norm_term TEXT, lookup_terms TEXT[],
 
 103                                                  OUT partial_tokens INT[])
 
 106   partial_terms TEXT[] = '{}'::TEXT[];
 
 111   SELECT min(word_id) INTO full_token
 
 112     FROM word WHERE info->>'word' = norm_term and type = 'W';
 
 114   IF full_token IS NULL THEN
 
 115     full_token := nextval('seq_word');
 
 116     INSERT INTO word (word_id, word_token, type, info)
 
 117       SELECT full_token, lookup_term, 'W',
 
 118              json_build_object('word', norm_term, 'count', 0)
 
 119         FROM unnest(lookup_terms) as lookup_term;
 
 122   FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
 
 124     IF NOT (ARRAY[term] <@ partial_terms) THEN
 
 125       partial_terms := partial_terms || term;
 
 129   partial_tokens := '{}'::INT[];
 
 130   FOR term IN SELECT unnest(partial_terms) LOOP
 
 131     SELECT min(word_id), max(info->>'count') INTO term_id, term_count
 
 132       FROM word WHERE word_token = term and type = 'w';
 
 134     IF term_id IS NULL THEN
 
 135       term_id := nextval('seq_word');
 
 137       INSERT INTO word (word_id, word_token, type, info)
 
 138         VALUES (term_id, term, 'w', json_build_object('count', term_count));
 
 141     IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
 
 142       partial_tokens := partial_tokens || term_id;
 
 152 def test_init_new(tokenizer_factory, test_config, db_prop):
 
 153     tok = tokenizer_factory()
 
 154     tok.init_new_db(test_config)
 
 156     assert db_prop(nominatim.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES) \
 
 157             .startswith(':: lower ();')
 
 160 def test_init_word_table(tokenizer_factory, test_config, place_row, temp_db_cursor):
 
 161     place_row(names={'name' : 'Test Area', 'ref' : '52'})
 
 162     place_row(names={'name' : 'No Area'})
 
 163     place_row(names={'name' : 'Holzstrasse'})
 
 165     tok = tokenizer_factory()
 
 166     tok.init_new_db(test_config)
 
 168     assert temp_db_cursor.table_exists('word')
 
 171 def test_init_from_project(test_config, tokenizer_factory):
 
 172     tok = tokenizer_factory()
 
 173     tok.init_new_db(test_config)
 
 175     tok = tokenizer_factory()
 
 176     tok.init_from_project(test_config)
 
 178     assert tok.loader is not None
 
 181 def test_update_sql_functions(db_prop, temp_db_cursor,
 
 182                               tokenizer_factory, test_config, table_factory,
 
 184     tok = tokenizer_factory()
 
 185     tok.init_new_db(test_config)
 
 187     table_factory('test', 'txt TEXT')
 
 189     func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
 
 190     func_file.write_text("""INSERT INTO test VALUES (1133)""")
 
 192     tok.update_sql_functions(test_config)
 
 194     test_content = temp_db_cursor.row_set('SELECT * FROM test')
 
 195     assert test_content == set((('1133', ), ))
 
 198 def test_finalize_import(tokenizer_factory, temp_db_conn,
 
 199                          temp_db_cursor, test_config, sql_preprocessor_cfg):
 
 200     func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer_indices.sql'
 
 201     func_file.write_text("""CREATE FUNCTION test() RETURNS TEXT
 
 202                             AS $$ SELECT 'b'::text $$ LANGUAGE SQL""")
 
 204     tok = tokenizer_factory()
 
 205     tok.init_new_db(test_config)
 
 207     tok.finalize_import(test_config)
 
 209     temp_db_cursor.scalar('SELECT test()') == 'b'
 
 212 def test_check_database(test_config, tokenizer_factory,
 
 213                         temp_db_cursor, sql_preprocessor_cfg):
 
 214     tok = tokenizer_factory()
 
 215     tok.init_new_db(test_config)
 
 217     assert tok.check_database(test_config) is None
 
 220 def test_update_statistics_reverse_only(word_table, tokenizer_factory):
 
 221     tok = tokenizer_factory()
 
 222     tok.update_statistics()
 
 225 def test_update_statistics(word_table, table_factory, temp_db_cursor, tokenizer_factory):
 
 226     word_table.add_full_word(1000, 'hello')
 
 227     table_factory('search_name',
 
 228                   'place_id BIGINT, name_vector INT[]',
 
 230     tok = tokenizer_factory()
 
 232     tok.update_statistics()
 
 234     assert temp_db_cursor.scalar("""SELECT count(*) FROM word
 
 236                                           (info->>'count')::int > 0""") > 0
 
 239 def test_normalize_postcode(analyzer):
 
 240     with analyzer() as anl:
 
 241         anl.normalize_postcode('123') == '123'
 
 242         anl.normalize_postcode('ab-34 ') == 'AB-34'
 
 243         anl.normalize_postcode('38 Б') == '38 Б'
 
 246 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
 
 247     table_factory('location_postcode', 'postcode TEXT',
 
 248                   content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
 
 250     with analyzer() as anl:
 
 251         anl.update_postcodes_from_db()
 
 253     assert word_table.count() == 3
 
 254     assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
 
 257 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
 
 258     table_factory('location_postcode', 'postcode TEXT',
 
 259                   content=(('1234',), ('45BC', ), ('XX45', )))
 
 260     word_table.add_postcode(' 1234', '1234')
 
 261     word_table.add_postcode(' 5678', '5678')
 
 263     with analyzer() as anl:
 
 264         anl.update_postcodes_from_db()
 
 266     assert word_table.count() == 3
 
 267     assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
 
 270 def test_update_special_phrase_empty_table(analyzer, word_table):
 
 271     with analyzer() as anl:
 
 272         anl.update_special_phrases([
 
 273             ("König  bei", "amenity", "royal", "near"),
 
 274             ("Könige ", "amenity", "royal", "-"),
 
 275             ("street", "highway", "primary", "in")
 
 278     assert word_table.get_special() \
 
 279                == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
 
 280                    ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
 
 281                    ('STREET', 'street', 'highway', 'primary', 'in')}
 
 284 def test_update_special_phrase_delete_all(analyzer, word_table):
 
 285     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
 
 286     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
 
 288     assert word_table.count_special() == 2
 
 290     with analyzer() as anl:
 
 291         anl.update_special_phrases([], True)
 
 293     assert word_table.count_special() == 0
 
 296 def test_update_special_phrases_no_replace(analyzer, word_table):
 
 297     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
 
 298     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
 
 300     assert word_table.count_special() == 2
 
 302     with analyzer() as anl:
 
 303         anl.update_special_phrases([], False)
 
 305     assert word_table.count_special() == 2
 
 308 def test_update_special_phrase_modify(analyzer, word_table):
 
 309     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
 
 310     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
 
 312     assert word_table.count_special() == 2
 
 314     with analyzer() as anl:
 
 315         anl.update_special_phrases([
 
 316             ('prison', 'amenity', 'prison', 'in'),
 
 317             ('bar', 'highway', 'road', '-'),
 
 318             ('garden', 'leisure', 'garden', 'near')
 
 321     assert word_table.get_special() \
 
 322                == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
 
 323                    ('BAR', 'bar', 'highway', 'road', None),
 
 324                    ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
 
 327 def test_add_country_names_new(analyzer, word_table):
 
 328     with analyzer() as anl:
 
 329         anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
 
 331     assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
 
 334 def test_add_country_names_extend(analyzer, word_table):
 
 335     word_table.add_country('ch', 'SCHWEIZ')
 
 337     with analyzer() as anl:
 
 338         anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
 
 340     assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
 
 343 class TestPlaceNames:
 
 345     @pytest.fixture(autouse=True)
 
 346     def setup(self, analyzer, sql_functions):
 
 347         sanitizers = [{'step': 'split-name-list'},
 
 348                       {'step': 'strip-brace-terms'}]
 
 349         with analyzer(sanitizers=sanitizers) as anl:
 
 354     def expect_name_terms(self, info, *expected_terms):
 
 355         tokens = self.analyzer.get_word_token_info(expected_terms)
 
 357             assert token[2] is not None, "No token for {0}".format(token)
 
 359         assert eval(info['names']) == set((t[2] for t in tokens))
 
 362     def process_named_place(self, names):
 
 363         return self.analyzer.process_place(PlaceInfo({'name': names}))
 
 366     def test_simple_names(self):
 
 367         info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
 
 369         self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
 
 372     @pytest.mark.parametrize('sep', [',' , ';'])
 
 373     def test_names_with_separator(self, sep):
 
 374         info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
 
 376         self.expect_name_terms(info, '#New York', '#Big Apple',
 
 377                                      'new', 'york', 'big', 'apple')
 
 380     def test_full_names_with_bracket(self):
 
 381         info = self.process_named_place({'name': 'Houseboat (left)'})
 
 383         self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
 
 387     def test_country_name(self, word_table):
 
 388         place = PlaceInfo({'name' : {'name': 'Norge'},
 
 389                            'country_code': 'no',
 
 392                            'type': 'administrative'})
 
 394         info = self.analyzer.process_place(place)
 
 396         self.expect_name_terms(info, '#norge', 'norge')
 
 397         assert word_table.get_country() == {('no', 'NORGE')}
 
 400 class TestPlaceAddress:
 
 402     @pytest.fixture(autouse=True)
 
 403     def setup(self, analyzer, sql_functions):
 
 404         hnr = {'step': 'clean-housenumbers',
 
 405                'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
 
 406         with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr]) as anl:
 
 412     def getorcreate_hnr_id(self, temp_db_cursor):
 
 413         temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
 
 414                                   RETURNS INTEGER AS $$
 
 415                                     SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
 
 418     def process_address(self, **kwargs):
 
 419         return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
 
 422     def name_token_set(self, *expected_terms):
 
 423         tokens = self.analyzer.get_word_token_info(expected_terms)
 
 425             assert token[2] is not None, "No token for {0}".format(token)
 
 427         return set((t[2] for t in tokens))
 
 430     @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
 
 431     def test_process_place_postcode(self, word_table, pcode):
 
 432         self.process_address(postcode=pcode)
 
 434         assert word_table.get_postcodes() == {pcode, }
 
 437     @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
 
 438     def test_process_place_bad_postcode(self, word_table, pcode):
 
 439         self.process_address(postcode=pcode)
 
 441         assert not word_table.get_postcodes()
 
 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}"
 
 452     def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
 
 453         info = self.process_address(housenumber='134',
 
 454                                     conscriptionnumber='134',
 
 457         assert set(info['hnr'].split(';')) == set(('134', '99A'))
 
 458         assert info['hnr_tokens'] == "{-1,-2}"
 
 461     def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
 
 462         info = self.process_address(housenumber="45")
 
 463         assert info['hnr_tokens'] == "{-1}"
 
 465         info = self.process_address(housenumber="46")
 
 466         assert info['hnr_tokens'] == "{-2}"
 
 468         info = self.process_address(housenumber="41;45")
 
 469         assert eval(info['hnr_tokens']) == {-1, -3}
 
 471         info = self.process_address(housenumber="41")
 
 472         assert eval(info['hnr_tokens']) == {-3}
 
 475     def test_process_place_street(self):
 
 476         self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road'}}))
 
 477         info = self.process_address(street='Grand Road')
 
 479         assert eval(info['street']) == self.name_token_set('#Grand Road')
 
 482     def test_process_place_nonexisting_street(self):
 
 483         info = self.process_address(street='Grand Road')
 
 485         assert 'street' not in info
 
 488     def test_process_place_multiple_street_tags(self):
 
 489         self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road',
 
 491         info = self.process_address(**{'street': 'Grand Road',
 
 492                                       'street:sym_ul': '05989'})
 
 494         assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
 
 497     def test_process_place_street_empty(self):
 
 498         info = self.process_address(street='🜵')
 
 500         assert 'street' not in info
 
 503     def test_process_place_street_from_cache(self):
 
 504         self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road'}}))
 
 505         self.process_address(street='Grand Road')
 
 507         # request address again
 
 508         info = self.process_address(street='Grand Road')
 
 510         assert eval(info['street']) == self.name_token_set('#Grand Road')
 
 513     def test_process_place_place(self):
 
 514         info = self.process_address(place='Honu Lulu')
 
 516         assert eval(info['place']) == self.name_token_set('HONU', 'LULU')
 
 519     def test_process_place_place_extra(self):
 
 520         info = self.process_address(**{'place:en': 'Honu Lulu'})
 
 522         assert 'place' not in info
 
 525     def test_process_place_place_empty(self):
 
 526         info = self.process_address(place='🜵')
 
 528         assert 'place' not in info
 
 531     def test_process_place_address_terms(self):
 
 532         info = self.process_address(country='de', city='Zwickau', state='Sachsen',
 
 533                                     suburb='Zwickau', street='Hauptstr',
 
 534                                     full='right behind the church')
 
 536         city = self.name_token_set('ZWICKAU')
 
 537         state = self.name_token_set('SACHSEN')
 
 539         result = {k: eval(v) for k,v in info['addr'].items()}
 
 541         assert result == {'city': city, 'suburb': city, 'state': state}
 
 544     def test_process_place_multiple_address_terms(self):
 
 545         info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
 
 547         result = {k: eval(v) for k,v in info['addr'].items()}
 
 549         assert result == {'city': self.name_token_set('Bruxelles')}
 
 552     def test_process_place_address_terms_empty(self):
 
 553         info = self.process_address(country='de', city=' ', street='Hauptstr',
 
 554                                     full='right behind the church')
 
 556         assert 'addr' not in info
 
 559 class TestUpdateWordTokens:
 
 561     @pytest.fixture(autouse=True)
 
 562     def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
 
 563         table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
 
 564         self.tok = tokenizer_factory()
 
 568     def search_entry(self, temp_db_cursor):
 
 569         place_id = itertools.count(1000)
 
 572             temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
 
 573                                    (next(place_id), list(args)))
 
 578     @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
 
 579     def test_remove_unused_housenumbers(self, word_table, hnr):
 
 580         word_table.add_housenumber(1000, hnr)
 
 582         assert word_table.count_housenumbers() == 1
 
 583         self.tok.update_word_tokens()
 
 584         assert word_table.count_housenumbers() == 0
 
 587     def test_keep_unused_numeral_housenumbers(self, word_table):
 
 588         word_table.add_housenumber(1000, '5432')
 
 590         assert word_table.count_housenumbers() == 1
 
 591         self.tok.update_word_tokens()
 
 592         assert word_table.count_housenumbers() == 1
 
 595     def test_keep_housenumbers_from_search_name_table(self, word_table, search_entry):
 
 596         word_table.add_housenumber(9999, '5432a')
 
 597         word_table.add_housenumber(9991, '9 a')
 
 598         search_entry(123, 9999, 34)
 
 600         assert word_table.count_housenumbers() == 2
 
 601         self.tok.update_word_tokens()
 
 602         assert word_table.count_housenumbers() == 1
 
 605     def test_keep_housenumbers_from_placex_table(self, word_table, placex_table):
 
 606         word_table.add_housenumber(9999, '5432a')
 
 607         word_table.add_housenumber(9990, '34z')
 
 608         placex_table.add(housenumber='34z')
 
 609         placex_table.add(housenumber='25432a')
 
 611         assert word_table.count_housenumbers() == 2
 
 612         self.tok.update_word_tokens()
 
 613         assert word_table.count_housenumbers() == 1
 
 616     def test_keep_housenumbers_from_placex_table_hnr_list(self, word_table, placex_table):
 
 617         word_table.add_housenumber(9991, '9 b')
 
 618         word_table.add_housenumber(9990, '34z')
 
 619         placex_table.add(housenumber='9 a;9 b;9 c')
 
 621         assert word_table.count_housenumbers() == 2
 
 622         self.tok.update_word_tokens()
 
 623         assert word_table.count_housenumbers() == 1