2 Tests for ICU tokenizer.
 
   9 from nominatim.tokenizer import icu_tokenizer
 
  10 import nominatim.tokenizer.icu_rule_loader
 
  11 from nominatim.db import properties
 
  12 from nominatim.db.sql_preprocessor import SQLPreprocessor
 
  13 from nominatim.indexer.place_info import PlaceInfo
 
  15 from mock_icu_word_table import MockIcuWordTable
 
  18 def word_table(temp_db_conn):
 
  19     return MockIcuWordTable(temp_db_conn)
 
  23 def test_config(project_env, tmp_path):
 
  24     sqldir = tmp_path / 'sql'
 
  26     (sqldir / 'tokenizer').mkdir()
 
  27     (sqldir / 'tokenizer' / 'icu_tokenizer.sql').write_text("SELECT 'a'")
 
  28     shutil.copy(str(project_env.lib_dir.sql / 'tokenizer' / 'icu_tokenizer_tables.sql'),
 
  29                 str(sqldir / 'tokenizer' / 'icu_tokenizer_tables.sql'))
 
  31     project_env.lib_dir.sql = sqldir
 
  37 def tokenizer_factory(dsn, tmp_path, property_table,
 
  38                       sql_preprocessor, place_table, word_table):
 
  39     (tmp_path / 'tokenizer').mkdir()
 
  42         return icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
 
  48 def db_prop(temp_db_conn):
 
  49     def _get_db_property(name):
 
  50         return properties.get_property(temp_db_conn, name)
 
  52     return _get_db_property
 
  56 def analyzer(tokenizer_factory, test_config, monkeypatch,
 
  57              temp_db_with_extensions, tmp_path):
 
  58     sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
 
  59     sql.write_text("SELECT 'a';")
 
  61     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
 
  62     tok = tokenizer_factory()
 
  63     tok.init_new_db(test_config)
 
  66     def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
 
  67                      variants=('~gasse -> gasse', 'street => st', ),
 
  69         cfgstr = {'normalization': list(norm),
 
  70                   'sanitizers': sanitizers,
 
  71                   'transliteration': list(trans),
 
  72                   'token-analysis': [{'analyzer': 'generic',
 
  73                                       'variants': [{'words': list(variants)}]}]}
 
  74         (test_config.project_dir / 'icu_tokenizer.yaml').write_text(yaml.dump(cfgstr))
 
  75         tok.loader = nominatim.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
 
  77         return tok.name_analyzer()
 
  82 def sql_functions(temp_db_conn, def_config, src_dir):
 
  83     orig_sql = def_config.lib_dir.sql
 
  84     def_config.lib_dir.sql = src_dir / 'lib-sql'
 
  85     sqlproc = SQLPreprocessor(temp_db_conn, def_config)
 
  86     sqlproc.run_sql_file(temp_db_conn, 'functions/utils.sql')
 
  87     sqlproc.run_sql_file(temp_db_conn, 'tokenizer/icu_tokenizer.sql')
 
  88     def_config.lib_dir.sql = orig_sql
 
  92 def getorcreate_full_word(temp_db_cursor):
 
  93     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
 
  94                                                  norm_term TEXT, lookup_terms TEXT[],
 
  96                                                  OUT partial_tokens INT[])
 
  99   partial_terms TEXT[] = '{}'::TEXT[];
 
 104   SELECT min(word_id) INTO full_token
 
 105     FROM word WHERE info->>'word' = norm_term and type = 'W';
 
 107   IF full_token IS NULL THEN
 
 108     full_token := nextval('seq_word');
 
 109     INSERT INTO word (word_id, word_token, type, info)
 
 110       SELECT full_token, lookup_term, 'W',
 
 111              json_build_object('word', norm_term, 'count', 0)
 
 112         FROM unnest(lookup_terms) as lookup_term;
 
 115   FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
 
 117     IF NOT (ARRAY[term] <@ partial_terms) THEN
 
 118       partial_terms := partial_terms || term;
 
 122   partial_tokens := '{}'::INT[];
 
 123   FOR term IN SELECT unnest(partial_terms) LOOP
 
 124     SELECT min(word_id), max(info->>'count') INTO term_id, term_count
 
 125       FROM word WHERE word_token = term and type = 'w';
 
 127     IF term_id IS NULL THEN
 
 128       term_id := nextval('seq_word');
 
 130       INSERT INTO word (word_id, word_token, type, info)
 
 131         VALUES (term_id, term, 'w', json_build_object('count', term_count));
 
 134     IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
 
 135       partial_tokens := partial_tokens || term_id;
 
 145 def test_init_new(tokenizer_factory, test_config, db_prop):
 
 146     tok = tokenizer_factory()
 
 147     tok.init_new_db(test_config)
 
 149     assert db_prop(nominatim.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES) \
 
 150             .startswith(':: lower ();')
 
 153 def test_init_word_table(tokenizer_factory, test_config, place_row, temp_db_cursor):
 
 154     place_row(names={'name' : 'Test Area', 'ref' : '52'})
 
 155     place_row(names={'name' : 'No Area'})
 
 156     place_row(names={'name' : 'Holzstrasse'})
 
 158     tok = tokenizer_factory()
 
 159     tok.init_new_db(test_config)
 
 161     assert temp_db_cursor.table_exists('word')
 
 164 def test_init_from_project(test_config, tokenizer_factory):
 
 165     tok = tokenizer_factory()
 
 166     tok.init_new_db(test_config)
 
 168     tok = tokenizer_factory()
 
 169     tok.init_from_project(test_config)
 
 171     assert tok.loader is not None
 
 174 def test_update_sql_functions(db_prop, temp_db_cursor,
 
 175                               tokenizer_factory, test_config, table_factory,
 
 177     tok = tokenizer_factory()
 
 178     tok.init_new_db(test_config)
 
 180     table_factory('test', 'txt TEXT')
 
 182     func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
 
 183     func_file.write_text("""INSERT INTO test VALUES (1133)""")
 
 185     tok.update_sql_functions(test_config)
 
 187     test_content = temp_db_cursor.row_set('SELECT * FROM test')
 
 188     assert test_content == set((('1133', ), ))
 
 191 def test_finalize_import(tokenizer_factory, temp_db_conn,
 
 192                          temp_db_cursor, test_config, sql_preprocessor_cfg):
 
 193     func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer_indices.sql'
 
 194     func_file.write_text("""CREATE FUNCTION test() RETURNS TEXT
 
 195                             AS $$ SELECT 'b'::text $$ LANGUAGE SQL""")
 
 197     tok = tokenizer_factory()
 
 198     tok.init_new_db(test_config)
 
 200     tok.finalize_import(test_config)
 
 202     temp_db_cursor.scalar('SELECT test()') == 'b'
 
 205 def test_check_database(test_config, tokenizer_factory,
 
 206                         temp_db_cursor, sql_preprocessor_cfg):
 
 207     tok = tokenizer_factory()
 
 208     tok.init_new_db(test_config)
 
 210     assert tok.check_database(test_config) is None
 
 213 def test_update_statistics_reverse_only(word_table, tokenizer_factory):
 
 214     tok = tokenizer_factory()
 
 215     tok.update_statistics()
 
 218 def test_update_statistics(word_table, table_factory, temp_db_cursor, tokenizer_factory):
 
 219     word_table.add_full_word(1000, 'hello')
 
 220     table_factory('search_name',
 
 221                   'place_id BIGINT, name_vector INT[]',
 
 223     tok = tokenizer_factory()
 
 225     tok.update_statistics()
 
 227     assert temp_db_cursor.scalar("""SELECT count(*) FROM word
 
 229                                           (info->>'count')::int > 0""") > 0
 
 232 def test_normalize_postcode(analyzer):
 
 233     with analyzer() as anl:
 
 234         anl.normalize_postcode('123') == '123'
 
 235         anl.normalize_postcode('ab-34 ') == 'AB-34'
 
 236         anl.normalize_postcode('38 Б') == '38 Б'
 
 239 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
 
 240     table_factory('location_postcode', 'postcode TEXT',
 
 241                   content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
 
 243     with analyzer() as anl:
 
 244         anl.update_postcodes_from_db()
 
 246     assert word_table.count() == 3
 
 247     assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
 
 250 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
 
 251     table_factory('location_postcode', 'postcode TEXT',
 
 252                   content=(('1234',), ('45BC', ), ('XX45', )))
 
 253     word_table.add_postcode(' 1234', '1234')
 
 254     word_table.add_postcode(' 5678', '5678')
 
 256     with analyzer() as anl:
 
 257         anl.update_postcodes_from_db()
 
 259     assert word_table.count() == 3
 
 260     assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
 
 263 def test_update_special_phrase_empty_table(analyzer, word_table):
 
 264     with analyzer() as anl:
 
 265         anl.update_special_phrases([
 
 266             ("König  bei", "amenity", "royal", "near"),
 
 267             ("Könige ", "amenity", "royal", "-"),
 
 268             ("street", "highway", "primary", "in")
 
 271     assert word_table.get_special() \
 
 272                == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
 
 273                    ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
 
 274                    ('STREET', 'street', 'highway', 'primary', 'in')}
 
 277 def test_update_special_phrase_delete_all(analyzer, word_table):
 
 278     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
 
 279     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
 
 281     assert word_table.count_special() == 2
 
 283     with analyzer() as anl:
 
 284         anl.update_special_phrases([], True)
 
 286     assert word_table.count_special() == 0
 
 289 def test_update_special_phrases_no_replace(analyzer, word_table):
 
 290     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
 
 291     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
 
 293     assert word_table.count_special() == 2
 
 295     with analyzer() as anl:
 
 296         anl.update_special_phrases([], False)
 
 298     assert word_table.count_special() == 2
 
 301 def test_update_special_phrase_modify(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([
 
 309             ('prison', 'amenity', 'prison', 'in'),
 
 310             ('bar', 'highway', 'road', '-'),
 
 311             ('garden', 'leisure', 'garden', 'near')
 
 314     assert word_table.get_special() \
 
 315                == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
 
 316                    ('BAR', 'bar', 'highway', 'road', None),
 
 317                    ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
 
 320 def test_add_country_names_new(analyzer, word_table):
 
 321     with analyzer() as anl:
 
 322         anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
 
 324     assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
 
 327 def test_add_country_names_extend(analyzer, word_table):
 
 328     word_table.add_country('ch', 'SCHWEIZ')
 
 330     with analyzer() as anl:
 
 331         anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
 
 333     assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
 
 336 class TestPlaceNames:
 
 338     @pytest.fixture(autouse=True)
 
 339     def setup(self, analyzer, sql_functions):
 
 340         sanitizers = [{'step': 'split-name-list'},
 
 341                       {'step': 'strip-brace-terms'}]
 
 342         with analyzer(sanitizers=sanitizers) as anl:
 
 347     def expect_name_terms(self, info, *expected_terms):
 
 348         tokens = self.analyzer.get_word_token_info(expected_terms)
 
 350             assert token[2] is not None, "No token for {0}".format(token)
 
 352         assert eval(info['names']) == set((t[2] for t in tokens))
 
 355     def process_named_place(self, names):
 
 356         return self.analyzer.process_place(PlaceInfo({'name': names}))
 
 359     def test_simple_names(self):
 
 360         info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
 
 362         self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
 
 365     @pytest.mark.parametrize('sep', [',' , ';'])
 
 366     def test_names_with_separator(self, sep):
 
 367         info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
 
 369         self.expect_name_terms(info, '#New York', '#Big Apple',
 
 370                                      'new', 'york', 'big', 'apple')
 
 373     def test_full_names_with_bracket(self):
 
 374         info = self.process_named_place({'name': 'Houseboat (left)'})
 
 376         self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
 
 380     def test_country_name(self, word_table):
 
 381         place = PlaceInfo({'name' : {'name': 'Norge'},
 
 382                            'country_code': 'no',
 
 385                            'type': 'administrative'})
 
 387         info = self.analyzer.process_place(place)
 
 389         self.expect_name_terms(info, '#norge', 'norge')
 
 390         assert word_table.get_country() == {('no', 'NORGE')}
 
 393 class TestPlaceAddress:
 
 395     @pytest.fixture(autouse=True)
 
 396     def setup(self, analyzer, sql_functions):
 
 397         with analyzer(trans=(":: upper()", "'🜵' > ' '")) as anl:
 
 403     def getorcreate_hnr_id(self, temp_db_cursor):
 
 404         temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
 
 405                                   RETURNS INTEGER AS $$
 
 406                                     SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
 
 409     def process_address(self, **kwargs):
 
 410         return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
 
 413     def name_token_set(self, *expected_terms):
 
 414         tokens = self.analyzer.get_word_token_info(expected_terms)
 
 416             assert token[2] is not None, "No token for {0}".format(token)
 
 418         return set((t[2] for t in tokens))
 
 421     @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
 
 422     def test_process_place_postcode(self, word_table, pcode):
 
 423         self.process_address(postcode=pcode)
 
 425         assert word_table.get_postcodes() == {pcode, }
 
 428     @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
 
 429     def test_process_place_bad_postcode(self, word_table, pcode):
 
 430         self.process_address(postcode=pcode)
 
 432         assert not word_table.get_postcodes()
 
 435     @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
 
 436     def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
 
 437         info = self.process_address(housenumber=hnr)
 
 439         assert info['hnr'] == hnr.upper()
 
 440         assert info['hnr_tokens'] == "{-1}"
 
 443     def test_process_place_housenumbers_lists(self, getorcreate_hnr_id):
 
 444         info = self.process_address(conscriptionnumber='1; 2;3')
 
 446         assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
 
 447         assert info['hnr_tokens'] == "{-1,-2,-3}"
 
 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}"
 
 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}
 
 473     def test_process_place_street(self):
 
 474         info = self.process_address(street='Grand Road')
 
 476         assert eval(info['street']) == self.name_token_set('GRAND', 'ROAD')
 
 479     def test_process_place_street_empty(self):
 
 480         info = self.process_address(street='🜵')
 
 482         assert 'street' not in info
 
 485     def test_process_place_place(self):
 
 486         info = self.process_address(place='Honu Lulu')
 
 488         assert eval(info['place']) == self.name_token_set('HONU', 'LULU')
 
 491     def test_process_place_place_empty(self):
 
 492         info = self.process_address(place='🜵')
 
 494         assert 'place' not in info
 
 497     def test_process_place_address_terms(self):
 
 498         info = self.process_address(country='de', city='Zwickau', state='Sachsen',
 
 499                                     suburb='Zwickau', street='Hauptstr',
 
 500                                     full='right behind the church')
 
 502         city = self.name_token_set('ZWICKAU')
 
 503         state = self.name_token_set('SACHSEN')
 
 505         result = {k: eval(v) for k,v in info['addr'].items()}
 
 507         assert result == {'city': city, 'suburb': city, 'state': state}
 
 510     def test_process_place_address_terms_empty(self):
 
 511         info = self.process_address(country='de', city=' ', street='Hauptstr',
 
 512                                     full='right behind the church')
 
 514         assert 'addr' not in info