Debian Codegraph @

test/units/parsing/test_dataloader.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import collections
21 import os
22 import pathlib
23 import tempfile
24
25 import unittest
26 from unittest.mock import patch
27
28 import pytest
29
30 from ansible.errors import AnsibleParserError, AnsibleFileNotFound
31 from ansible.parsing.vault import AnsibleVaultError
32 from ansible.module_utils.common.text.converters import to_text
33 from ansible._internal._datatag._tags import Origin, SourceWasEncrypted, TrustedAsTemplate
34
35 from units.mock.vault_helper import TextVaultSecret
36 from ansible.parsing.dataloader import DataLoader
37
38 from units.mock.path import mock_unfrackpath_noop
39 from units.test_utils.controller.display import emits_warnings
40
41
42 class TestDataLoader(unittest.TestCase):
43
44 def setUp(self):
45 self._loader = DataLoader()
46
47 @patch('os.path.exists')
48 def test__is_role(self, p_exists):
49 p_exists.side_effect = lambda p: p == 'test_path/tasks/main.yml'
50 self.assertTrue(self._loader._is_role('test_path/tasks'))
51 self.assertTrue(self._loader._is_role('test_path/'))
52
53 @patch.object(DataLoader, '_get_file_contents')
54 def test_parse_json_from_file(self, mock_def):
55 mock_def.return_value = (b"""{"a": 1, "b": 2, "c": 3}""", True)
56 output = self._loader.load_from_file('dummy_json.txt')
57 self.assertEqual(output, dict(a=1, b=2, c=3))
58
59 @patch.object(DataLoader, '_get_file_contents')
60 def test_parse_yaml_from_file(self, mock_def):
61 mock_def.return_value = (b"""
62 a: 1
63 b: 2
64 c: 3
65 """, True)
66 output = self._loader.load_from_file('dummy_yaml.txt')
67 self.assertEqual(output, dict(a=1, b=2, c=3))
68
69 @patch.object(DataLoader, '_get_file_contents')
70 def test_parse_fail_from_file(self, mock_def):
71 mock_def.return_value = (b"""
72 TEXT:
73 ***
74 NOT VALID
75 """, True)
76 self.assertRaises(AnsibleParserError, self._loader.load_from_file, 'dummy_yaml_bad.txt')
77
78 @patch('ansible.parsing.dataloader.unfrackpath', mock_unfrackpath_noop)
79 @patch.object(DataLoader, '_is_role')
80 def test_path_dwim_relative(self, mock_is_role):
81 """
82 simulate a nested dynamic include:
83
84 playbook.yml:
85 - hosts: localhost
86 roles:
87 - { role: 'testrole' }
88
89 testrole/tasks/main.yml:
90 - include_tasks: "include1.yml"
91 static: no
92
93 testrole/tasks/include1.yml:
94 - include_tasks: include2.yml
95 static: no
96
97 testrole/tasks/include2.yml:
98 - debug: msg="blah"
99 """
100 mock_is_role.return_value = False
101 with patch('os.path.exists') as mock_os_path_exists:
102 mock_os_path_exists.return_value = False
103 self._loader.path_dwim_relative('/tmp/roles/testrole/tasks', 'tasks', 'included2.yml')
104
105 # Fetch first args for every call
106 # mock_os_path_exists.assert_any_call isn't used because os.path.normpath must be used in order to compare paths
107 called_args = [os.path.normpath(to_text(call[0][0])) for call in mock_os_path_exists.call_args_list]
108
109 # 'path_dwim_relative' docstrings say 'with or without explicitly named dirname subdirs':
110 self.assertIn('/tmp/roles/testrole/tasks/included2.yml', called_args)
111 self.assertIn('/tmp/roles/testrole/tasks/tasks/included2.yml', called_args)
112
113 c = collections.Counter(called_args)
114 assert c['/tmp/roles/testrole/tasks/included2.yml'] == 1
115 assert c['/tmp/roles/testrole/tasks/tasks/included2.yml'] == 2
116
117 def test_path_dwim_root(self):
118 self.assertEqual(self._loader.path_dwim('/'), '/')
119
120 def test_path_dwim_home(self):
121 self.assertEqual(self._loader.path_dwim('~'), os.path.expanduser('~'))
122
123 def test_path_dwim_tilde_slash(self):
124 self.assertEqual(self._loader.path_dwim('~/'), os.path.expanduser('~'))
125
126 def test_get_real_file(self):
127 self.assertEqual(self._loader.get_real_file(__file__), __file__)
128
129 def test_is_file(self):
130 self.assertTrue(self._loader.is_file(__file__))
131
132 def test_is_directory_positive(self):
133 self.assertTrue(self._loader.is_directory(os.path.dirname(__file__)))
134
135 def test_get_file_contents_none_path(self):
136 with pytest.raises(TypeError, match='Invalid filename'):
137 self._loader.get_text_file_contents(None)
138
139 def test_get_file_contents_non_existent_path(self):
140 with pytest.raises(AnsibleFileNotFound):
141 self._loader.get_text_file_contents('/non_existent_file')
142
143
144 class TestPathDwimRelativeDataLoader(unittest.TestCase):
145
146 def setUp(self):
147 self._loader = DataLoader()
148
149 def test_all_slash(self):
150 self.assertEqual(self._loader.path_dwim_relative('/', '/', '/'), '/')
151
152 def test_path_endswith_role(self):
153 self.assertEqual(self._loader.path_dwim_relative(path='foo/bar/tasks/', dirname='/', source='/'), '/')
154
155 def test_path_endswith_role_main_yml(self):
156 self.assertIn('main.yml', self._loader.path_dwim_relative(path='foo/bar/tasks/', dirname='/', source='main.yml'))
157
158 def test_path_endswith_role_source_tilde(self):
159 self.assertEqual(self._loader.path_dwim_relative(path='foo/bar/tasks/', dirname='/', source='~/'), os.path.expanduser('~'))
160
161
162 class TestPathDwimRelativeStackDataLoader(unittest.TestCase):
163
164 def setUp(self):
165 self._loader = DataLoader()
166
167 def test_none(self):
168 self.assertRaisesRegex(AnsibleFileNotFound, 'on the Ansible Controller', self._loader.path_dwim_relative_stack, None, None, None)
169
170 def test_empty_strings(self):
171 self.assertEqual(self._loader.path_dwim_relative_stack('', '', ''), os.path.abspath('./') + '/')
172
173 def test_empty_lists(self):
174 self.assertEqual(self._loader.path_dwim_relative_stack([], '', '~/'), os.path.expanduser('~'))
175
176 def test_all_slash(self):
177 self.assertEqual(self._loader.path_dwim_relative_stack('/', '/', '/'), '/')
178
179 def test_path_endswith_role(self):
180 self.assertEqual(self._loader.path_dwim_relative_stack(paths=['foo/bar/tasks/'], dirname='/', source='/'), '/')
181
182 def test_path_endswith_role_source_tilde(self):
183 self.assertEqual(self._loader.path_dwim_relative_stack(paths=['foo/bar/tasks/'], dirname='/', source='~/'), os.path.expanduser('~'))
184
185 def test_path_endswith_role_source_main_yml(self):
186 self.assertRaises(AnsibleFileNotFound, self._loader.path_dwim_relative_stack, ['foo/bar/tasks/'], '/', 'main.yml')
187
188 def test_path_endswith_role_source_main_yml_source_in_dirname(self):
189 self.assertRaises(AnsibleFileNotFound, self._loader.path_dwim_relative_stack, 'foo/bar/tasks/', 'tasks', 'tasks/main.yml')
190
191
192 class TestDataLoaderWithVault(unittest.TestCase):
193
194 def setUp(self):
195 self._loader = DataLoader()
196 vault_secrets = [('default', TextVaultSecret('ansible'))]
197 self._loader.set_vault_secrets(vault_secrets)
198 self.test_vault_data_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'vault.yml')
199
200 def tearDown(self):
201 pass
202
203 def test_get_text_file_contents_vaulted_yaml(self) -> None:
204 content = self._loader.get_text_file_contents(self.test_vault_data_path)
205
206 assert SourceWasEncrypted.is_tagged_on(content)
207
208 def test_get_text_file_contents_non_vaulted_file(self) -> None:
209 content = self._loader.get_text_file_contents(__file__)
210
211 assert not SourceWasEncrypted.is_tagged_on(content)
212
213 def test_get_real_file_vault(self):
214 real_file_path = self._loader.get_real_file(self.test_vault_data_path)
215 self.assertTrue(os.path.exists(real_file_path))
216
217 def test_get_real_file_vault_no_vault(self):
218 self._loader.set_vault_secrets(None)
219 self.assertRaises(AnsibleParserError, self._loader.get_real_file, self.test_vault_data_path)
220
221 def test_get_real_file_vault_wrong_password(self):
222 wrong_vault = [('default', TextVaultSecret('wrong_password'))]
223 self._loader.set_vault_secrets(wrong_vault)
224 self.assertRaises(AnsibleVaultError, self._loader.get_real_file, self.test_vault_data_path)
225
226 def test_parse_from_vault_1_1_file(self):
227 vaulted_data = """$ANSIBLE_VAULT;1.1;AES256
228 33343734386261666161626433386662623039356366656637303939306563376130623138626165
229 6436333766346533353463636566313332623130383662340a393835656134633665333861393331
230 37666233346464636263636530626332623035633135363732623332313534306438393366323966
231 3135306561356164310a343937653834643433343734653137383339323330626437313562306630
232 3035
233 """
234
235 with tempfile.NamedTemporaryFile(mode='w') as file:
236 file.write(vaulted_data)
237 file.flush()
238 output = self._loader.load_from_file(file.name, cache='none')
239 self.assertEqual(output, dict(foo='bar'))
240
241 # no cache used
242 self.assertFalse(self._loader._FILE_CACHE)
243
244 # vault cache entry written
245 output = self._loader.load_from_file(file.name, cache='vaulted')
246 self.assertEqual(output, dict(foo='bar'))
247 self.assertTrue(self._loader._FILE_CACHE)
248
249 # cache entry used
250 key = next(iter(self._loader._FILE_CACHE.keys()))
251 modified = {'changed': True}
252 self._loader._FILE_CACHE[key] = modified
253 output = self._loader.load_from_file(file.name, cache='vaulted')
254 self.assertEqual(output, modified)
255
256
257 def test_get_text_file_contents(tmp_path: pathlib.Path) -> None:
258 original_contents = 'Hello World'
259
260 temp_file = tmp_path / 'valid.txt'
261 temp_file.write_text(original_contents)
262
263 loader = DataLoader()
264 read_contents = loader.get_text_file_contents(str(temp_file))
265
266 assert read_contents == original_contents
267
268 origin = Origin.get_tag(read_contents)
269
270 assert origin.path == str(temp_file)
271 assert origin.line_num is None
272 assert origin.col_num is None
273 assert origin.description is None
274
275
276 @pytest.mark.parametrize("content,encoding", (
277 (b'\xa4\xa4\xb0\xea\xa4H', 'utf-8'),
278 (b'\xa4\xa4\xb0\xea\xa4H', None),
279 ))
280 def test_get_text_file_contents_encoding_deprecation(content: bytes, encoding: str | None, tmp_path: pathlib.Path) -> None:
281 temp = tmp_path / 'bogus_file'
282 temp.write_bytes(content)
283
284 loader = DataLoader()
285
286 if encoding:
287 # help text will imply that encoding is settable if non-empty
288 expected_warning_pattern = f"could not be decoded as {encoding!r}.*Ensure the correct encoding was specified"
289 else:
290 expected_warning_pattern = "could not be decoded as 'utf-8'.*must be UTF-8 encoded"
291
292 with emits_warnings(deprecation_pattern=expected_warning_pattern):
293 loaded = loader.get_text_file_contents(str(temp), encoding=encoding)
294
295 assert loaded == content.decode(encoding or 'utf-8', errors='surrogateescape')
296
297 assert Origin.is_tagged_on(loaded)
298 assert not SourceWasEncrypted.is_tagged_on(loaded)
299 assert not TrustedAsTemplate.is_tagged_on(loaded)
300
301
302 @pytest.mark.parametrize("encoding", (
303 None,
304 'utf-8',
305 'big5',
306 ))
307 def test_get_text_file_contents_strict(encoding: str | None) -> None:
308 text_content = '中文'
309 content = text_content.encode(encoding or 'utf-8')
310
311 with tempfile.NamedTemporaryFile(mode='wb') as temp:
312 temp.write(content)
313 temp.flush()
314
315 loader = DataLoader()
316 loaded = loader.get_text_file_contents(temp.name, encoding=encoding)
317
318 assert loaded == text_content
319
320 assert Origin.is_tagged_on(loaded)
321 assert not SourceWasEncrypted.is_tagged_on(loaded)
322 assert not TrustedAsTemplate.is_tagged_on(loaded)