2 Tests for import special phrases methods
3 of the class SpecialPhrasesImporter.
5 from mocks import MockParamCapture
6 from nominatim.errors import UsageError
7 from pathlib import Path
9 from shutil import copyfile
11 from nominatim.tools.special_phrases import SpecialPhrasesImporter
13 TEST_BASE_DIR = Path(__file__) / '..' / '..'
15 def test_fetch_existing_words_phrases_basic(special_phrases_importer, word_table,
18 Check for the fetch_existing_words_phrases() method.
19 It should return special phrase term added to the word
22 with temp_db_conn.cursor() as temp_db_cursor:
24 INSERT INTO word VALUES(99999, 'lookup_token', 'normalized_word',
25 'class', 'type', null, 0, 'near');
27 temp_db_cursor.execute(query)
29 assert not special_phrases_importer.words_phrases_to_delete
30 special_phrases_importer._fetch_existing_words_phrases()
31 contained_phrase = special_phrases_importer.words_phrases_to_delete.pop()
32 assert contained_phrase == ('normalized_word', 'class', 'type', 'near')
34 def test_fetch_existing_words_phrases_housenumber(special_phrases_importer, word_table,
37 Check for the fetch_existing_words_phrases() method.
38 It should return nothing as the term added correspond
39 to a housenumber term.
41 with temp_db_conn.cursor() as temp_db_cursor:
43 INSERT INTO word VALUES(99999, 'lookup_token', 'normalized_word',
44 'place', 'house', null, 0, 'near');
46 temp_db_cursor.execute(query)
48 special_phrases_importer._fetch_existing_words_phrases()
49 assert not special_phrases_importer.words_phrases_to_delete
51 def test_fetch_existing_words_phrases_postcode(special_phrases_importer, word_table,
54 Check for the fetch_existing_words_phrases() method.
55 It should return nothing as the term added correspond
58 with temp_db_conn.cursor() as temp_db_cursor:
60 INSERT INTO word VALUES(99999, 'lookup_token', 'normalized_word',
61 'place', 'postcode', null, 0, 'near');
63 temp_db_cursor.execute(query)
65 special_phrases_importer._fetch_existing_words_phrases()
66 assert not special_phrases_importer.words_phrases_to_delete
68 def test_fetch_existing_place_classtype_tables(special_phrases_importer, temp_db_conn):
70 Check for the fetch_existing_place_classtype_tables() method.
71 It should return the table just created.
73 with temp_db_conn.cursor() as temp_db_cursor:
74 query = 'CREATE TABLE place_classtype_testclasstypetable()'
75 temp_db_cursor.execute(query)
77 special_phrases_importer._fetch_existing_place_classtype_tables()
78 contained_table = special_phrases_importer.table_phrases_to_delete.pop()
79 assert contained_table == 'place_classtype_testclasstypetable'
81 def test_check_sanity_class(special_phrases_importer):
83 Check for _check_sanity() method.
84 If a wrong class or type is given, an UsageError should raise.
85 If a good class and type are given, nothing special happens.
87 with pytest.raises(UsageError):
88 special_phrases_importer._check_sanity('en', '', 'type')
90 with pytest.raises(UsageError):
91 special_phrases_importer._check_sanity('en', 'class', '')
93 special_phrases_importer._check_sanity('en', 'class', 'type')
95 def test_load_white_and_black_lists(special_phrases_importer):
97 Test that _load_white_and_black_lists() well return
98 black list and white list and that they are of dict type.
100 black_list, white_list = special_phrases_importer._load_white_and_black_lists()
102 assert isinstance(black_list, dict) and isinstance(white_list, dict)
104 def test_convert_php_settings(special_phrases_importer):
106 Test that _convert_php_settings_if_needed() convert the given
107 php file to a json file.
109 php_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.php').resolve()
111 with tempfile.TemporaryDirectory() as temp_dir:
112 temp_settings = (Path(temp_dir) / 'phrase_settings.php').resolve()
113 copyfile(php_file, temp_settings)
114 special_phrases_importer._convert_php_settings_if_needed(temp_settings)
116 assert (Path(temp_dir) / 'phrase_settings.json').is_file()
118 def test_convert_settings_wrong_file(special_phrases_importer):
120 Test that _convert_php_settings_if_needed() raise an exception
121 if the given file is not a valid file.
123 with pytest.raises(UsageError, match='random_file is not a valid file.'):
124 special_phrases_importer._convert_php_settings_if_needed('random_file')
126 def test_convert_settings_json_already_exist(special_phrases_importer):
128 Test that if we give to '_convert_php_settings_if_needed' a php file path
129 and that a the corresponding json file already exists, it is returned.
131 php_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.php').resolve()
132 json_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.json').resolve()
134 returned = special_phrases_importer._convert_php_settings_if_needed(php_file)
136 assert returned == json_file
138 def test_convert_settings_giving_json(special_phrases_importer):
140 Test that if we give to '_convert_php_settings_if_needed' a json file path
141 the same path is directly returned
143 json_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.json').resolve()
145 returned = special_phrases_importer._convert_php_settings_if_needed(json_file)
147 assert returned == json_file
149 def test_process_amenity_with_operator(special_phrases_importer, getorcreate_amenityoperator_funcs,
152 Test that _process_amenity() execute well the
153 getorcreate_amenityoperator() SQL function and that
154 the 2 differents operators are well handled.
156 special_phrases_importer._process_amenity('', '', '', '', 'near')
157 special_phrases_importer._process_amenity('', '', '', '', 'in')
159 with temp_db_conn.cursor() as temp_db_cursor:
160 temp_db_cursor.execute("SELECT * FROM temp_with_operator WHERE op='near' OR op='in'")
161 results = temp_db_cursor.fetchall()
163 assert len(results) == 2
165 def test_process_amenity_without_operator(special_phrases_importer, getorcreate_amenity_funcs,
168 Test that _process_amenity() execute well the
169 getorcreate_amenity() SQL function.
171 special_phrases_importer._process_amenity('', '', '', '', '')
173 with temp_db_conn.cursor() as temp_db_cursor:
174 temp_db_cursor.execute("SELECT * FROM temp_without_operator WHERE op='no_operator'")
175 result = temp_db_cursor.fetchone()
179 def test_create_place_classtype_indexes(temp_db_conn, special_phrases_importer):
181 Test that _create_place_classtype_indexes() create the
182 place_id index and centroid index on the right place_class_type table.
184 phrase_class = 'class'
186 table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
188 with temp_db_conn.cursor() as temp_db_cursor:
189 temp_db_cursor.execute("CREATE EXTENSION postgis;")
190 temp_db_cursor.execute('CREATE TABLE {}(place_id BIGINT, centroid GEOMETRY)'.format(table_name))
192 special_phrases_importer._create_place_classtype_indexes('', phrase_class, phrase_type)
194 assert check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type)
196 def test_create_place_classtype_table(temp_db_conn, placex_table, special_phrases_importer):
198 Test that _create_place_classtype_table() create
199 the right place_classtype table.
201 phrase_class = 'class'
203 special_phrases_importer._create_place_classtype_table('', phrase_class, phrase_type)
205 assert check_table_exist(temp_db_conn, phrase_class, phrase_type)
207 def test_grant_access_to_web_user(temp_db_conn, def_config, special_phrases_importer):
209 Test that _grant_access_to_webuser() give
210 right access to the web user.
212 phrase_class = 'class'
214 table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
216 with temp_db_conn.cursor() as temp_db_cursor:
217 temp_db_cursor.execute('CREATE TABLE {}()'.format(table_name))
219 special_phrases_importer._grant_access_to_webuser(phrase_class, phrase_type)
221 assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, phrase_class, phrase_type)
223 def test_create_place_classtype_table_and_indexes(
224 temp_db_conn, def_config, placex_table, getorcreate_amenity_funcs,
225 getorcreate_amenityoperator_funcs, special_phrases_importer):
227 Test that _create_place_classtype_table_and_indexes()
228 create the right place_classtype tables and place_id indexes
229 and centroid indexes and grant access to the web user
230 for the given set of pairs.
232 pairs = set([('class1', 'type1'), ('class2', 'type2')])
234 special_phrases_importer._create_place_classtype_table_and_indexes(pairs)
237 assert check_table_exist(temp_db_conn, pair[0], pair[1])
238 assert check_placeid_and_centroid_indexes(temp_db_conn, pair[0], pair[1])
239 assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, pair[0], pair[1])
241 def test_process_xml_content(temp_db_conn, def_config, special_phrases_importer,
242 getorcreate_amenity_funcs, getorcreate_amenityoperator_funcs):
244 Test that _process_xml_content() process the given xml content right
245 by executing the right SQL functions for amenities and
246 by returning the right set of pairs.
248 class_test = 'aerialway'
249 type_test = 'zip_line'
251 #Converted output set to a dict for easy assert further.
252 results = dict(special_phrases_importer._process_xml_content(get_test_xml_wiki_content(), 'en'))
254 assert check_amenities_with_op(temp_db_conn)
255 assert check_amenities_without_op(temp_db_conn)
256 assert results[class_test] and type_test in results.values()
258 def test_remove_non_existent_phrases_from_db(special_phrases_importer, default_phrases,
261 Check for the remove_non_existent_phrases_from_db() method.
263 It should removed entries from the word table which are contained
264 in the words_phrases_to_delete set and not those also contained
265 in the words_phrases_still_exist set.
267 place_classtype tables contained in table_phrases_to_delete should
270 with temp_db_conn.cursor() as temp_db_cursor:
271 to_delete_phrase_tuple = ('normalized_word', 'class', 'type', 'near')
272 to_keep_phrase_tuple = (
273 'normalized_word_exists', 'class_exists', 'type_exists', 'near'
275 special_phrases_importer.words_phrases_to_delete = {
276 to_delete_phrase_tuple,
279 special_phrases_importer.words_phrases_still_exist = {
282 special_phrases_importer.table_phrases_to_delete = {
283 'place_classtype_testclasstypetable_to_delete'
286 query_words = 'SELECT word, class, type, operator FROM word;'
289 FROM information_schema.tables
290 WHERE table_schema='public'
291 AND table_name like 'place_classtype_%';
294 special_phrases_importer._remove_non_existent_phrases_from_db()
296 temp_db_cursor.execute(query_words)
297 words_result = temp_db_cursor.fetchall()
298 temp_db_cursor.execute(query_tables)
299 tables_result = temp_db_cursor.fetchall()
300 assert len(words_result) == 1 and words_result[0] == [
301 'normalized_word_exists', 'class_exists', 'type_exists', 'near'
303 assert (len(tables_result) == 1 and
304 tables_result[0][0] == 'place_classtype_testclasstypetable_to_keep'
307 def test_import_from_wiki(monkeypatch, temp_db_conn, def_config, special_phrases_importer, placex_table,
308 getorcreate_amenity_funcs, getorcreate_amenityoperator_funcs, word_table):
310 Check that the main import_from_wiki() method is well executed.
311 It should create the place_classtype table, the place_id and centroid indexes,
312 grand access to the web user and executing the SQL functions for amenities.
314 mock_fetch_existing_words_phrases = MockParamCapture()
315 mock_fetch_existing_place_classtype_tables = MockParamCapture()
316 mock_remove_non_existent_phrases_from_db = MockParamCapture()
318 monkeypatch.setattr('nominatim.tools.special_phrases.SpecialPhrasesImporter._fetch_existing_words_phrases',
319 mock_fetch_existing_words_phrases)
320 monkeypatch.setattr('nominatim.tools.special_phrases.SpecialPhrasesImporter._fetch_existing_place_classtype_tables',
321 mock_fetch_existing_place_classtype_tables)
322 monkeypatch.setattr('nominatim.tools.special_phrases.SpecialPhrasesImporter._remove_non_existent_phrases_from_db',
323 mock_remove_non_existent_phrases_from_db)
324 monkeypatch.setattr('nominatim.tools.special_phrases.SpecialPhrasesImporter._get_wiki_content', mock_get_wiki_content)
325 special_phrases_importer.import_from_wiki(['en'])
327 class_test = 'aerialway'
328 type_test = 'zip_line'
330 assert check_table_exist(temp_db_conn, class_test, type_test)
331 assert check_placeid_and_centroid_indexes(temp_db_conn, class_test, type_test)
332 assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, class_test, type_test)
333 assert check_amenities_with_op(temp_db_conn)
334 assert check_amenities_without_op(temp_db_conn)
335 assert mock_fetch_existing_words_phrases.called == 1
336 assert mock_fetch_existing_place_classtype_tables.called == 1
337 assert mock_remove_non_existent_phrases_from_db.called == 1
339 def mock_get_wiki_content(lang):
341 Mock the _get_wiki_content() method to return
342 static xml test file content.
344 return get_test_xml_wiki_content()
346 def get_test_xml_wiki_content():
348 return the content of the static xml test file.
350 xml_test_content_path = (TEST_BASE_DIR / 'testdata' / 'special_phrases_test_content.txt').resolve()
351 with open(xml_test_content_path) as xml_content_reader:
352 return xml_content_reader.read()
354 def check_table_exist(temp_db_conn, phrase_class, phrase_type):
356 Verify that the place_classtype table exists for the given
357 phrase_class and phrase_type.
359 table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
361 with temp_db_conn.cursor() as temp_db_cursor:
362 temp_db_cursor.execute("""
364 FROM information_schema.tables
365 WHERE table_type='BASE TABLE'
366 AND table_name='{}'""".format(table_name))
367 return temp_db_cursor.fetchone()
369 def check_grant_access(temp_db_conn, user, phrase_class, phrase_type):
371 Check that the web user has been granted right access to the
372 place_classtype table of the given phrase_class and phrase_type.
374 table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
376 with temp_db_conn.cursor() as temp_db_cursor:
377 temp_db_cursor.execute("""
378 SELECT * FROM information_schema.role_table_grants
379 WHERE table_name='{}'
381 AND privilege_type='SELECT'""".format(table_name, user))
382 return temp_db_cursor.fetchone()
384 def check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type):
386 Check that the place_id index and centroid index exist for the
387 place_classtype table of the given phrase_class and phrase_type.
389 index_prefix = 'idx_place_classtype_{}_{}_'.format(phrase_class, phrase_type)
392 temp_db_conn.index_exists(index_prefix + 'centroid')
394 temp_db_conn.index_exists(index_prefix + 'place_id')
397 def check_amenities_with_op(temp_db_conn):
399 Check that the test table for the SQL function getorcreate_amenityoperator()
400 contains more than one value (so that the SQL function was call more than one time).
402 with temp_db_conn.cursor() as temp_db_cursor:
403 temp_db_cursor.execute("SELECT * FROM temp_with_operator")
404 return len(temp_db_cursor.fetchall()) > 1
406 def check_amenities_without_op(temp_db_conn):
408 Check that the test table for the SQL function getorcreate_amenity()
409 contains more than one value (so that the SQL function was call more than one time).
411 with temp_db_conn.cursor() as temp_db_cursor:
412 temp_db_cursor.execute("SELECT * FROM temp_without_operator")
413 return len(temp_db_cursor.fetchall()) > 1
416 def special_phrases_importer(temp_db_conn, def_config, temp_phplib_dir_with_migration):
418 Return an instance of SpecialPhrasesImporter.
420 return SpecialPhrasesImporter(def_config, temp_phplib_dir_with_migration, temp_db_conn)
423 def temp_phplib_dir_with_migration():
425 Return temporary phpdir with migration subdirectory and
426 PhraseSettingsToJson.php script inside.
428 migration_file = (TEST_BASE_DIR / '..' / 'lib-php' / 'migration'
429 / 'PhraseSettingsToJson.php').resolve()
430 with tempfile.TemporaryDirectory() as phpdir:
431 (Path(phpdir) / 'migration').mkdir()
432 migration_dest_path = (Path(phpdir) / 'migration' / 'PhraseSettingsToJson.php').resolve()
433 copyfile(migration_file, migration_dest_path)
438 def default_phrases(word_table, temp_db_cursor):
439 temp_db_cursor.execute("""
440 INSERT INTO word VALUES(99999, 'lookup_token', 'normalized_word',
441 'class', 'type', null, 0, 'near');
443 INSERT INTO word VALUES(99999, 'lookup_token', 'normalized_word_exists',
444 'class_exists', 'type_exists', null, 0, 'near');
446 CREATE TABLE place_classtype_testclasstypetable_to_delete();
447 CREATE TABLE place_classtype_testclasstypetable_to_keep();""")
450 def make_strandard_name_func(temp_db_cursor):
451 temp_db_cursor.execute("""
452 CREATE OR REPLACE FUNCTION make_standard_name(name TEXT) RETURNS TEXT AS $$
454 RETURN trim(name); --Basically return only the trimed name for the tests
456 $$ LANGUAGE plpgsql IMMUTABLE;""")
459 def getorcreate_amenity_funcs(temp_db_cursor, make_strandard_name_func):
460 temp_db_cursor.execute("""
461 CREATE TABLE temp_without_operator(op TEXT);
463 CREATE OR REPLACE FUNCTION getorcreate_amenity(lookup_word TEXT, normalized_word TEXT,
464 lookup_class text, lookup_type text)
467 INSERT INTO temp_without_operator VALUES('no_operator');
469 $$ LANGUAGE plpgsql""")
472 def getorcreate_amenityoperator_funcs(temp_db_cursor, make_strandard_name_func):
473 temp_db_cursor.execute("""
474 CREATE TABLE temp_with_operator(op TEXT);
476 CREATE OR REPLACE FUNCTION getorcreate_amenityoperator(lookup_word TEXT, normalized_word TEXT,
477 lookup_class text, lookup_type text, op text)
480 INSERT INTO temp_with_operator VALUES(op);
482 $$ LANGUAGE plpgsql""")