]> git.openstreetmap.org Git - nominatim.git/blob - test/python/test_tools_import_special_phrases.py
b77ae10dc1233f0ede3a3535a2924a22b89251db
[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):
21         special_phrases_importer._check_sanity('en', '', 'type')
22     
23     with pytest.raises(UsageError):
24         special_phrases_importer._check_sanity('en', 'class', '')
25
26     special_phrases_importer._check_sanity('en', 'class', 'type')
27
28 def test_load_white_and_black_lists(special_phrases_importer):
29     """
30         Test that _load_white_and_black_lists() well return
31         black list and white list and that they are of dict type.
32     """
33     black_list, white_list = special_phrases_importer._load_white_and_black_lists()
34
35     assert isinstance(black_list, dict) and isinstance(white_list, dict)
36
37 def test_convert_php_settings(special_phrases_importer):
38     """
39         Test that _convert_php_settings_if_needed() convert the given
40         php file to a json file.
41     """
42     php_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.php').resolve()
43
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)
48
49         assert (Path(temp_dir) / 'phrase_settings.json').is_file()
50
51 def test_convert_settings_wrong_file(special_phrases_importer):
52     """
53         Test that _convert_php_settings_if_needed() raise an exception
54         if the given file is not a valid file.
55     """
56     with pytest.raises(UsageError, match='random_file is not a valid file.'):
57         special_phrases_importer._convert_php_settings_if_needed('random_file')
58
59 def test_convert_settings_json_already_exist(special_phrases_importer):
60     """
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.
63     """
64     php_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.php').resolve()
65     json_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.json').resolve()
66
67     returned = special_phrases_importer._convert_php_settings_if_needed(php_file)
68
69     assert returned == json_file
70
71 def test_convert_settings_giving_json(special_phrases_importer):
72     """
73         Test that if we give to '_convert_php_settings_if_needed' a json file path
74         the same path is directly returned
75     """
76     json_file = (TEST_BASE_DIR / 'testfiles' / 'phrase_settings.json').resolve()
77     
78     returned = special_phrases_importer._convert_php_settings_if_needed(json_file)
79
80     assert returned == json_file
81
82 def test_process_amenity_with_operator(special_phrases_importer, getorcreate_amenityoperator_funcs,
83                                        word_table, temp_db_conn):
84     """
85         Test that _process_amenity() execute well the 
86         getorcreate_amenityoperator() SQL function and that
87         the 2 differents operators are well handled.
88     """
89     special_phrases_importer._process_amenity('', '', '', '', 'near')
90     special_phrases_importer._process_amenity('', '', '', '', 'in')
91
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()
95
96     assert len(results) == 2
97
98 def test_process_amenity_without_operator(special_phrases_importer, getorcreate_amenity_funcs,
99                                           temp_db_conn):
100     """
101         Test that _process_amenity() execute well the
102         getorcreate_amenity() SQL function.
103     """
104     special_phrases_importer._process_amenity('', '', '', '', '')
105
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()
109
110     assert result
111
112 def test_create_place_classtype_indexes(temp_db_conn, special_phrases_importer):
113     """
114         Test that _create_place_classtype_indexes() create the
115         place_id index and centroid index on the right place_class_type table.
116     """
117     phrase_class = 'class'
118     phrase_type = 'type'
119     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
120
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))
124
125     special_phrases_importer._create_place_classtype_indexes('', phrase_class, phrase_type)
126
127     assert check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type)
128
129 def test_create_place_classtype_table(temp_db_conn, placex_table, special_phrases_importer):
130     """
131         Test that _create_place_classtype_table() create
132         the right place_classtype table.
133     """
134     phrase_class = 'class'
135     phrase_type = 'type'
136     special_phrases_importer._create_place_classtype_table('', phrase_class, phrase_type)
137
138     assert check_table_exist(temp_db_conn, phrase_class, phrase_type)
139
140 def test_grant_access_to_web_user(temp_db_conn, def_config, special_phrases_importer):
141     """
142         Test that _grant_access_to_webuser() give 
143         right access to the web user.
144     """
145     phrase_class = 'class'
146     phrase_type = 'type'
147     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
148
149     with temp_db_conn.cursor() as temp_db_cursor:
150         temp_db_cursor.execute('CREATE TABLE {}()'.format(table_name))
151
152     special_phrases_importer._grant_access_to_webuser(phrase_class, phrase_type)
153
154     assert check_grant_access(temp_db_conn, def_config.DATABASE_WEBUSER, phrase_class, phrase_type)
155
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):
159     """
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.
164     """
165     pairs = set([('class1', 'type1'), ('class2', 'type2')])
166
167     special_phrases_importer._create_place_classtype_table_and_indexes(pairs)
168
169     for pair in 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])
173
174 def test_process_xml_content(temp_db_conn, def_config, special_phrases_importer, 
175                              getorcreate_amenity_funcs, getorcreate_amenityoperator_funcs):
176     """
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.
180     """
181     class_test = 'aerialway'
182     type_test = 'zip_line'
183
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'))
186
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()
190
191 def test_import_from_wiki(monkeypatch, temp_db_conn, def_config, special_phrases_importer, placex_table, 
192                           getorcreate_amenity_funcs, getorcreate_amenityoperator_funcs):
193     """
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.
197     """
198     monkeypatch.setattr('nominatim.tools.special_phrases.SpecialPhrasesImporter._get_wiki_content', mock_get_wiki_content)
199     special_phrases_importer.import_from_wiki(['en'])
200
201     class_test = 'aerialway'
202     type_test = 'zip_line'
203
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)
209
210 def mock_get_wiki_content(lang):
211     """
212         Mock the _get_wiki_content() method to return
213         static xml test file content.
214     """
215     return get_test_xml_wiki_content()
216
217 def get_test_xml_wiki_content():
218     """
219         return the content of the static xml test file.
220     """
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()
224
225 def check_table_exist(temp_db_conn, phrase_class, phrase_type):
226     """
227         Verify that the place_classtype table exists for the given
228         phrase_class and phrase_type.
229     """
230     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
231
232     with temp_db_conn.cursor() as temp_db_cursor:
233         temp_db_cursor.execute("""
234             SELECT *
235             FROM information_schema.tables
236             WHERE table_type='BASE TABLE'
237             AND table_name='{}'""".format(table_name))
238         return temp_db_cursor.fetchone()
239
240 def check_grant_access(temp_db_conn, user, phrase_class, phrase_type):
241     """
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.
244     """
245     table_name = 'place_classtype_{}_{}'.format(phrase_class, phrase_type)
246
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='{}'
251                 AND grantee='{}'
252                 AND privilege_type='SELECT'""".format(table_name, user))
253         return temp_db_cursor.fetchone()
254
255 def check_placeid_and_centroid_indexes(temp_db_conn, phrase_class, phrase_type):
256     """
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.
259     """
260     index_prefix = 'idx_place_classtype_{}_{}_'.format(phrase_class, phrase_type)
261
262     return (
263         temp_db_conn.index_exists(index_prefix + 'centroid')
264         and
265         temp_db_conn.index_exists(index_prefix + 'place_id')
266     )
267
268 def check_amenities_with_op(temp_db_conn):
269     """
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).
272     """
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
276
277 def check_amenities_without_op(temp_db_conn):
278     """
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).
281     """
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
285
286 @pytest.fixture
287 def special_phrases_importer(temp_db_conn, def_config, temp_phplib_dir_with_migration):
288     """
289         Return an instance of SpecialPhrasesImporter.
290     """
291     return SpecialPhrasesImporter(def_config, temp_phplib_dir_with_migration, temp_db_conn)
292
293 @pytest.fixture
294 def temp_phplib_dir_with_migration():
295     """
296         Return temporary phpdir with migration subdirectory and
297         PhraseSettingsToJson.php script inside.
298     """
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)
305
306         yield Path(phpdir)
307
308 @pytest.fixture
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 $$
312         BEGIN
313         RETURN trim(name); --Basically return only the trimed name for the tests
314         END;
315         $$ LANGUAGE plpgsql IMMUTABLE;""")
316         
317 @pytest.fixture
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);
321     
322         CREATE OR REPLACE FUNCTION getorcreate_amenity(lookup_word TEXT, normalized_word TEXT,
323                                                     lookup_class text, lookup_type text)
324         RETURNS void as $$
325         BEGIN
326             INSERT INTO temp_without_operator VALUES('no_operator');
327         END;
328         $$ LANGUAGE plpgsql""")
329
330 @pytest.fixture
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);
334
335         CREATE OR REPLACE FUNCTION getorcreate_amenityoperator(lookup_word TEXT, normalized_word TEXT,
336                                                     lookup_class text, lookup_type text, op text)
337         RETURNS void as $$
338         BEGIN 
339             INSERT INTO temp_with_operator VALUES(op);
340         END;
341         $$ LANGUAGE plpgsql""")