Debian Codegraph @

test/units/errors/test_handler.py

raw
1 from __future__ import annotations
2
3 import os
4
5 import pytest
6 import pytest_mock
7
8 from ansible.constants import config
9 from ansible.errors import AnsibleUndefinedConfigEntry
10 from ansible._internal._errors._handler import ErrorHandler, ErrorAction, Skippable, _SkipException
11 from ansible.utils.display import Display
12
13
14 def test_skippable_ignore_skips_body() -> None:
15 """Verify that `skip_on_ignore=True` skips the body within the context manager when `action=ErrorAction.IGNORE`."""
16 body_ran = False
17 assert not body_ran # satisfy static analysis which assumes the context manager body will run
18
19 with Skippable, ErrorHandler(ErrorAction.IGNORE).handle(Exception, skip_on_ignore=True):
20 body_ran = True
21
22 assert not body_ran
23
24
25 def test_skippable_without_skip_on_ignore() -> None:
26 """
27 Verify using `Skippable` without invoking a handler with `skip_on_ignore=True` will fail.
28 This protects against accidental use of `Skippable` by itself, or forgetting to use `skip_on_ignore=True` -- both of which have no effect.
29 """
30 body_ran = False
31 assert not body_ran # satisfy static analysis which assumes the context manager body will run
32
33 with pytest.raises(RuntimeError) as err:
34 with Skippable:
35 body_ran = True
36
37 assert body_ran
38 assert 'handler was never invoked' in str(err.value)
39
40
41 def test_skippable_non_skip_exception() -> None:
42 """Verify that `Skippable` does not interfere with exceptions."""
43 ex_to_raise = RuntimeError('let me through')
44
45 with pytest.raises(RuntimeError) as err:
46 with Skippable:
47 raise ex_to_raise
48
49 assert err.value is ex_to_raise
50
51
52 @pytest.mark.parametrize("error_action", (ErrorAction.IGNORE, ErrorAction.WARNING, ErrorAction.ERROR))
53 def test_skip_on_ignore_missing_skippable(error_action: ErrorAction) -> None:
54 """Verify that a `_SkipException` is raised when `skip_on_ignore=True` and no `Skippable` context was used to suppress it."""
55 body_ran = False
56 assert not body_ran # satisfy static analysis which assumes the context manager body will run
57
58 with pytest.raises(_SkipException):
59 with ErrorHandler(error_action).handle(Exception, skip_on_ignore=True):
60 body_ran = True
61
62 if error_action is ErrorAction.IGNORE:
63 assert not body_ran
64 else:
65 assert body_ran
66
67
68 @pytest.mark.parametrize("exception_type", (RuntimeError, NotImplementedError))
69 def test_ignore_success(exception_type: type[Exception]) -> None:
70 """Verify that `ErrorAction.IGNORE` suppresses the specified exception types."""
71 body_ran = False
72 assert not body_ran # satisfy static analysis which assumes the context manager body will run
73
74 with ErrorHandler(ErrorAction.IGNORE).handle(RuntimeError, NotImplementedError):
75 body_ran = True
76 raise exception_type('should be ignored')
77
78 assert body_ran
79
80
81 def test_ignore_passes_other_exceptions() -> None:
82 """Verify that `ErrorAction.IGNORE` does not suppress exception types not passed to `handle`."""
83 with pytest.raises(NotImplementedError):
84 with ErrorHandler(ErrorAction.IGNORE).handle(TypeError, ValueError):
85 raise NotImplementedError()
86
87
88 @pytest.mark.parametrize("exception_type", (RuntimeError, NotImplementedError))
89 def test_warn_success(exception_type: type[Exception], mocker: pytest_mock.MockerFixture) -> None:
90 """Verify that `ErrorAction.WARNING` eats the specified error type and calls `error_as_warning` with the exception instance raised."""
91 eaw = mocker.patch.object(Display(), 'error_as_warning')
92 with ErrorHandler(ErrorAction.WARNING).handle(RuntimeError, NotImplementedError):
93 raise exception_type()
94
95 assert isinstance(eaw.call_args.kwargs['exception'], exception_type)
96
97
98 def test_warn_passes_other_exceptions(mocker: pytest_mock.MockerFixture) -> None:
99 """Verify that `ErrorAction.WARNING` does not suppress exception types not passed to `handle`, and that `error_as_warning` is not called for them."""
100 eaw = mocker.patch.object(Display(), 'error_as_warning')
101
102 with pytest.raises(NotImplementedError):
103 with ErrorHandler(ErrorAction.WARNING).handle(TypeError, ValueError):
104 raise NotImplementedError()
105
106 assert not eaw.called
107
108
109 @pytest.mark.parametrize("exception_type", (AttributeError, NotImplementedError, ValueError))
110 def test_fail(exception_type: type[Exception]) -> None:
111 """Verify that `ErrorAction.ERROR` passes through all exception types, regardless of what was passed to `handle`."""
112 with pytest.raises(exception_type):
113 with ErrorHandler(ErrorAction.ERROR).handle(AttributeError, NotImplementedError):
114 raise exception_type()
115
116
117 def test_no_exceptions_to_handle():
118 """Verify that passing no exceptions to `handle` fails."""
119 with pytest.raises(ValueError):
120 with ErrorHandler(ErrorAction.IGNORE).handle():
121 pass
122
123
124 @pytest.mark.parametrize("value", ('ignore', 'warning', 'error'))
125 def test_from_config_env_success(value: str, mocker: pytest_mock.MockerFixture) -> None:
126 """Verify that `from_config` correctly creates handlers with the requested error action config string."""
127 mocker.patch.dict(os.environ, dict(_ANSIBLE_CALLBACK_DISPATCH_ERROR_BEHAVIOR=value))
128
129 assert config.get_config_value("_CALLBACK_DISPATCH_ERROR_BEHAVIOR") == value
130 eh = ErrorHandler.from_config("_CALLBACK_DISPATCH_ERROR_BEHAVIOR")
131 assert eh.action == ErrorAction[value.upper()]
132
133
134 def test_from_config_fail() -> None:
135 """Verify that `from_config` fails on an invalid config entry name."""
136 with pytest.raises(AnsibleUndefinedConfigEntry):
137 ErrorHandler.from_config("invalid")