Skip to content

Commit 437a13f

Browse files
committed
test(version-scanner): add parametrized unit tests for _safe_read_file helper
1 parent 00d409d commit 437a13f

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

scripts/version_scanner/tests/unit/test_version_scanner.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,44 @@ def sample_match():
4848
}
4949

5050

51+
@pytest.mark.parametrize(
52+
"exception_to_raise, required, silent_missing, expected_exit, expected_output, expected_return",
53+
[
54+
(None, True, False, False, None, "file content"), # Success
55+
(FileNotFoundError(), True, True, False, None, None), # Silent missing FileNotFoundError
56+
(FileNotFoundError(), True, False, True, "Error: Test_desc not found", None), # Required FileNotFoundError
57+
(FileNotFoundError(), False, False, False, "Warning: Test_desc not found", None), # Optional FileNotFoundError
58+
(PermissionError(), True, False, True, "Error: Permission denied reading test_desc", None), # Required PermissionError
59+
(PermissionError(), False, False, False, "Warning: Permission denied reading test_desc", None), # Optional PermissionError
60+
(IOError("disk full"), True, False, True, "Error reading test_desc", None), # Required IOError
61+
(IOError("disk full"), False, False, False, "Warning: Error reading test_desc", None), # Optional IOError
62+
]
63+
)
64+
def test_safe_read_file_scenarios(
65+
capsys, exception_to_raise, required, silent_missing, expected_exit, expected_output, expected_return
66+
):
67+
from version_scanner import _safe_read_file
68+
69+
if exception_to_raise:
70+
mock_open = mock.mock_open()
71+
mock_open.side_effect = exception_to_raise
72+
else:
73+
mock_open = mock.mock_open(read_data="file content")
74+
75+
with patch("builtins.open", mock_open):
76+
if expected_exit:
77+
with pytest.raises(SystemExit) as excinfo:
78+
_safe_read_file("dummy.txt", required=required, description="test_desc", silent_missing=silent_missing)
79+
assert excinfo.value.code == 1
80+
else:
81+
res = _safe_read_file("dummy.txt", required=required, description="test_desc", silent_missing=silent_missing)
82+
assert res == expected_return
83+
84+
if expected_output:
85+
captured = capsys.readouterr()
86+
assert expected_output in captured.err
87+
88+
5189
# Test ConfigManager
5290
@pytest.mark.parametrize("dependency, version, expected", [
5391
(

0 commit comments

Comments
 (0)