2     Tests for import special phrases methods
 
   3     of the class SpecialPhrasesImporter.
 
   5 from nominatim.errors import UsageError
 
   6 from pathlib import Path
 
   8 from shutil import copyfile
 
  10 from nominatim.tools.special_phrases import SpecialPhrasesImporter
 
  12 TEST_BASE_DIR = Path(__file__) / '..' / '..'
 
  14 def test_check_sanity_class(special_phrases_importer):
 
  16         Check for _check_sanity() method.
 
  17         If a wrong class or type is given, an UsageError should raise.
 
  18         If a good class and type are given, nothing special happens.
 
  20     with pytest.raises(UsageError):
 
  21         special_phrases_importer._check_sanity('en', '', 'type')
 
  23     with pytest.raises(UsageError):
 
  24         special_phrases_importer._check_sanity('en', 'class', '')
 
  26     special_phrases_importer._check_sanity('en', 'class', 'type')
 
  28 def test_load_white_and_black_lists(special_phrases_importer):
 
  30         Test that _load_white_and_black_lists() well return
 
  31         black list and white list and that they are of dict type.
 
  33     black_list, white_list = special_phrases_importer._load_white_and_black_lists()
 
  35     assert isinstance(black_list, dict) and isinstance(white_list, dict)
 
  37 def test_convert_php_settings(special_phrases_importer):
 
  39         Test that _convert_php_settings_if_needed() convert the given
 
  40         php file to a json file.
 
  42     php_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.php').resolve()
 
  44     with tempfile.TemporaryDirectory() as temp_dir:
 
  45         temp_settings = (Path(temp_dir) / 'phrase_settings.php').resolve()
 
  46         copyfile(php_file, temp_settings)
 
  47         special_phrases_importer._convert_php_settings_if_needed(temp_settings)
 
  49         assert (Path(temp_dir) / 'phrase_settings.json').is_file()
 
  51 def test_convert_settings_wrong_file(special_phrases_importer):
 
  53         Test that _convert_php_settings_if_needed() raise an exception
 
  54         if the given file is not a valid file.
 
  56     with pytest.raises(UsageError, match='random_file is not a valid file.'):
 
  57         special_phrases_importer._convert_php_settings_if_needed('random_file')
 
  59 def test_convert_settings_json_already_exist(special_phrases_importer):
 
  61         Test that if we give to '_convert_php_settings_if_needed' a php file path
 
  62         and that a the corresponding json file already exists, it is returned.
 
  64     php_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.php').resolve()
 
  65     json_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.json').resolve()
 
  67     returned = special_phrases_importer._convert_php_settings_if_needed(php_file)
 
  69     assert returned == json_file
 
  71 def test_convert_settings_giving_json(special_phrases_importer):
 
  73         Test that if we give to '_convert_php_settings_if_needed' a json file path
 
  74         the same path is directly returned
 
  76     json_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.json').resolve()
 
  78     returned = special_phrases_importer._convert_php_settings_if_needed(json_file)
 
  80     assert returned == json_file
 
  82 def test_process_amenity_with_operator(special_phrases_importer, getorcreate_amenityoperator_funcs,
 
  83                                        word_table, temp_db_conn):
 
  85         Test that _process_amenity() execute well the 
 
  86         getorcreate_amenityoperator() SQL function and that
 
  87         the 2 differents operators are well handled.
 
  89     special_phrases_importer._process_amenity('', '', '', '', 'near')
 
  90     special_phrases_importer._process_amenity('', '', '', '', 'in')
 
  92     with temp_db_conn.cursor() as temp_db_cursor:
 
  93         temp_db_cursor.execute("SELECT * FROM temp_with_operator WHERE op='near' OR op='in'")
 
  94         results = temp_db_cursor.fetchall()
 
  96     assert len(results) == 2
 
  98 def test_process_amenity_without_operator(special_phrases_importer, getorcreate_amenity_funcs,
 
 101         Test that _process_amenity() execute well the
 
 102         getorcreate_amenity() SQL function.
 
 104     special_phrases_importer._process_amenity('', '', '', '', '')
 
 106     with temp_db_conn.cursor() as temp_db_cursor:
 
 107         temp_db_cursor.execute("SELECT * FROM temp_without_operator WHERE op='no_operator'")
 
 108         result = temp_db_cursor.fetchone()
 
 112 def test_create_place_classtype_indexes(temp_db_conn, special_phrases_importer):
 
 114         Test that _create_place_classtype_indexes() create the
 
 115         place_id index and centroid index on the right place_class_type table.
 
 117     phrase_class = 'class'
 
 119     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
 
 121     with temp_db_conn.cursor() as temp_db_cursor:
 
 122         temp_db_cursor.execute("CREATE EXTENSION postgis;")
 
 123         temp_db_cursor.execute('CREATE TABLE {}(place_id BIGINT, centroid GEOMETRY)'.format(table_name))
 
 125     special_phrases_importer._create_place_classtype_indexes('', phrase_class, phrase_type)
 
 127     assert check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type)
 
 129 def test_create_place_classtype_table(temp_db_conn, placex_table, special_phrases_importer):
 
 131         Test that _create_place_classtype_table() create
 
 132         the right place_classtype table.
 
 134     phrase_class = 'class'
 
 136     special_phrases_importer._create_place_classtype_table('', phrase_class, phrase_type)
 
 138     assert check_table_exist(temp_db_conn, phrase_class, phrase_type)
 
 140 def test_grant_access_to_web_user(temp_db_conn, def_config, special_phrases_importer):
 
 142         Test that _grant_access_to_webuser() give 
 
 143         right access to the web user.
 
 145     phrase_class = 'class'
 
 147     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
 
 149     with temp_db_conn.cursor() as temp_db_cursor:
 
 150         temp_db_cursor.execute('CREATE TABLE {}()'.format(table_name))
 
 152     special_phrases_importer._grant_access_to_webuser(phrase_class, phrase_type)
 
 154     assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, phrase_class, phrase_type)
 
 156 def test_create_place_classtype_table_and_indexes(
 
 157         temp_db_conn, def_config, placex_table, getorcreate_amenity_funcs,
 
 158         getorcreate_amenityoperator_funcs, special_phrases_importer):
 
 160         Test that _create_place_classtype_table_and_indexes()
 
 161         create the right place_classtype tables and place_id indexes
 
 162         and centroid indexes and grant access to the web user
 
 163         for the given set of pairs.
 
 165     pairs = set([('class1', 'type1'), ('class2', 'type2')])
 
 167     special_phrases_importer._create_place_classtype_table_and_indexes(pairs)
 
 170         assert check_table_exist(temp_db_conn, pair[0], pair[1])
 
 171         assert check_placeid_and_centroid_indexes(temp_db_conn, pair[0], pair[1])
 
 172         assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, pair[0], pair[1])
 
 174 def test_process_xml_content(temp_db_conn, def_config, special_phrases_importer, 
 
 175                              getorcreate_amenity_funcs, getorcreate_amenityoperator_funcs):
 
 177         Test that _process_xml_content() process the given xml content right
 
 178         by executing the right SQL functions for amenities and 
 
 179         by returning the right set of pairs.
 
 181     class_test = 'aerialway'
 
 182     type_test = 'zip_line'
 
 184     #Converted output set to a dict for easy assert further.
 
 185     results = dict(special_phrases_importer._process_xml_content(get_test_xml_wiki_content(), 'en'))
 
 187     assert check_amenities_with_op(temp_db_conn)
 
 188     assert check_amenities_without_op(temp_db_conn)
 
 189     assert results[class_test] and type_test in results.values()
 
 191 def test_import_from_wiki(monkeypatch, temp_db_conn, def_config, special_phrases_importer, placex_table, 
 
 192                           getorcreate_amenity_funcs, getorcreate_amenityoperator_funcs):
 
 194         Check that the main import_from_wiki() method is well executed.
 
 195         It should create the place_classtype table, the place_id and centroid indexes,
 
 196         grand access to the web user and executing the SQL functions for amenities.
 
 198     monkeypatch.setattr('nominatim.tools.special_phrases.SpecialPhrasesImporter._get_wiki_content', mock_get_wiki_content)
 
 199     special_phrases_importer.import_from_wiki(['en'])
 
 201     class_test = 'aerialway'
 
 202     type_test = 'zip_line'
 
 204     assert check_table_exist(temp_db_conn, class_test, type_test)
 
 205     assert check_placeid_and_centroid_indexes(temp_db_conn, class_test, type_test)
 
 206     assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, class_test, type_test)
 
 207     assert check_amenities_with_op(temp_db_conn)
 
 208     assert check_amenities_without_op(temp_db_conn)
 
 210 def mock_get_wiki_content(lang):
 
 212         Mock the _get_wiki_content() method to return
 
 213         static xml test file content.
 
 215     return get_test_xml_wiki_content()
 
 217 def get_test_xml_wiki_content():
 
 219         return the content of the static xml test file.
 
 221     xml_test_content_path = (TEST_BASE_DIR / 'testdata' / 'special_phrases_test_content.txt').resolve()
 
 222     with open(xml_test_content_path) as xml_content_reader:
 
 223         return xml_content_reader.read()
 
 225 def check_table_exist(temp_db_conn, phrase_class, phrase_type):
 
 227         Verify that the place_classtype table exists for the given
 
 228         phrase_class and phrase_type.
 
 230     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
 
 232     with temp_db_conn.cursor() as temp_db_cursor:
 
 233         temp_db_cursor.execute("""
 
 235             FROM information_schema.tables
 
 236             WHERE table_type='BASE TABLE'
 
 237             AND table_name='{}'""".format(table_name))
 
 238         return temp_db_cursor.fetchone()
 
 240 def check_grant_access(temp_db_conn, user, phrase_class, phrase_type):
 
 242         Check that the web user has been granted right access to the
 
 243         place_classtype table of the given phrase_class and phrase_type.
 
 245     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
 
 247     with temp_db_conn.cursor() as temp_db_cursor:
 
 248         temp_db_cursor.execute("""
 
 249                 SELECT * FROM information_schema.role_table_grants
 
 250                 WHERE table_name='{}'
 
 252                 AND privilege_type='SELECT'""".format(table_name, user))
 
 253         return temp_db_cursor.fetchone()
 
 255 def check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type):
 
 257         Check that the place_id index and centroid index exist for the
 
 258         place_classtype table of the given phrase_class and phrase_type.
 
 260     index_prefix = 'idx_place_classtype_{}_{}_'.format(phrase_class, phrase_type)
 
 263         temp_db_conn.index_exists(index_prefix + 'centroid')
 
 265         temp_db_conn.index_exists(index_prefix + 'place_id')
 
 268 def check_amenities_with_op(temp_db_conn):
 
 270         Check that the test table for the SQL function getorcreate_amenityoperator()
 
 271         contains more than one value (so that the SQL function was call more than one time).
 
 273     with temp_db_conn.cursor() as temp_db_cursor:
 
 274         temp_db_cursor.execute("SELECT * FROM temp_with_operator")
 
 275         return len(temp_db_cursor.fetchall()) > 1
 
 277 def check_amenities_without_op(temp_db_conn):
 
 279         Check that the test table for the SQL function getorcreate_amenity()
 
 280         contains more than one value (so that the SQL function was call more than one time).
 
 282     with temp_db_conn.cursor() as temp_db_cursor:
 
 283         temp_db_cursor.execute("SELECT * FROM temp_without_operator")
 
 284         return len(temp_db_cursor.fetchall()) > 1
 
 287 def special_phrases_importer(temp_db_conn, def_config, temp_phplib_dir_with_migration):
 
 289         Return an instance of SpecialPhrasesImporter.
 
 291     return SpecialPhrasesImporter(def_config, temp_phplib_dir_with_migration, temp_db_conn)
 
 294 def temp_phplib_dir_with_migration():
 
 296         Return temporary phpdir with migration subdirectory and
 
 297         PhraseSettingsToJson.php script inside.
 
 299     migration_file = (TEST_BASE_DIR / '..' / 'lib-php' / 'migration'
 
 300                       / 'PhraseSettingsToJson.php').resolve()
 
 301     with tempfile.TemporaryDirectory() as phpdir:
 
 302         (Path(phpdir) / 'migration').mkdir()
 
 303         migration_dest_path = (Path(phpdir) / 'migration' / 'PhraseSettingsToJson.php').resolve()
 
 304         copyfile(migration_file, migration_dest_path)
 
 309 def make_strandard_name_func(temp_db_cursor):
 
 310     temp_db_cursor.execute("""
 
 311         CREATE OR REPLACE FUNCTION make_standard_name(name TEXT) RETURNS TEXT AS $$
 
 313         RETURN trim(name); --Basically return only the trimed name for the tests
 
 315         $$ LANGUAGE plpgsql IMMUTABLE;""")
 
 318 def getorcreate_amenity_funcs(temp_db_cursor, make_strandard_name_func):
 
 319     temp_db_cursor.execute("""
 
 320         CREATE TABLE temp_without_operator(op TEXT);
 
 322         CREATE OR REPLACE FUNCTION getorcreate_amenity(lookup_word TEXT, normalized_word TEXT,
 
 323                                                     lookup_class text, lookup_type text)
 
 326             INSERT INTO temp_without_operator VALUES('no_operator');
 
 328         $$ LANGUAGE plpgsql""")
 
 331 def getorcreate_amenityoperator_funcs(temp_db_cursor, make_strandard_name_func):
 
 332     temp_db_cursor.execute("""
 
 333         CREATE TABLE temp_with_operator(op TEXT);
 
 335         CREATE OR REPLACE FUNCTION getorcreate_amenityoperator(lookup_word TEXT, normalized_word TEXT,
 
 336                                                     lookup_class text, lookup_type text, op text)
 
 339             INSERT INTO temp_with_operator VALUES(op);
 
 341         $$ LANGUAGE plpgsql""")