Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 66dc84d

Browse files
committedOct 16, 2022
Clean up tests
1 parent 768eed6 commit 66dc84d

File tree

4 files changed

+65
-56
lines changed

4 files changed

+65
-56
lines changed
 

‎tests/lib/boto3_proxy_test.py

-10
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
from cloudformation_cli_python_lib.boto3_proxy import SessionProxy, _get_boto_session
33
from cloudformation_cli_python_lib.utils import Credentials
44

5-
import botocore # pylint: disable=C0411
6-
75

86
def test_get_boto_session_returns_proxy():
97
proxy = _get_boto_session(Credentials("", "", ""))
@@ -15,14 +13,6 @@ def test_get_boto_session_returns_none():
1513
assert proxy is None
1614

1715

18-
def test_can_create_boto_client():
19-
proxy = _get_boto_session(Credentials("", "", ""))
20-
client = proxy.client(
21-
"s3", region_name="us-west-2"
22-
) # just in case AWS_REGION not set in test environment
23-
assert isinstance(client, botocore.client.BaseClient)
24-
25-
2616
def test_can_retrieve_boto_session():
2717
proxy = _get_boto_session(Credentials("", "", ""))
2818
session = proxy.session

‎tests/lib/cipher_test.py

+10-4
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def test_create_kms_cipher():
1717
with patch(
1818
"cloudformation_cli_python_lib.cipher.aws_encryption_sdk.StrictAwsKmsMasterKeyProvider",
1919
autospec=True,
20-
):
20+
), patch("boto3.client", autospec=True):
2121
cipher = KmsCipher("encryptionKeyArn", "encryptionKeyRole")
2222
assert cipher
2323

@@ -35,7 +35,9 @@ def test_decrypt_credentials_success():
3535
autospec=True,
3636
), patch(
3737
"cloudformation_cli_python_lib.cipher.aws_encryption_sdk.EncryptionSDKClient.decrypt"
38-
) as mock_decrypt:
38+
) as mock_decrypt, patch(
39+
"boto3.client", autospec=True
40+
):
3941
mock_decrypt.return_value = (
4042
b'{"accessKeyId": "IASAYK835GAIFHAHEI23", "secretAccessKey": "66iOGPN5LnpZorcLr8Kh25u8AbjHVllv5poh2O0", "sessionToken": "lameHS2vQOknSHWhdFYTxm2eJc1JMn9YBNI4nV4mXue945KPL6DHfW8EsUQT5zwssYEC1NvYP9yD6Y5s5lKR3chflOHPFsIe6eqg"}', # noqa: B950
4143
Mock(),
@@ -56,7 +58,9 @@ def test_decrypt_credentials_fail():
5658
"cloudformation_cli_python_lib.cipher.aws_encryption_sdk.EncryptionSDKClient.decrypt"
5759
) as mock_decrypt, pytest.raises(
5860
_EncryptionError
59-
) as excinfo:
61+
) as excinfo, patch(
62+
"boto3.client", autospec=True
63+
):
6064
mock_decrypt.side_effect = AWSEncryptionSDKClientError()
6165
cipher = KmsCipher("encryptionKeyArn", "encryptionKeyRole")
6266
cipher.decrypt_credentials(
@@ -73,7 +77,9 @@ def test_decrypt_credentials_returns_null_fail():
7377
"cloudformation_cli_python_lib.cipher.aws_encryption_sdk.EncryptionSDKClient.decrypt"
7478
) as mock_decrypt, pytest.raises(
7579
_EncryptionError
76-
) as excinfo:
80+
) as excinfo, patch(
81+
"boto3.client", autospec=True
82+
):
7783
mock_decrypt.return_value = (
7884
b"null",
7985
Mock(),

‎tests/lib/log_delivery_test.py

+28-28
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
from uuid import uuid4
55

66
import pytest
7-
from boto3.session import Session
8-
from cloudformation_cli_python_lib.boto3_proxy import SessionProxy
7+
import botocore.errorfactory
8+
import botocore.session
99
from cloudformation_cli_python_lib.log_delivery import (
1010
HookProviderLogHandler,
1111
ProviderFilter,
@@ -19,6 +19,11 @@
1919
)
2020

2121

22+
logs_model = botocore.session.get_session().get_service_model("logs")
23+
factory = botocore.errorfactory.ClientExceptionsFactory()
24+
logs_exceptions = factory.create_client_exceptions(logs_model)
25+
26+
2227
@pytest.fixture
2328
def mock_logger():
2429
return create_autospec(logging.getLogger())
@@ -100,38 +105,36 @@ def mock_handler_set_formatter():
100105

101106

102107
@pytest.fixture
103-
def mock_provider_handler():
108+
def mock_provider_handler(mock_session):
104109
plh = ProviderLogHandler(
105110
group="test-group",
106111
stream="test-stream",
107-
session=SessionProxy(
108-
Session(
109-
aws_access_key_id="", aws_secret_access_key="", aws_session_token=""
110-
)
111-
),
112+
session=mock_session,
112113
)
113114
# not mocking the whole client because that replaces generated exception classes to
114115
# be replaced with mocks
115116
for method in ["create_log_group", "create_log_stream", "put_log_events"]:
116117
setattr(plh.client, method, Mock(auto_spec=True))
118+
119+
# set exceptions instead of using Mock
120+
plh.client.exceptions = logs_exceptions
117121
return plh
118122

119123

120124
@pytest.fixture
121-
def mock_hook_provider_handler():
125+
def mock_hook_provider_handler(mock_session):
122126
plh = HookProviderLogHandler(
123127
group="test-hook-group",
124128
stream="test-hook-stream",
125-
session=SessionProxy(
126-
Session(
127-
aws_access_key_id="", aws_secret_access_key="", aws_session_token=""
128-
)
129-
),
129+
session=mock_session,
130130
)
131131
# not mocking the whole client because that replaces generated exception classes to
132132
# be replaced with mocks
133133
for method in ["create_log_group", "create_log_stream", "put_log_events"]:
134134
setattr(plh.client, method, Mock(auto_spec=True))
135+
136+
# set exceptions instead of using Mock
137+
plh.client.exceptions = logs_exceptions
135138
return plh
136139

137140

@@ -286,12 +289,11 @@ def test__put_log_event_success(mock_provider_handler, sequence_token):
286289

287290

288291
def test__put_log_event_invalid_token(mock_provider_handler):
289-
exc = mock_provider_handler.client.exceptions
290292
mock_put = mock_provider_handler.client.put_log_events
291293
mock_put.return_value = {"nextSequenceToken": "some-other-seq"}
292294
mock_put.side_effect = [
293-
exc.InvalidSequenceTokenException({}, operation_name="Test"),
294-
exc.DataAlreadyAcceptedException({}, operation_name="Test"),
295+
logs_exceptions.InvalidSequenceTokenException({}, operation_name="Test"),
296+
logs_exceptions.DataAlreadyAcceptedException({}, operation_name="Test"),
295297
DEFAULT,
296298
]
297299
mock_provider_handler._put_log_event(
@@ -309,8 +311,7 @@ def test_emit_existing_cwl_group_stream(mock_provider_handler):
309311

310312

311313
def test_emit_no_group_stream(mock_provider_handler):
312-
exc = mock_provider_handler.client.exceptions.ResourceNotFoundException
313-
group_exc = exc(
314+
group_exc = logs_exceptions.ResourceNotFoundException(
314315
{"Error": {"Message": "log group does not exist"}},
315316
operation_name="PutLogRecords",
316317
)
@@ -326,7 +327,7 @@ def test_emit_no_group_stream(mock_provider_handler):
326327
mock_provider_handler._create_log_stream.assert_called_once()
327328

328329
# create_group should not be called again if the group already exists
329-
stream_exc = exc(
330+
stream_exc = logs_exceptions.ResourceNotFoundException(
330331
{"Error": {"Message": "log stream does not exist"}},
331332
operation_name="PutLogRecords",
332333
)
@@ -474,8 +475,9 @@ def test_hook_log_stream_create_success(mock_hook_provider_handler):
474475
@pytest.mark.parametrize("create_method", ["_create_log_group", "_create_log_stream"])
475476
def test__hook_create_already_exists(mock_hook_provider_handler, create_method):
476477
mock_logs_method = getattr(mock_hook_provider_handler.client, create_method[1:])
477-
exc = mock_hook_provider_handler.client.exceptions.ResourceAlreadyExistsException
478-
mock_logs_method.side_effect = exc({}, operation_name="Test")
478+
mock_logs_method.side_effect = logs_exceptions.ResourceAlreadyExistsException(
479+
{}, operation_name="Test"
480+
)
479481
# should not raise an exception if the log group already exists
480482
getattr(mock_hook_provider_handler, create_method)()
481483
mock_logs_method.assert_called_once()
@@ -493,12 +495,11 @@ def test__hook_put_log_event_success(mock_hook_provider_handler, sequence_token)
493495

494496

495497
def test__hook_put_log_event_invalid_token(mock_hook_provider_handler):
496-
exc = mock_hook_provider_handler.client.exceptions
497498
mock_put = mock_hook_provider_handler.client.put_log_events
498499
mock_put.return_value = {"nextSequenceToken": "some-other-seq"}
499500
mock_put.side_effect = [
500-
exc.InvalidSequenceTokenException({}, operation_name="Test"),
501-
exc.DataAlreadyAcceptedException({}, operation_name="Test"),
501+
logs_exceptions.InvalidSequenceTokenException({}, operation_name="Test"),
502+
logs_exceptions.DataAlreadyAcceptedException({}, operation_name="Test"),
502503
DEFAULT,
503504
]
504505
mock_hook_provider_handler._put_log_event(
@@ -516,8 +517,7 @@ def test_hook_emit_existing_cwl_group_stream(mock_hook_provider_handler):
516517

517518

518519
def test_hook_emit_no_group_stream(mock_hook_provider_handler):
519-
exc = mock_hook_provider_handler.client.exceptions.ResourceNotFoundException
520-
group_exc = exc(
520+
group_exc = logs_exceptions.ResourceNotFoundException(
521521
{"Error": {"Message": "log group does not exist"}},
522522
operation_name="PutLogRecords",
523523
)
@@ -533,7 +533,7 @@ def test_hook_emit_no_group_stream(mock_hook_provider_handler):
533533
mock_hook_provider_handler._create_log_stream.assert_called_once()
534534

535535
# create_group should not be called again if the group already exists
536-
stream_exc = exc(
536+
stream_exc = logs_exceptions.ResourceNotFoundException(
537537
{"Error": {"Message": "log stream does not exist"}},
538538
operation_name="PutLogRecords",
539539
)

‎tests/lib/metrics_test.py

+27-14
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
from datetime import datetime
44
from unittest.mock import Mock, call, patch
55

6-
import boto3
76
import pytest
7+
import botocore.errorfactory
8+
import botocore.session
89
from cloudformation_cli_python_lib.interface import (
910
Action,
1011
HookInvocationPoint,
@@ -18,7 +19,11 @@
1819
format_dimensions,
1920
)
2021

21-
from botocore.stub import Stubber # pylint: disable=C0411
22+
23+
cloudwatch_model = botocore.session.get_session().get_service_model("cloudwatch")
24+
factory = botocore.errorfactory.ClientExceptionsFactory()
25+
cloudwatch_exceptions = factory.create_client_exceptions(cloudwatch_model)
26+
2227

2328
ACCOUNT_ID = "123456789012"
2429
RESOURCE_TYPE = "Aa::Bb::Cc"
@@ -42,11 +47,16 @@ def test_format_dimensions():
4247

4348

4449
def test_put_metric_catches_error(mock_session):
45-
client = boto3.client("cloudwatch")
46-
stubber = Stubber(client)
47-
48-
stubber.add_client_error("put_metric_data", "InternalServiceError")
49-
stubber.activate()
50+
client = mock_session.client("cloudwatch")
51+
client.exceptions = cloudwatch_exceptions
52+
mock_put = client.put_metric_data
53+
mock_put.return_value = {}
54+
mock_put.side_effect = [
55+
cloudwatch_exceptions.InternalServiceFault(
56+
{"Error": {"Code": "InternalServiceError", "Message": ""}},
57+
operation_name="PutMetricData",
58+
),
59+
]
5060

5161
mock_session.client.return_value = client
5262

@@ -67,7 +77,6 @@ def test_put_metric_catches_error(mock_session):
6777
datetime.now(),
6878
)
6979

70-
stubber.deactivate()
7180
expected_calls = [
7281
call.error(
7382
"An error occurred while publishing metrics: %s",
@@ -197,11 +206,16 @@ def test_publish_log_delivery_exception_metric(mock_session):
197206

198207

199208
def test_put_hook_metric_catches_error(mock_session):
200-
client = boto3.client("cloudwatch")
201-
stubber = Stubber(client)
202-
203-
stubber.add_client_error("put_metric_data", "InternalServiceError")
204-
stubber.activate()
209+
client = mock_session.client("cloudwatch")
210+
client.exceptions = cloudwatch_exceptions
211+
mock_put = client.put_metric_data
212+
mock_put.return_value = {}
213+
mock_put.side_effect = [
214+
cloudwatch_exceptions.InternalServiceFault(
215+
{"Error": {"Code": "InternalServiceError", "Message": ""}},
216+
operation_name="PutMetricData",
217+
),
218+
]
205219

206220
mock_session.client.return_value = client
207221

@@ -222,7 +236,6 @@ def test_put_hook_metric_catches_error(mock_session):
222236
datetime.now(),
223237
)
224238

225-
stubber.deactivate()
226239
expected_calls = [
227240
call.error(
228241
"An error occurred while publishing metrics: %s",

0 commit comments

Comments
 (0)
Please sign in to comment.