Debian Codegraph @

test/units/modules/test_mount_facts.py

raw
1 # Copyright: Contributors to the Ansible project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3 from __future__ import annotations
4
5 from ansible.module_utils.basic import AnsibleModule
6 from ansible.modules import mount_facts
7 from units.modules.utils import (
8 AnsibleExitJson,
9 AnsibleFailJson,
10 exit_json,
11 fail_json,
12 )
13 from units.modules.mount_facts_data import aix7_2, freebsd14_1, openbsd6_4, rhel9_4, solaris11_2
14
15 from dataclasses import astuple
16 from unittest.mock import MagicMock
17
18 import pytest
19 import time
20
21
22 @pytest.fixture
23 def get_mock_module(set_module_args):
24 def get_mock_module(invocation):
25 set_module_args(invocation)
26 module = AnsibleModule(
27 argument_spec=mount_facts.get_argument_spec(),
28 supports_check_mode=True,
29 )
30 return module
31
32 yield get_mock_module
33
34
35 def mock_callable(return_value=None):
36 def func(*args, **kwargs):
37 return return_value
38
39 return func
40
41
42 @pytest.fixture
43 def set_file_content(monkeypatch):
44 def _set_file_content(data):
45 def mock_get_file_content(filename, default=None):
46 if filename in data:
47 return data[filename]
48 return default
49 monkeypatch.setattr(mount_facts, "get_file_content", mock_get_file_content)
50 return _set_file_content
51
52
53 def test_invocation(monkeypatch, set_file_content, set_module_args):
54 set_file_content({})
55 set_module_args({})
56 monkeypatch.setattr(mount_facts, "run_mount_bin", mock_callable(return_value=""))
57 monkeypatch.setattr(AnsibleModule, "exit_json", exit_json)
58 with pytest.raises(AnsibleExitJson, match="{'ansible_facts': {'mount_points': {}, 'aggregate_mounts': \\[\\]}}"):
59 mount_facts.main()
60
61
62 def test_invalid_timeout(monkeypatch, set_module_args):
63 set_module_args({"timeout": 0})
64 monkeypatch.setattr(AnsibleModule, "fail_json", fail_json)
65 with pytest.raises(AnsibleFailJson, match="argument 'timeout' must be a positive number or null"):
66 mount_facts.main()
67
68
69 @pytest.mark.parametrize("invalid_binary, error", [
70 ("ansible_test_missing_binary", 'Failed to find required executable "ansible_test_missing_binary" in paths: .*'),
71 ("false", "Failed to execute .*false: Command '[^']*false' returned non-zero exit status 1"),
72 (["one", "two"], "argument 'mount_binary' must be a string or null, not \\['one', 'two'\\]"),
73 ])
74 def test_invalid_mount_binary(monkeypatch, set_file_content, invalid_binary, error, set_module_args):
75 set_file_content({})
76 set_module_args({"mount_binary": invalid_binary})
77 monkeypatch.setattr(AnsibleModule, "fail_json", fail_json)
78 with pytest.raises(AnsibleFailJson, match=error):
79 mount_facts.main()
80
81
82 def test_invalid_source(monkeypatch, set_module_args):
83 set_module_args({"sources": [""]})
84 monkeypatch.setattr(AnsibleModule, "fail_json", fail_json)
85 with pytest.raises(AnsibleFailJson, match="sources contains an empty string"):
86 mount_facts.main()
87
88
89 def test_duplicate_source(monkeypatch, set_file_content, get_mock_module):
90 set_file_content({"/etc/fstab": rhel9_4.fstab})
91 mock_warn = MagicMock()
92 monkeypatch.setattr(AnsibleModule, "warn", mock_warn)
93
94 user_sources = ["static", "/etc/fstab"]
95 resolved_sources = ["/etc/fstab", "/etc/vfstab", "/etc/filesystems", "/etc/fstab"]
96 expected_warning = "mount_facts option 'sources' contains duplicate entries, repeat sources will be ignored:"
97
98 module = get_mock_module({"sources": user_sources})
99 list(mount_facts.gen_mounts_by_source(module))
100 assert mock_warn.called
101 assert len(mock_warn.call_args_list) == 1
102 assert mock_warn.call_args_list[0].args == (f"{expected_warning} {resolved_sources}",)
103
104
105 @pytest.mark.parametrize("function, data, expected_result_data", [
106 ("gen_fstab_entries", rhel9_4.fstab, rhel9_4.fstab_parsed),
107 ("gen_fstab_entries", rhel9_4.mtab, rhel9_4.mtab_parsed),
108 ("gen_fstab_entries", freebsd14_1.fstab, freebsd14_1.fstab_parsed),
109 ("gen_vfstab_entries", solaris11_2.vfstab, solaris11_2.vfstab_parsed),
110 ("gen_mnttab_entries", solaris11_2.mnttab, solaris11_2.mnttab_parsed),
111 ("gen_aix_filesystems_entries", aix7_2.filesystems, aix7_2.filesystems_parsed),
112 ])
113 def test_list_mounts(function, data, expected_result_data):
114 function = getattr(mount_facts, function)
115 result = [astuple(mount_info) for mount_info in function(data.splitlines())]
116 assert result == [(_mnt, _line, _info) for _src, _mnt, _line, _info in expected_result_data]
117
118
119 def test_etc_filesystems_linux(set_file_content, get_mock_module):
120 not_aix_data = (
121 "ext4\next3\next2\nnodev proc\nnodev devpts\niso9770\nvfat\nhfs\nhfsplus\n*"
122 )
123 set_file_content({"/etc/filesystems": not_aix_data})
124 module = get_mock_module({"sources": ["/etc/filesystems"]})
125 assert list(mount_facts.gen_mounts_by_source(module)) == []
126
127
128 @pytest.mark.parametrize("mount_stdout, expected_result_data", [
129 (rhel9_4.mount, rhel9_4.mount_parsed),
130 (freebsd14_1.mount, freebsd14_1.mount_parsed),
131 (openbsd6_4.mount, openbsd6_4.mount_parsed),
132 (aix7_2.mount, aix7_2.mount_parsed),
133 ])
134 def test_parse_mount_bin_stdout(mount_stdout, expected_result_data):
135 expected_result = [(_mnt, _line, _info) for _src, _mnt, _line, _info in expected_result_data]
136 result = [astuple(mount_info) for mount_info in mount_facts.gen_mounts_from_stdout(mount_stdout)]
137 assert result == expected_result
138
139
140 def test_parse_mount_bin_stdout_unknown(monkeypatch, set_file_content, set_module_args):
141 set_file_content({})
142 set_module_args({})
143 monkeypatch.setattr(mount_facts, "run_mount_bin", mock_callable(return_value="nonsense"))
144 monkeypatch.setattr(AnsibleModule, "exit_json", exit_json)
145 with pytest.raises(AnsibleExitJson, match="{'ansible_facts': {'mount_points': {}, 'aggregate_mounts': \\[\\]}}"):
146 mount_facts.main()
147
148
149 rhel_mock_fs = {"/etc/fstab": rhel9_4.fstab, "/etc/mtab": rhel9_4.mtab}
150 freebsd_mock_fs = {"/etc/fstab": freebsd14_1.fstab}
151 aix_mock_fs = {"/etc/filesystems": aix7_2.filesystems}
152 openbsd_mock_fs = {"/etc/fstab": openbsd6_4.fstab}
153 solaris_mock_fs = {"/etc/mnttab": solaris11_2.mnttab, "/etc/vfstab": solaris11_2.vfstab}
154
155
156 @pytest.mark.parametrize("sources, file_data, mount_data, results", [
157 (["static"], rhel_mock_fs, rhel9_4.mount, rhel9_4.fstab_parsed),
158 (["/etc/fstab"], rhel_mock_fs, rhel9_4.mount, rhel9_4.fstab_parsed),
159 (["dynamic"], rhel_mock_fs, rhel9_4.mount, rhel9_4.mtab_parsed),
160 (["/etc/mtab"], rhel_mock_fs, rhel9_4.mount, rhel9_4.mtab_parsed),
161 (["all"], rhel_mock_fs, rhel9_4.mount, rhel9_4.mtab_parsed + rhel9_4.fstab_parsed),
162 (["mount"], rhel_mock_fs, rhel9_4.mount, rhel9_4.mount_parsed),
163 (["all"], freebsd_mock_fs, freebsd14_1.mount, freebsd14_1.fstab_parsed + freebsd14_1.mount_parsed),
164 (["static"], freebsd_mock_fs, freebsd14_1.mount, freebsd14_1.fstab_parsed),
165 (["dynamic"], freebsd_mock_fs, freebsd14_1.mount, freebsd14_1.mount_parsed),
166 (["mount"], freebsd_mock_fs, freebsd14_1.mount, freebsd14_1.mount_parsed),
167 (["all"], aix_mock_fs, aix7_2.mount, aix7_2.filesystems_parsed + aix7_2.mount_parsed),
168 (["all"], openbsd_mock_fs, openbsd6_4.mount, openbsd6_4.fstab_parsed + openbsd6_4.mount_parsed),
169 (["all"], solaris_mock_fs, "", solaris11_2.mnttab_parsed + solaris11_2.vfstab_parsed),
170 ])
171 def test_gen_mounts_by_sources(monkeypatch, set_file_content, sources, file_data, mount_data, results, get_mock_module):
172 set_file_content(file_data)
173 mock_run_mount = mock_callable(return_value=mount_data)
174 monkeypatch.setattr(mount_facts, "run_mount_bin", mock_run_mount)
175 module = get_mock_module({"sources": sources})
176 actual_results = list(mount_facts.gen_mounts_by_source(module))
177 assert actual_results == results
178
179
180 @pytest.mark.parametrize("on_timeout, should_warn, should_raise", [
181 (None, False, True),
182 ("warn", True, False),
183 ("ignore", False, False),
184 ])
185 def test_gen_mounts_by_source_timeout(monkeypatch, set_file_content, on_timeout, should_warn, should_raise, get_mock_module):
186 set_file_content({})
187 monkeypatch.setattr(AnsibleModule, "fail_json", fail_json)
188 mock_warn = MagicMock()
189 monkeypatch.setattr(AnsibleModule, "warn", mock_warn)
190
191 # hack to simulate a hang (module entrypoint requires >= 1 or None)
192 params = {"timeout": 0}
193 if on_timeout:
194 params["on_timeout"] = on_timeout
195
196 module = get_mock_module(params)
197 if should_raise:
198 with pytest.raises(AnsibleFailJson, match="Command '[^']*mount' timed out after 0.0 seconds"):
199 list(mount_facts.gen_mounts_by_source(module))
200 else:
201 assert list(mount_facts.gen_mounts_by_source(module)) == []
202 assert mock_warn.called == should_warn
203
204
205 def test_get_mount_facts(monkeypatch, set_file_content, get_mock_module):
206 set_file_content({"/etc/mtab": rhel9_4.mtab, "/etc/fstab": rhel9_4.fstab})
207 monkeypatch.setattr(mount_facts, "get_mount_size", mock_callable(return_value=None))
208 monkeypatch.setattr(mount_facts, "get_partition_uuid", mock_callable(return_value=None))
209 module = get_mock_module({})
210 assert len(rhel9_4.fstab_parsed) == 3
211 assert len(rhel9_4.mtab_parsed) == 4
212 assert len(mount_facts.get_mount_facts(module)) == 7
213
214
215 @pytest.mark.parametrize("filter_name, filter_value, source, mount_info", [
216 ("devices", "proc", rhel9_4.mtab_parsed[0][2], rhel9_4.mtab_parsed[0][-1]),
217 ("fstypes", "proc", rhel9_4.mtab_parsed[0][2], rhel9_4.mtab_parsed[0][-1]),
218 ])
219 def test_get_mounts_facts_filtering(monkeypatch, set_file_content, filter_name, filter_value, source, mount_info, get_mock_module):
220 set_file_content({"/etc/mtab": rhel9_4.mtab})
221 monkeypatch.setattr(mount_facts, "get_mount_size", mock_callable(return_value=None))
222 monkeypatch.setattr(mount_facts, "get_partition_uuid", mock_callable(return_value=None))
223 module = get_mock_module({filter_name: [filter_value]})
224 results = mount_facts.get_mount_facts(module)
225 expected_context = {"source": "/etc/mtab", "source_data": source}
226 assert len(results) == 1
227 assert results[0]["ansible_context"] == expected_context
228 assert results[0] == dict(ansible_context=expected_context, uuid=None, **mount_info)
229
230
231 def test_get_mounts_size(monkeypatch, set_file_content, get_mock_module):
232 def mock_get_mount_size(*args, **kwargs):
233 return {
234 "block_available": 3242510,
235 "block_size": 4096,
236 "block_total": 3789825,
237 "block_used": 547315,
238 "inode_available": 1875503,
239 "inode_total": 1966080,
240 "size_available": 13281320960,
241 "size_total": 15523123200,
242 }
243
244 set_file_content({"/etc/mtab": rhel9_4.mtab})
245 monkeypatch.setattr(mount_facts, "get_mount_size", mock_get_mount_size)
246 monkeypatch.setattr(mount_facts, "get_partition_uuid", mock_callable(return_value=None))
247 module = get_mock_module({})
248 result = mount_facts.get_mount_facts(module)
249 assert len(result) == len(rhel9_4.mtab_parsed)
250 expected_results = setup_parsed_sources_with_context(rhel9_4.mtab_parsed)
251 assert result == [dict(**result, **mock_get_mount_size()) for result in expected_results]
252
253
254 @pytest.mark.parametrize("on_timeout, should_warn, should_raise", [
255 (None, False, True),
256 ("error", False, True),
257 ("warn", True, False),
258 ("ignore", False, False),
259 ])
260 def test_get_mount_size_timeout(monkeypatch, set_file_content, on_timeout, should_warn, should_raise, get_mock_module):
261 set_file_content({"/etc/mtab": rhel9_4.mtab})
262 monkeypatch.setattr(AnsibleModule, "fail_json", fail_json)
263 mock_warn = MagicMock()
264 monkeypatch.setattr(AnsibleModule, "warn", mock_warn)
265 monkeypatch.setattr(mount_facts, "get_partition_uuid", mock_callable(return_value=None))
266
267 params = {"timeout": 0.1, "sources": ["dynamic"], "mount_binary": "mount"}
268 if on_timeout:
269 params["on_timeout"] = on_timeout
270
271 module = get_mock_module(params)
272
273 def mock_slow_function(*args, **kwargs):
274 time.sleep(0.15)
275 raise Exception("Timeout failed")
276
277 monkeypatch.setattr(mount_facts, "get_mount_size", mock_slow_function)
278 match = r"Timed out getting mount size for mount /proc \(type proc\) after 0.1 seconds"
279
280 if should_raise:
281 with pytest.raises(AnsibleFailJson, match=match):
282 mount_facts.get_mount_facts(module)
283 else:
284 results = mount_facts.get_mount_facts(module)
285 assert len(results) == len(rhel9_4.mtab_parsed)
286 assert results == setup_parsed_sources_with_context(rhel9_4.mtab_parsed)
287 assert mock_warn.called == should_warn
288
289
290 def setup_missing_uuid(monkeypatch, module):
291 monkeypatch.setattr(module, "get_bin_path", mock_callable(return_value="fake_bin"))
292 monkeypatch.setattr(mount_facts.subprocess, "check_output", mock_callable(return_value=""))
293 monkeypatch.setattr(mount_facts.os, "listdir", MagicMock(side_effect=FileNotFoundError))
294
295
296 def setup_udevadm_fallback(monkeypatch):
297 mock_udevadm_snippet = (
298 "DEVPATH=/devices/virtual/block/dm-0\n"
299 "DEVNAME=/dev/dm-0\n"
300 "DEVTYPE=disk\n"
301 "ID_FS_UUID=d37b5483-304d-471d-913e-4bb77856d90f\n"
302 )
303 monkeypatch.setattr(mount_facts.subprocess, "check_output", mock_callable(return_value=mock_udevadm_snippet))
304
305
306 def setup_run_lsblk_fallback(monkeypatch):
307 mount_facts.run_lsblk.cache_clear()
308 mock_lsblk_snippet = (
309 "/dev/zram0\n"
310 "/dev/mapper/luks-2f2610e3-56b3-4131-ae3e-caf9aa535b73 d37b5483-304d-471d-913e-4bb77856d90f\n"
311 "/dev/nvme0n1\n"
312 "/dev/nvme0n1p1 B521-06FD\n"
313 )
314 monkeypatch.setattr(mount_facts.subprocess, "check_output", mock_callable(return_value=mock_lsblk_snippet))
315
316
317 def setup_list_uuids_linux_preferred(monkeypatch):
318 mount_facts.list_uuids_linux.cache_clear()
319
320 def mock_realpath(path):
321 if path.endswith("d37b5483-304d-471d-913e-4bb77856d90f"):
322 return "/dev/mapper/luks-2f2610e3-56b3-4131-ae3e-caf9aa535b73"
323 return 'miss'
324
325 monkeypatch.setattr(mount_facts.os.path, "realpath", mock_realpath)
326 monkeypatch.setattr(mount_facts.os, "listdir", mock_callable(return_value=["B521-06FD", "d37b5483-304d-471d-913e-4bb77856d90f"]))
327
328
329 def test_get_partition_uuid(monkeypatch, get_mock_module):
330 module = get_mock_module({})
331
332 # Test missing UUID
333 setup_missing_uuid(monkeypatch, module)
334 assert mount_facts.get_partition_uuid(module, "ansible-test-fake-dev") is None
335
336 # Test udevadm (legacy fallback)
337 setup_udevadm_fallback(monkeypatch)
338 assert mount_facts.get_partition_uuid(module, "ansible-test-udevadm") == "d37b5483-304d-471d-913e-4bb77856d90f"
339
340 # Test run_lsblk fallback
341 setup_run_lsblk_fallback(monkeypatch)
342 assert mount_facts.get_partition_uuid(module, "/dev/nvme0n1p1") == "B521-06FD"
343
344 # Test list_uuids_linux (preferred)
345 setup_list_uuids_linux_preferred(monkeypatch)
346 assert mount_facts.get_partition_uuid(module, "/dev/mapper/luks-2f2610e3-56b3-4131-ae3e-caf9aa535b73") == "d37b5483-304d-471d-913e-4bb77856d90f"
347
348
349 def setup_parsed_sources_with_context(parsed_sources):
350 mounts = []
351 for source, mount, line, info in parsed_sources:
352 mount_point_result = dict(ansible_context={"source": source, "source_data": line}, uuid=None, **info)
353 mounts.append(mount_point_result)
354 return mounts
355
356
357 def test_handle_deduplication(monkeypatch, get_mock_module):
358 unformatted_mounts = [
359 {"mount": "/mnt/mount1", "device": "foo", "ansible_context": {"source": "/proc/mounts"}},
360 {"mount": "/mnt/mount2", "ansible_context": {"source": "/proc/mounts"}},
361 {"mount": "/mnt/mount1", "device": "qux", "ansible_context": {"source": "/etc/fstab"}},
362 ]
363
364 mock_warn = MagicMock()
365 monkeypatch.setattr(AnsibleModule, "warn", mock_warn)
366
367 module = get_mock_module({})
368 mount_points, aggregate_mounts = mount_facts.handle_deduplication(module, unformatted_mounts)
369 assert len(mount_points.keys()) == 2
370 assert mount_points["/mnt/mount1"]["device"] == "foo"
371 assert aggregate_mounts == []
372 assert not mock_warn.called
373
374
375 @pytest.mark.parametrize("include_aggregate_mounts, warn_expected", [
376 (None, True),
377 (False, False),
378 (True, False),
379 ])
380 def test_handle_deduplication_warning(monkeypatch, include_aggregate_mounts, warn_expected, get_mock_module):
381 unformatted_mounts = [
382 {"mount": "/mnt/mount1", "device": "foo", "ansible_context": {"source": "/proc/mounts"}},
383 {"mount": "/mnt/mount1", "device": "bar", "ansible_context": {"source": "/proc/mounts"}},
384 {"mount": "/mnt/mount2", "ansible_context": {"source": "/proc/mounts"}},
385 {"mount": "/mnt/mount1", "device": "qux", "ansible_context": {"source": "/etc/fstab"}},
386 ]
387
388 mock_warn = MagicMock()
389 monkeypatch.setattr(AnsibleModule, "warn", mock_warn)
390
391 module = get_mock_module({"include_aggregate_mounts": include_aggregate_mounts})
392 mount_points, aggregate_mounts = mount_facts.handle_deduplication(module, unformatted_mounts)
393
394 assert aggregate_mounts == [] if not include_aggregate_mounts else unformatted_mounts
395 assert mock_warn.called == warn_expected