Debian Codegraph @

ansible_collections/amazon/aws/tests/unit/plugins/module_utils/exceptions/test_exceptions.py

raw
1 # (c) 2022 Red Hat Inc.
2 #
3 # This file is part of Ansible
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from unittest.mock import sentinel
7
8 import pytest
9 from botocore.exceptions import ClientError
10
11 import ansible_collections.amazon.aws.plugins.module_utils.exceptions as aws_exceptions
12
13
14 @pytest.fixture(name="utils_exceptions")
15 def fixture_utils_exceptions():
16 return aws_exceptions
17
18
19 def test_with_kwargs(utils_exceptions):
20 nested_exception = Exception(sentinel.EXCEPTION)
21 with pytest.raises(utils_exceptions.AnsibleAWSError) as e:
22 raise utils_exceptions.AnsibleAWSError(kw1=sentinel.KW1, kw2=sentinel.KW2)
23 assert str(e.value) == ""
24 assert e.value.exception is None
25 assert e.value.message is None
26 assert e.value.kwargs == dict(kw1=sentinel.KW1, kw2=sentinel.KW2)
27
28 with pytest.raises(utils_exceptions.AnsibleAWSError) as e:
29 raise utils_exceptions.AnsibleAWSError(
30 message=sentinel.MESSAGE, exception=nested_exception, kw1=sentinel.KW1, kw2=sentinel.KW2
31 )
32 assert str(e.value) == "sentinel.MESSAGE: sentinel.EXCEPTION"
33 assert e.value.exception is nested_exception
34 assert e.value.message is sentinel.MESSAGE
35 assert e.value.kwargs == dict(kw1=sentinel.KW1, kw2=sentinel.KW2)
36
37
38 def test_with_both(utils_exceptions):
39 nested_exception = Exception(sentinel.EXCEPTION)
40
41 with pytest.raises(utils_exceptions.AnsibleAWSError) as e:
42 raise utils_exceptions.AnsibleAWSError(message=sentinel.MESSAGE, exception=nested_exception)
43 assert str(e.value) == "sentinel.MESSAGE: sentinel.EXCEPTION"
44 assert e.value.exception is nested_exception
45 assert e.value.message is sentinel.MESSAGE
46 assert e.value.kwargs == {}
47
48 with pytest.raises(utils_exceptions.AnsibleAWSError) as e:
49 raise utils_exceptions.AnsibleAWSError(sentinel.MESSAGE, exception=nested_exception)
50 assert str(e.value) == "sentinel.MESSAGE: sentinel.EXCEPTION"
51 assert e.value.exception is nested_exception
52 assert e.value.message is sentinel.MESSAGE
53 assert e.value.kwargs == {}
54
55
56 def test_with_exception(utils_exceptions):
57 nested_exception = Exception(sentinel.EXCEPTION)
58
59 with pytest.raises(utils_exceptions.AnsibleAWSError) as e:
60 raise utils_exceptions.AnsibleAWSError(exception=nested_exception)
61 assert str(e.value) == "sentinel.EXCEPTION"
62 assert e.value.exception is nested_exception
63 assert e.value.message is None
64 assert e.value.kwargs == {}
65
66
67 def test_with_message(utils_exceptions):
68 with pytest.raises(utils_exceptions.AnsibleAWSError) as e:
69 raise utils_exceptions.AnsibleAWSError(message=sentinel.MESSAGE)
70 assert str(e.value) == "sentinel.MESSAGE"
71 assert e.value.exception is None
72 assert e.value.message is sentinel.MESSAGE
73 assert e.value.kwargs == {}
74
75 with pytest.raises(utils_exceptions.AnsibleAWSError) as e:
76 raise utils_exceptions.AnsibleAWSError(sentinel.MESSAGE)
77 assert str(e.value) == "sentinel.MESSAGE"
78 assert e.value.exception is None
79 assert e.value.message is sentinel.MESSAGE
80 assert e.value.kwargs == {}
81
82
83 def test_empty(utils_exceptions):
84 with pytest.raises(utils_exceptions.AnsibleAWSError) as e:
85 raise utils_exceptions.AnsibleAWSError()
86 assert str(e.value) == ""
87 assert e.value.exception is None
88 assert e.value.message is None
89 assert e.value.kwargs == {}
90
91
92 def test_inheritence(utils_exceptions):
93 aws_exception = utils_exceptions.AnsibleAWSError()
94
95 assert isinstance(aws_exception, Exception)
96 assert isinstance(aws_exception, utils_exceptions.AnsibleAWSError)
97
98 botocore_exception = utils_exceptions.AnsibleBotocoreError()
99
100 assert isinstance(botocore_exception, Exception)
101 assert isinstance(botocore_exception, utils_exceptions.AnsibleAWSError)
102 assert isinstance(botocore_exception, utils_exceptions.AnsibleBotocoreError)
103
104
105 def _make_clienterror(code, message):
106 """Helper to create a botocore ClientError exception."""
107 params = {
108 "Error": {"Code": code, "Message": message},
109 "ResponseMetadata": {"RequestId": "01234567-89ab-cdef-0123-456789abcdef"},
110 }
111 return ClientError(params, "test_operation")
112
113
114 class TestIsAnsibleAwsErrorCode:
115 """Test suite for is_ansible_aws_error_code() function."""
116
117 def test_catch_matching_error_code(self, utils_exceptions):
118 """Test that matching error codes are caught by is_ansible_aws_error_code."""
119 client_error = _make_clienterror("IdempotentParameterMismatch", "Parameter mismatch")
120 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
121
122 # Should catch the exception when error code matches
123 caught = False
124 try:
125 raise aws_error
126 except utils_exceptions.is_ansible_aws_error_code("IdempotentParameterMismatch"):
127 caught = True
128
129 assert caught
130
131 def test_not_catch_non_matching_error_code(self, utils_exceptions):
132 """Test that non-matching error codes pass through is_ansible_aws_error_code."""
133 client_error = _make_clienterror("ResourceNotFound", "Resource not found")
134 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
135
136 # Should not catch exception when error code doesn't match
137 # pytest.raises verifies the exception propagates through the except clause
138 with pytest.raises(utils_exceptions.AnsibleAWSError):
139 try:
140 raise aws_error
141 except utils_exceptions.is_ansible_aws_error_code("IdempotentParameterMismatch"):
142 pass
143
144 def test_catch_code_from_list(self, utils_exceptions):
145 """Test catching when error code is in a list of codes."""
146 client_error = _make_clienterror("RouteAlreadyExists", "Route already exists")
147 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
148
149 # Should catch when code is in the list
150 caught = False
151 try:
152 raise aws_error
153 except utils_exceptions.is_ansible_aws_error_code(["IdempotentParameterMismatch", "RouteAlreadyExists"]):
154 caught = True
155
156 assert caught
157
158 def test_catch_code_from_tuple(self, utils_exceptions):
159 """Test catching when error code is in a tuple."""
160 client_error = _make_clienterror("AccessDenied", "Access denied")
161 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
162
163 # Should catch when code is in the tuple
164 caught = False
165 try:
166 raise aws_error
167 except utils_exceptions.is_ansible_aws_error_code(("InvalidParameter", "AccessDenied")):
168 caught = True
169
170 assert caught
171
172 def test_catch_code_from_set(self, utils_exceptions):
173 """Test catching when error code is in a set."""
174 client_error = _make_clienterror("Throttling", "Request throttled")
175 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
176
177 # Should catch when code is in the set
178 caught = False
179 try:
180 raise aws_error
181 except utils_exceptions.is_ansible_aws_error_code({"InvalidParameter", "Throttling"}):
182 caught = True
183
184 assert caught
185
186 def test_does_not_catch_regular_exception(self, utils_exceptions):
187 """Test that non-AnsibleAWSError exceptions pass through."""
188 regular_exception = ValueError("Some error")
189
190 # Should not catch regular exceptions - verify they propagate
191 with pytest.raises(ValueError):
192 try:
193 raise regular_exception
194 except utils_exceptions.is_ansible_aws_error_code("SomeCode"):
195 pass
196
197 def test_does_not_catch_ansible_aws_error_without_client_error(self, utils_exceptions):
198 """Test that AnsibleAWSError without ClientError passes through."""
199 aws_error = utils_exceptions.AnsibleAWSError(message="Some error")
200
201 # Should not catch AnsibleAWSError that doesn't wrap a ClientError
202 with pytest.raises(utils_exceptions.AnsibleAWSError):
203 try:
204 raise aws_error
205 except utils_exceptions.is_ansible_aws_error_code("SomeCode"):
206 pass
207
208 def test_returns_ansible_aws_error_class_on_match(self, utils_exceptions):
209 """Test that matching returns AnsibleAWSError class."""
210 client_error = _make_clienterror("InvalidParameter", "Invalid parameter")
211 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
212
213 result = utils_exceptions.is_ansible_aws_error_code("InvalidParameter", aws_error)
214 assert result is utils_exceptions.AnsibleAWSError
215
216 def test_returns_dummy_exception_on_no_match(self, utils_exceptions):
217 """Test that non-matching returns dummy exception class."""
218 client_error = _make_clienterror("ResourceNotFound", "Resource not found")
219 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
220
221 result = utils_exceptions.is_ansible_aws_error_code("InvalidParameter", aws_error)
222 assert result is not utils_exceptions.AnsibleAWSError
223 assert issubclass(result, Exception)
224 assert result.__name__ == "NeverEverRaisedException"
225
226
227 class TestIsAnsibleAwsErrorMessage:
228 """Test suite for is_ansible_aws_error_message() function."""
229
230 def test_catch_matching_error_message(self, utils_exceptions):
231 """Test that matching error messages are caught."""
232 client_error = _make_clienterror(
233 "VpcClassicLinkNotSupported", "The functionality you requested is not available in this region."
234 )
235 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
236
237 # Should catch when message matches
238 caught = False
239 try:
240 raise aws_error
241 except utils_exceptions.is_ansible_aws_error_message(
242 "The functionality you requested is not available in this region."
243 ):
244 caught = True
245
246 assert caught
247
248 def test_catch_message_substring(self, utils_exceptions):
249 """Test that substring matching works for error messages."""
250 client_error = _make_clienterror(
251 "VpcClassicLinkNotSupported", "The functionality you requested is not available in this region."
252 )
253 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
254
255 # Should catch when substring matches
256 caught = False
257 try:
258 raise aws_error
259 except utils_exceptions.is_ansible_aws_error_message("functionality you requested"):
260 caught = True
261
262 assert caught
263
264 def test_not_catch_non_matching_message(self, utils_exceptions):
265 """Test that non-matching messages pass through."""
266 client_error = _make_clienterror("ResourceNotFound", "The specified resource does not exist")
267 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
268
269 # Should not catch when message doesn't match - verify exception propagates
270 with pytest.raises(utils_exceptions.AnsibleAWSError):
271 try:
272 raise aws_error
273 except utils_exceptions.is_ansible_aws_error_message("access denied"):
274 pass
275
276 def test_case_sensitive_matching(self, utils_exceptions):
277 """Test that message matching is case-sensitive."""
278 client_error = _make_clienterror("AccessDenied", "Access Denied")
279 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
280
281 # Should catch with correct case
282 caught_correct_case = False
283 try:
284 raise aws_error
285 except utils_exceptions.is_ansible_aws_error_message("Access Denied"):
286 caught_correct_case = True
287
288 assert caught_correct_case
289
290 # Should not catch with different case - verify exception propagates
291 client_error2 = _make_clienterror("AccessDenied", "Access Denied")
292 aws_error2 = utils_exceptions.AnsibleAWSError(exception=client_error2)
293
294 with pytest.raises(utils_exceptions.AnsibleAWSError):
295 try:
296 raise aws_error2
297 except utils_exceptions.is_ansible_aws_error_message("access denied"):
298 pass
299
300 def test_does_not_catch_regular_exception(self, utils_exceptions):
301 """Test that non-AnsibleAWSError exceptions pass through."""
302 regular_exception = ValueError("Some error")
303
304 # Should not catch regular exceptions - verify they propagate
305 with pytest.raises(ValueError):
306 try:
307 raise regular_exception
308 except utils_exceptions.is_ansible_aws_error_message("Some message"):
309 pass
310
311 def test_does_not_catch_ansible_aws_error_without_client_error(self, utils_exceptions):
312 """Test that AnsibleAWSError without ClientError passes through."""
313 aws_error = utils_exceptions.AnsibleAWSError(message="Some error")
314
315 # Should not catch AnsibleAWSError that doesn't wrap a ClientError
316 with pytest.raises(utils_exceptions.AnsibleAWSError):
317 try:
318 raise aws_error
319 except utils_exceptions.is_ansible_aws_error_message("Some message"):
320 pass
321
322 def test_returns_ansible_aws_error_class_on_match(self, utils_exceptions):
323 """Test that matching returns AnsibleAWSError class."""
324 client_error = _make_clienterror("InvalidParameter", "Invalid parameter value")
325 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
326
327 result = utils_exceptions.is_ansible_aws_error_message("Invalid parameter", aws_error)
328 assert result is utils_exceptions.AnsibleAWSError
329
330 def test_returns_dummy_exception_on_no_match(self, utils_exceptions):
331 """Test that non-matching returns dummy exception class."""
332 client_error = _make_clienterror("ResourceNotFound", "Resource not found")
333 aws_error = utils_exceptions.AnsibleAWSError(exception=client_error)
334
335 result = utils_exceptions.is_ansible_aws_error_message("access denied", aws_error)
336 assert result is not utils_exceptions.AnsibleAWSError
337 assert issubclass(result, Exception)
338 assert result.__name__ == "NeverEverRaisedException"