2 Test for legacy tokenizer.
 
   8 from nominatim.indexer.place_info import PlaceInfo
 
   9 from nominatim.tokenizer import legacy_tokenizer
 
  10 from nominatim.db import properties
 
  11 from nominatim.errors import UsageError
 
  14 def test_config(def_config, tmp_path):
 
  15     def_config.project_dir = tmp_path / 'project'
 
  16     def_config.project_dir.mkdir()
 
  18     module_dir = tmp_path / 'module_src'
 
  20     (module_dir / 'nominatim.so').write_text('TEST nomiantim.so')
 
  22     def_config.lib_dir.module = module_dir
 
  24     sqldir = tmp_path / 'sql'
 
  26     (sqldir / 'tokenizer').mkdir()
 
  27     (sqldir / 'tokenizer' / 'legacy_tokenizer.sql').write_text("SELECT 'a'")
 
  28     (sqldir / 'words.sql').write_text("SELECT 'a'")
 
  29     shutil.copy(str(def_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer_tables.sql'),
 
  30                 str(sqldir / 'tokenizer' / 'legacy_tokenizer_tables.sql'))
 
  32     def_config.lib_dir.sql = sqldir
 
  33     def_config.lib_dir.data = sqldir
 
  39 def tokenizer_factory(dsn, tmp_path, property_table):
 
  40     (tmp_path / 'tokenizer').mkdir()
 
  43         return legacy_tokenizer.create(dsn, tmp_path / 'tokenizer')
 
  49 def tokenizer_setup(tokenizer_factory, test_config, monkeypatch, sql_preprocessor):
 
  50     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
 
  51     tok = tokenizer_factory()
 
  52     tok.init_new_db(test_config)
 
  56 def analyzer(tokenizer_factory, test_config, monkeypatch, sql_preprocessor,
 
  57              word_table, temp_db_with_extensions, tmp_path):
 
  58     sql = tmp_path / 'sql' / 'tokenizer' / 'legacy_tokenizer.sql'
 
  60         CREATE OR REPLACE FUNCTION getorcreate_housenumber_id(lookup_word TEXT)
 
  61           RETURNS INTEGER AS $$ SELECT 342; $$ LANGUAGE SQL;
 
  64     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
 
  65     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
 
  66     tok = tokenizer_factory()
 
  67     tok.init_new_db(test_config)
 
  70     with tok.name_analyzer() as analyzer:
 
  75 def make_standard_name(temp_db_cursor):
 
  76     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION make_standard_name(name TEXT)
 
  77                               RETURNS TEXT AS $$ SELECT '#' || lower(name) || '#'; $$ LANGUAGE SQL""")
 
  81 def create_postcode_id(temp_db_cursor):
 
  82     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION create_postcode_id(postcode TEXT)
 
  84                               INSERT INTO word (word_token, word, class, type)
 
  85                                 VALUES (' ' || postcode, postcode, 'place', 'postcode')
 
  91 def make_keywords(temp_db_cursor, temp_db_with_extensions):
 
  92     temp_db_cursor.execute(
 
  93         """CREATE OR REPLACE FUNCTION make_keywords(names HSTORE)
 
  94            RETURNS INTEGER[] AS $$ SELECT ARRAY[1, 2, 3] $$ LANGUAGE SQL""")
 
  96 def test_init_new(tokenizer_factory, test_config, monkeypatch,
 
  97                   temp_db_conn, sql_preprocessor):
 
  98     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', 'xxvv')
 
  99     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
 
 101     tok = tokenizer_factory()
 
 102     tok.init_new_db(test_config)
 
 104     assert properties.get_property(temp_db_conn, legacy_tokenizer.DBCFG_NORMALIZATION) == 'xxvv'
 
 106     outfile = test_config.project_dir / 'module' / 'nominatim.so'
 
 108     assert outfile.exists()
 
 109     assert outfile.read_text() == 'TEST nomiantim.so'
 
 110     assert outfile.stat().st_mode == 33261
 
 113 def test_init_module_load_failed(tokenizer_factory, test_config):
 
 114     tok = tokenizer_factory()
 
 116     with pytest.raises(UsageError):
 
 117         tok.init_new_db(test_config)
 
 120 def test_init_module_custom(tokenizer_factory, test_config,
 
 121                             monkeypatch, tmp_path, sql_preprocessor):
 
 122     module_dir = (tmp_path / 'custom').resolve()
 
 124     (module_dir/ 'nominatim.so').write_text('CUSTOM nomiantim.so')
 
 126     monkeypatch.setenv('NOMINATIM_DATABASE_MODULE_PATH', str(module_dir))
 
 127     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
 
 129     tok = tokenizer_factory()
 
 130     tok.init_new_db(test_config)
 
 132     assert not (test_config.project_dir / 'module').exists()
 
 135 def test_init_from_project(tokenizer_setup, tokenizer_factory, test_config):
 
 136     tok = tokenizer_factory()
 
 138     tok.init_from_project(test_config)
 
 140     assert tok.normalization is not None
 
 143 def test_update_sql_functions(sql_preprocessor, temp_db_conn,
 
 144                               tokenizer_factory, test_config, table_factory,
 
 145                               monkeypatch, temp_db_cursor):
 
 146     monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '1133')
 
 147     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
 
 148     tok = tokenizer_factory()
 
 149     tok.init_new_db(test_config)
 
 152     assert properties.get_property(temp_db_conn, legacy_tokenizer.DBCFG_MAXWORDFREQ) == '1133'
 
 154     table_factory('test', 'txt TEXT')
 
 156     func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer.sql'
 
 157     func_file.write_text("""INSERT INTO test VALUES ('{{max_word_freq}}'),
 
 158                                                    ('{{modulepath}}')""")
 
 160     tok.update_sql_functions(test_config)
 
 162     test_content = temp_db_cursor.row_set('SELECT * FROM test')
 
 163     assert test_content == set((('1133', ), (str(test_config.project_dir / 'module'), )))
 
 166 def test_migrate_database(tokenizer_factory, test_config, temp_db_conn, monkeypatch):
 
 167     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
 
 168     tok = tokenizer_factory()
 
 169     tok.migrate_database(test_config)
 
 171     assert properties.get_property(temp_db_conn, legacy_tokenizer.DBCFG_MAXWORDFREQ) is not None
 
 172     assert properties.get_property(temp_db_conn, legacy_tokenizer.DBCFG_NORMALIZATION) is not None
 
 174     outfile = test_config.project_dir / 'module' / 'nominatim.so'
 
 176     assert outfile.exists()
 
 177     assert outfile.read_text() == 'TEST nomiantim.so'
 
 178     assert outfile.stat().st_mode == 33261
 
 181 def test_normalize(analyzer):
 
 182     assert analyzer.normalize('TEsT') == 'test'
 
 185 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table,
 
 187     table_factory('location_postcode', 'postcode TEXT',
 
 188                   content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
 
 190     analyzer.update_postcodes_from_db()
 
 192     assert word_table.count() == 3
 
 193     assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
 
 196 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table,
 
 198     table_factory('location_postcode', 'postcode TEXT',
 
 199                   content=(('1234',), ('45BC', ), ('XX45', )))
 
 200     word_table.add_postcode(' 1234', '1234')
 
 201     word_table.add_postcode(' 5678', '5678')
 
 203     analyzer.update_postcodes_from_db()
 
 205     assert word_table.count() == 3
 
 206     assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
 
 209 def test_update_special_phrase_empty_table(analyzer, word_table, make_standard_name):
 
 210     analyzer.update_special_phrases([
 
 211         ("König bei", "amenity", "royal", "near"),
 
 212         ("Könige", "amenity", "royal", "-"),
 
 213         ("könige", "amenity", "royal", "-"),
 
 214         ("strasse", "highway", "primary", "in")
 
 217     assert word_table.get_special() \
 
 218                == set(((' #könig bei#', 'könig bei', 'amenity', 'royal', 'near'),
 
 219                        (' #könige#', 'könige', 'amenity', 'royal', None),
 
 220                        (' #strasse#', 'strasse', 'highway', 'primary', 'in')))
 
 223 def test_update_special_phrase_delete_all(analyzer, word_table, make_standard_name):
 
 224     word_table.add_special(' #foo#', 'foo', 'amenity', 'prison', 'in')
 
 225     word_table.add_special(' #bar#', 'bar', 'highway', 'road', None)
 
 227     assert word_table.count_special() == 2
 
 229     analyzer.update_special_phrases([], True)
 
 231     assert word_table.count_special() == 0
 
 234 def test_update_special_phrases_no_replace(analyzer, word_table, make_standard_name):
 
 235     word_table.add_special(' #foo#', 'foo', 'amenity', 'prison', 'in')
 
 236     word_table.add_special(' #bar#', 'bar', 'highway', 'road', None)
 
 238     assert word_table.count_special() == 2
 
 240     analyzer.update_special_phrases([], False)
 
 242     assert word_table.count_special() == 2
 
 245 def test_update_special_phrase_modify(analyzer, word_table, make_standard_name):
 
 246     word_table.add_special(' #foo#', 'foo', 'amenity', 'prison', 'in')
 
 247     word_table.add_special(' #bar#', 'bar', 'highway', 'road', None)
 
 249     assert word_table.count_special() == 2
 
 251     analyzer.update_special_phrases([
 
 252         ('prison', 'amenity', 'prison', 'in'),
 
 253         ('bar', 'highway', 'road', '-'),
 
 254         ('garden', 'leisure', 'garden', 'near')
 
 257     assert word_table.get_special() \
 
 258                == set(((' #prison#', 'prison', 'amenity', 'prison', 'in'),
 
 259                        (' #bar#', 'bar', 'highway', 'road', None),
 
 260                        (' #garden#', 'garden', 'leisure', 'garden', 'near')))
 
 263 def test_add_country_names(analyzer, word_table, make_standard_name):
 
 264     analyzer.add_country_names('de', {'name': 'Germany',
 
 265                                       'name:de': 'Deutschland',
 
 266                                       'short_name': 'germany'})
 
 268     assert word_table.get_country() \
 
 269                == {('de', ' #germany#'),
 
 270                    ('de', ' #deutschland#')}
 
 273 def test_add_more_country_names(analyzer, word_table, make_standard_name):
 
 274     word_table.add_country('fr', ' #france#')
 
 275     word_table.add_country('it', ' #italy#')
 
 276     word_table.add_country('it', ' #itala#')
 
 278     analyzer.add_country_names('it', {'name': 'Italy', 'ref': 'IT'})
 
 280     assert word_table.get_country() \
 
 281                == {('fr', ' #france#'),
 
 287 def test_process_place_names(analyzer, make_keywords):
 
 288     info = analyzer.process_place(PlaceInfo({'name' : {'name' : 'Soft bAr', 'ref': '34'}}))
 
 290     assert info['names'] == '{1,2,3}'
 
 293 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
 
 294 def test_process_place_postcode(analyzer, create_postcode_id, word_table, pcode):
 
 295     analyzer.process_place(PlaceInfo({'address': {'postcode' : pcode}}))
 
 297     assert word_table.get_postcodes() == {pcode, }
 
 300 @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
 
 301 def test_process_place_bad_postcode(analyzer, create_postcode_id, word_table, pcode):
 
 302     analyzer.process_place(PlaceInfo({'address': {'postcode' : pcode}}))
 
 304     assert not word_table.get_postcodes()
 
 307 class TestHousenumberName:
 
 310     @pytest.fixture(autouse=True)
 
 311     def setup_create_housenumbers(temp_db_cursor):
 
 312         temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION create_housenumbers(
 
 314                                       OUT tokens TEXT, OUT normtext TEXT)
 
 316                                   SELECT housenumbers::TEXT, array_to_string(housenumbers, ';')
 
 321     @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
 
 322     def test_process_place_housenumbers_simple(analyzer, hnr):
 
 323         info = analyzer.process_place(PlaceInfo({'address': {'housenumber' : hnr}}))
 
 325         assert info['hnr'] == hnr
 
 326         assert info['hnr_tokens'].startswith("{")
 
 330     def test_process_place_housenumbers_lists(analyzer):
 
 331         info = analyzer.process_place(PlaceInfo({'address': {'conscriptionnumber' : '1; 2;3'}}))
 
 333         assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
 
 337     def test_process_place_housenumbers_duplicates(analyzer):
 
 338         info = analyzer.process_place(PlaceInfo({'address': {'housenumber' : '134',
 
 339                                                    'conscriptionnumber' : '134',
 
 340                                                    'streetnumber' : '99a'}}))
 
 342         assert set(info['hnr'].split(';')) == set(('134', '99a'))