]> git.openstreetmap.org Git - nominatim.git/blob - test/python/test_tools_import_special_phrases.py
7a8b832d6b2e84ac3e9ba4838062a34a6c3fae67
[nominatim.git] / test / python / test_tools_import_special_phrases.py
1 """
2     Tests for import special phrases methods
3     of the class SpecialPhrasesImporter.
4 """
5 from nominatim.errors import UsageError
6 from pathlib import Path
7 import tempfile
8 from shutil import copyfile
9 import pytest
10 from nominatim.tools.special_phrases import SpecialPhrasesImporter
11
12 TEST_BASE_DIR = Path(__file__) / '..' / '..'
13
14 def test_check_sanity_class(special_phrases_importer):
15     """
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.
19     """
20     with pytest.raises(UsageError) as wrong_class:
21         special_phrases_importer._check_sanity('en', '', 'type')
22     
23     with pytest.raises(UsageError) as wrong_type:
24         special_phrases_importer._check_sanity('en', 'class', '')
25
26     special_phrases_importer._check_sanity('en', 'class', 'type')
27
28     assert wrong_class and wrong_type
29
30 def test_load_white_and_black_lists(special_phrases_importer):
31     """
32         Test that _load_white_and_black_lists() well return
33         black list and white list and that they are of dict type.
34     """
35     black_list, white_list = special_phrases_importer._load_white_and_black_lists()
36
37     assert isinstance(black_list, dict) and isinstance(white_list, dict)
38
39 def test_convert_php_settings(special_phrases_importer):
40     """
41         Test that _convert_php_settings_if_needed() convert the given
42         php file to a json file.
43     """
44     php_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.php').resolve()
45
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)
50
51         assert (Path(temp_dir) / 'phrase_settings.json').is_file()
52
53 def test_convert_settings_wrong_file(special_phrases_importer):
54     """
55         Test that _convert_php_settings_if_needed() raise an exception
56         if the given file is not a valid file.
57     """
58
59     with pytest.raises(UsageError) as exceptioninfos:
60         special_phrases_importer._convert_php_settings_if_needed('random_file')
61
62     assert str(exceptioninfos.value) == 'random_file is not a valid file.'
63
64 def test_convert_settings_json_already_exist(special_phrases_importer):
65     """
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.
68     """
69     php_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.php').resolve()
70     json_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.json').resolve()
71
72     returned = special_phrases_importer._convert_php_settings_if_needed(php_file)
73
74     assert returned == json_file
75
76 def test_convert_settings_giving_json(special_phrases_importer):
77     """
78         Test that if we give to '_convert_php_settings_if_needed' a json file path
79         the same path is directly returned
80     """
81     json_file = (TEST_BASE_DIR / 'testfiles' / 'phrase-settings.json').resolve()
82     
83     returned = special_phrases_importer._convert_php_settings_if_needed(json_file)
84
85     assert returned == json_file
86
87 def test_process_amenity_with_operator(special_phrases_importer, getorcreate_amenityoperator_funcs,
88                                        word_table, temp_db_conn):
89     """
90         Test that _process_amenity() execute well the 
91         getorcreate_amenityoperator() SQL function and that
92         the 2 differents operators are well handled.
93     """
94     special_phrases_importer._process_amenity('', '', '', '', 'near')
95     special_phrases_importer._process_amenity('', '', '', '', 'in')
96
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()
100
101     assert len(results) == 2
102
103 def test_process_amenity_without_operator(special_phrases_importer, getorcreate_amenity_funcs,
104                                           temp_db_conn):
105     """
106         Test that _process_amenity() execute well the
107         getorcreate_amenity() SQL function.
108     """
109     special_phrases_importer._process_amenity('', '', '', '', '')
110
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()
114
115     assert result
116
117 def test_create_place_classtype_indexes(temp_db_conn, special_phrases_importer):
118     """
119         Test that _create_place_classtype_indexes() create the
120         place_id index and centroid index on the right place_class_type table.
121     """
122     phrase_class = 'class'
123     phrase_type = 'type'
124     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
125
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))
129
130     special_phrases_importer._create_place_classtype_indexes('', phrase_class, phrase_type)
131
132     assert check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type)
133
134 def test_create_place_classtype_table(temp_db_conn, placex_table, special_phrases_importer):
135     """
136         Test that _create_place_classtype_table() create
137         the right place_classtype table.
138     """
139     phrase_class = 'class'
140     phrase_type = 'type'
141     special_phrases_importer._create_place_classtype_table('', phrase_class, phrase_type)
142
143     assert check_table_exist(temp_db_conn, phrase_class, phrase_type)
144
145 def test_grant_access_to_web_user(temp_db_conn, def_config, special_phrases_importer):
146     """
147         Test that _grant_access_to_webuser() give 
148         right access to the web user.
149     """
150     phrase_class = 'class'
151     phrase_type = 'type'
152     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
153
154     with temp_db_conn.cursor() as temp_db_cursor:
155         temp_db_cursor.execute('CREATE TABLE {}()'.format(table_name))
156
157     special_phrases_importer._grant_access_to_webuser(phrase_class, phrase_type)
158
159     assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, phrase_class, phrase_type)
160
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):
164     """
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.
169     """
170     pairs = set([('class1', 'type1'), ('class2', 'type2')])
171
172     special_phrases_importer._create_place_classtype_table_and_indexes(pairs)
173
174     for pair in 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])
178
179 def test_process_xml_content(temp_db_conn, def_config, special_phrases_importer, 
180                              getorcreate_amenity_funcs, getorcreate_amenityoperator_funcs):
181     """
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.
185     """
186     class_test = 'aerialway'
187     type_test = 'zip_line'
188
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'))
191
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()
195
196 def test_import_from_wiki(monkeypatch, temp_db_conn, def_config, special_phrases_importer, placex_table, 
197                           getorcreate_amenity_funcs, getorcreate_amenityoperator_funcs):
198     """
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.
202     """
203     monkeypatch.setattr('nominatim.tools.special_phrases.SpecialPhrasesImporter._get_wiki_content', mock_get_wiki_content)
204     special_phrases_importer.import_from_wiki(['en'])
205
206     class_test = 'aerialway'
207     type_test = 'zip_line'
208
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)
214
215 def mock_get_wiki_content(lang):
216     """
217         Mock the _get_wiki_content() method to return
218         static xml test file content.
219     """
220     return get_test_xml_wiki_content()
221
222 def get_test_xml_wiki_content():
223     """
224         return the content of the static xml test file.
225     """
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()
229
230 def check_table_exist(temp_db_conn, phrase_class, phrase_type):
231     """
232         Verify that the place_classtype table exists for the given
233         phrase_class and phrase_type.
234     """
235     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
236
237     with temp_db_conn.cursor() as temp_db_cursor:
238         temp_db_cursor.execute("""
239             SELECT *
240             FROM information_schema.tables
241             WHERE table_type='BASE TABLE'
242             AND table_name='{}'""".format(table_name))
243         return temp_db_cursor.fetchone()
244
245 def check_grant_access(temp_db_conn, user, phrase_class, phrase_type):
246     """
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.
249     """
250     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
251
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='{}'
256                 AND grantee='{}'
257                 AND privilege_type='SELECT'""".format(table_name, user))
258         return temp_db_cursor.fetchone()
259
260 def check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type):
261     """
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.
264     """
265     index_prefix = 'idx_place_classtype_{}_{}_'.format(phrase_class, phrase_type)
266
267     return (
268         temp_db_conn.index_exists(index_prefix + 'centroid')
269         and
270         temp_db_conn.index_exists(index_prefix + 'place_id')
271     )
272
273 def check_amenities_with_op(temp_db_conn):
274     """
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).
277     """
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
281
282 def check_amenities_without_op(temp_db_conn):
283     """
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).
286     """
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
290
291 @pytest.fixture
292 def special_phrases_importer(temp_db_conn, def_config, temp_phplib_dir_with_migration):
293     """
294         Return an instance of SpecialPhrasesImporter.
295     """
296     return SpecialPhrasesImporter(def_config, temp_phplib_dir_with_migration, temp_db_conn)
297
298 @pytest.fixture
299 def temp_phplib_dir_with_migration():
300     """
301         Return temporary phpdir with migration subdirectory and
302         PhraseSettingsToJson.php script inside.
303     """
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)
310
311         yield Path(phpdir)
312
313 @pytest.fixture
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 $$
317         BEGIN
318         RETURN trim(name); --Basically return only the trimed name for the tests
319         END;
320         $$ LANGUAGE plpgsql IMMUTABLE;""")
321         
322 @pytest.fixture
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);
326     
327         CREATE OR REPLACE FUNCTION getorcreate_amenity(lookup_word TEXT, normalized_word TEXT,
328                                                     lookup_class text, lookup_type text)
329         RETURNS void as $$
330         BEGIN
331             INSERT INTO temp_without_operator VALUES('no_operator');
332         END;
333         $$ LANGUAGE plpgsql""")
334
335 @pytest.fixture
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);
339
340         CREATE OR REPLACE FUNCTION getorcreate_amenityoperator(lookup_word TEXT, normalized_word TEXT,
341                                                     lookup_class text, lookup_type text, op text)
342         RETURNS void as $$
343         BEGIN 
344             INSERT INTO temp_with_operator VALUES(op);
345         END;
346         $$ LANGUAGE plpgsql""")