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) as wrong_class:
21 special_phrases_importer._check_sanity('en', '', 'type')
23 with pytest.raises(UsageError) as wrong_type:
24 special_phrases_importer._check_sanity('en', 'class', '')
26 special_phrases_importer._check_sanity('en', 'class', 'type')
28 assert wrong_class and wrong_type
30 def test_load_white_and_black_lists(special_phrases_importer):
32 Test that _load_white_and_black_lists() well return
33 black list and white list and that they are of dict type.
35 black_list, white_list = special_phrases_importer._load_white_and_black_lists()
37 assert isinstance(black_list, dict) and isinstance(white_list, dict)
39 def test_convert_php_settings(special_phrases_importer):
41 Test that _convert_php_settings_if_needed() convert the given
42 php file to a json file.
44 php_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.php').resolve()
46 with tempfile.TemporaryDirectory() as temp_dir:
47 temp_settings = (Path(temp_dir) / 'phrase_settings.php').resolve()
48 copyfile(php_file, temp_settings)
49 special_phrases_importer._convert_php_settings_if_needed(temp_settings)
51 assert (Path(temp_dir) / 'phrase_settings.json').is_file()
53 def test_convert_settings_wrong_file(special_phrases_importer):
55 Test that _convert_php_settings_if_needed() raise an exception
56 if the given file is not a valid file.
59 with pytest.raises(UsageError) as exceptioninfos:
60 special_phrases_importer._convert_php_settings_if_needed('random_file')
62 assert str(exceptioninfos.value) == 'random_file is not a valid file.'
64 def test_convert_settings_json_already_exist(special_phrases_importer):
66 Test that if we give to '_convert_php_settings_if_needed' a php file path
67 and that a the corresponding json file already exists, it is returned.
69 php_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.php').resolve()
70 json_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.json').resolve()
72 returned = special_phrases_importer._convert_php_settings_if_needed(php_file)
74 assert returned == json_file
76 def test_convert_settings_giving_json(special_phrases_importer):
78 Test that if we give to '_convert_php_settings_if_needed' a json file path
79 the same path is directly returned
81 json_file = (TEST_BASE_DIR / 'testfiles' / 'phrase-settings.json').resolve()
83 returned = special_phrases_importer._convert_php_settings_if_needed(json_file)
85 assert returned == json_file
87 def test_process_amenity_with_operator(special_phrases_importer, getorcreate_amenityoperator_funcs,
88 word_table, temp_db_conn):
90 Test that _process_amenity() execute well the
91 getorcreate_amenityoperator() SQL function and that
92 the 2 differents operators are well handled.
94 special_phrases_importer._process_amenity('', '', '', '', 'near')
95 special_phrases_importer._process_amenity('', '', '', '', 'in')
97 with temp_db_conn.cursor() as temp_db_cursor:
98 temp_db_cursor.execute("SELECT * FROM temp_with_operator WHERE op='near' OR op='in'")
99 results = temp_db_cursor.fetchall()
101 assert len(results) == 2
103 def test_process_amenity_without_operator(special_phrases_importer, getorcreate_amenity_funcs,
106 Test that _process_amenity() execute well the
107 getorcreate_amenity() SQL function.
109 special_phrases_importer._process_amenity('', '', '', '', '')
111 with temp_db_conn.cursor() as temp_db_cursor:
112 temp_db_cursor.execute("SELECT * FROM temp_without_operator WHERE op='no_operator'")
113 result = temp_db_cursor.fetchone()
117 def test_create_place_classtype_indexes(temp_db_conn, special_phrases_importer):
119 Test that _create_place_classtype_indexes() create the
120 place_id index and centroid index on the right place_class_type table.
122 phrase_class = 'class'
124 table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
126 with temp_db_conn.cursor() as temp_db_cursor:
127 temp_db_cursor.execute("CREATE EXTENSION postgis;")
128 temp_db_cursor.execute('CREATE TABLE {}(place_id BIGINT, centroid GEOMETRY)'.format(table_name))
130 special_phrases_importer._create_place_classtype_indexes('', phrase_class, phrase_type)
132 assert check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type)
134 def test_create_place_classtype_table(temp_db_conn, placex_table, special_phrases_importer):
136 Test that _create_place_classtype_table() create
137 the right place_classtype table.
139 phrase_class = 'class'
141 special_phrases_importer._create_place_classtype_table('', phrase_class, phrase_type)
143 assert check_table_exist(temp_db_conn, phrase_class, phrase_type)
145 def test_grant_access_to_web_user(temp_db_conn, def_config, special_phrases_importer):
147 Test that _grant_access_to_webuser() give
148 right access to the web user.
150 phrase_class = 'class'
152 table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
154 with temp_db_conn.cursor() as temp_db_cursor:
155 temp_db_cursor.execute('CREATE TABLE {}()'.format(table_name))
157 special_phrases_importer._grant_access_to_webuser(phrase_class, phrase_type)
159 assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, phrase_class, phrase_type)
161 def test_create_place_classtype_table_and_indexes(
162 temp_db_conn, def_config, placex_table, getorcreate_amenity_funcs,
163 getorcreate_amenityoperator_funcs, special_phrases_importer):
165 Test that _create_place_classtype_table_and_indexes()
166 create the right place_classtype tables and place_id indexes
167 and centroid indexes and grant access to the web user
168 for the given set of pairs.
170 pairs = set([('class1', 'type1'), ('class2', 'type2')])
172 special_phrases_importer._create_place_classtype_table_and_indexes(pairs)
175 assert check_table_exist(temp_db_conn, pair[0], pair[1])
176 assert check_placeid_and_centroid_indexes(temp_db_conn, pair[0], pair[1])
177 assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, pair[0], pair[1])
179 def test_process_xml_content(temp_db_conn, def_config, special_phrases_importer,
180 getorcreate_amenity_funcs, getorcreate_amenityoperator_funcs):
182 Test that _process_xml_content() process the given xml content right
183 by executing the right SQL functions for amenities and
184 by returning the right set of pairs.
186 class_test = 'aerialway'
187 type_test = 'zip_line'
189 #Converted output set to a dict for easy assert further.
190 results = dict(special_phrases_importer._process_xml_content(get_test_xml_wiki_content(), 'en'))
192 assert check_amenities_with_op(temp_db_conn)
193 assert check_amenities_without_op(temp_db_conn)
194 assert results[class_test] and type_test in results.values()
196 def test_import_from_wiki(monkeypatch, temp_db_conn, def_config, special_phrases_importer, placex_table,
197 getorcreate_amenity_funcs, getorcreate_amenityoperator_funcs):
199 Check that the main import_from_wiki() method is well executed.
200 It should create the place_classtype table, the place_id and centroid indexes,
201 grand access to the web user and executing the SQL functions for amenities.
203 monkeypatch.setattr('nominatim.tools.special_phrases.SpecialPhrasesImporter._get_wiki_content', mock_get_wiki_content)
204 special_phrases_importer.import_from_wiki(['en'])
206 class_test = 'aerialway'
207 type_test = 'zip_line'
209 assert check_table_exist(temp_db_conn, class_test, type_test)
210 assert check_placeid_and_centroid_indexes(temp_db_conn, class_test, type_test)
211 assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, class_test, type_test)
212 assert check_amenities_with_op(temp_db_conn)
213 assert check_amenities_without_op(temp_db_conn)
215 def mock_get_wiki_content(lang):
217 Mock the _get_wiki_content() method to return
218 static xml test file content.
220 return get_test_xml_wiki_content()
222 def get_test_xml_wiki_content():
224 return the content of the static xml test file.
226 xml_test_content_path = (TEST_BASE_DIR / 'testdata' / 'special_phrases_test_content.txt').resolve()
227 with open(xml_test_content_path) as xml_content_reader:
228 return xml_content_reader.read()
230 def check_table_exist(temp_db_conn, phrase_class, phrase_type):
232 Verify that the place_classtype table exists for the given
233 phrase_class and phrase_type.
235 table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
237 with temp_db_conn.cursor() as temp_db_cursor:
238 temp_db_cursor.execute("""
240 FROM information_schema.tables
241 WHERE table_type='BASE TABLE'
242 AND table_name='{}'""".format(table_name))
243 return temp_db_cursor.fetchone()
245 def check_grant_access(temp_db_conn, user, phrase_class, phrase_type):
247 Check that the web user has been granted right access to the
248 place_classtype table of the given phrase_class and phrase_type.
250 table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
252 with temp_db_conn.cursor() as temp_db_cursor:
253 temp_db_cursor.execute("""
254 SELECT * FROM information_schema.role_table_grants
255 WHERE table_name='{}'
257 AND privilege_type='SELECT'""".format(table_name, user))
258 return temp_db_cursor.fetchone()
260 def check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type):
262 Check that the place_id index and centroid index exist for the
263 place_classtype table of the given phrase_class and phrase_type.
265 index_prefix = 'idx_place_classtype_{}_{}_'.format(phrase_class, phrase_type)
268 temp_db_conn.index_exists(index_prefix + 'centroid')
270 temp_db_conn.index_exists(index_prefix + 'place_id')
273 def check_amenities_with_op(temp_db_conn):
275 Check that the test table for the SQL function getorcreate_amenityoperator()
276 contains more than one value (so that the SQL function was call more than one time).
278 with temp_db_conn.cursor() as temp_db_cursor:
279 temp_db_cursor.execute("SELECT * FROM temp_with_operator")
280 return len(temp_db_cursor.fetchall()) > 1
282 def check_amenities_without_op(temp_db_conn):
284 Check that the test table for the SQL function getorcreate_amenity()
285 contains more than one value (so that the SQL function was call more than one time).
287 with temp_db_conn.cursor() as temp_db_cursor:
288 temp_db_cursor.execute("SELECT * FROM temp_without_operator")
289 return len(temp_db_cursor.fetchall()) > 1
292 def special_phrases_importer(temp_db_conn, def_config, temp_phplib_dir_with_migration):
294 Return an instance of SpecialPhrasesImporter.
296 return SpecialPhrasesImporter(def_config, temp_phplib_dir_with_migration, temp_db_conn)
299 def temp_phplib_dir_with_migration():
301 Return temporary phpdir with migration subdirectory and
302 PhraseSettingsToJson.php script inside.
304 migration_file = (TEST_BASE_DIR / '..' / 'lib-php' / 'migration'
305 / 'PhraseSettingsToJson.php').resolve()
306 with tempfile.TemporaryDirectory() as phpdir:
307 (Path(phpdir) / 'migration').mkdir()
308 migration_dest_path = (Path(phpdir) / 'migration' / 'PhraseSettingsToJson.php').resolve()
309 copyfile(migration_file, migration_dest_path)
314 def make_strandard_name_func(temp_db_cursor):
315 temp_db_cursor.execute("""
316 CREATE OR REPLACE FUNCTION make_standard_name(name TEXT) RETURNS TEXT AS $$
318 RETURN trim(name); --Basically return only the trimed name for the tests
320 $$ LANGUAGE plpgsql IMMUTABLE;""")
323 def getorcreate_amenity_funcs(temp_db_cursor, make_strandard_name_func):
324 temp_db_cursor.execute("""
325 CREATE TABLE temp_without_operator(op TEXT);
327 CREATE OR REPLACE FUNCTION getorcreate_amenity(lookup_word TEXT, normalized_word TEXT,
328 lookup_class text, lookup_type text)
331 INSERT INTO temp_without_operator VALUES('no_operator');
333 $$ LANGUAGE plpgsql""")
336 def getorcreate_amenityoperator_funcs(temp_db_cursor, make_strandard_name_func):
337 temp_db_cursor.execute("""
338 CREATE TABLE temp_with_operator(op TEXT);
340 CREATE OR REPLACE FUNCTION getorcreate_amenityoperator(lookup_word TEXT, normalized_word TEXT,
341 lookup_class text, lookup_type text, op text)
344 INSERT INTO temp_with_operator VALUES(op);
346 $$ LANGUAGE plpgsql""")