keep-it-secret/tests/ext/aws/test_AWSSecrets.py

106 lines
2.4 KiB
Python
Raw Normal View History

2024-01-04 19:30:54 +00:00
# -*- coding: utf-8 -*-
# type: ignore
from __future__ import annotations
import os
from unittest import mock
2024-01-18 20:28:55 +00:00
import pytest
from pytest_mock import MockerFixture
2024-01-04 19:30:54 +00:00
from keep_it_secret.ext import aws
2024-01-18 20:28:55 +00:00
from .fixtures import TestingAWSSecrets
@pytest.fixture
def mock_boto3_client(mocker: MockerFixture) -> mock.Mock:
return mocker.patch.object(aws.boto3, 'client')
@pytest.fixture
def aws_secrets_manager_client() -> mock.Mock:
return mock.Mock()
def test_init():
# When
result = aws.AWSSecrets()
# Then
result.client is None
2024-01-04 19:30:54 +00:00
@mock.patch.dict(
os.environ,
{
'AWS_ACCESS_KEY_ID': 'test_access_key_id',
'AWS_SECRET_ACCESS_KEY': 'test_secret_access_key',
'AWS_SESSION_TOKEN': 'test_aws_session_token',
'AWS_DEFAULT_REGION': 'test_aws_default_region',
},
)
def test_as_boto3_client_kwargs():
# Given
secrets = aws.AWSSecrets()
# When
result = secrets.as_boto3_client_kwargs()
# Then
assert result == {
'aws_access_key_id': 'test_access_key_id',
'aws_secret_access_key': 'test_secret_access_key',
'aws_session_token': 'test_aws_session_token',
'region_name': 'test_aws_default_region',
}
@mock.patch.dict(os.environ, {}, clear=True)
def test_as_boto3_client_kwargs_empty():
# Given
secrets = aws.AWSSecrets()
# When
result = secrets.as_boto3_client_kwargs()
# Then
assert result == {}
2024-01-18 20:28:55 +00:00
def test_get_client_cache_miss(mock_boto3_client: mock.Mock,
aws_secrets_manager_client: mock.Mock,
testing_aws_secrets: TestingAWSSecrets):
# Given
mock_boto3_client.return_value = aws_secrets_manager_client
field = aws.AWSSecrets()
# When
result = field.get_client()
# Then
assert result == aws_secrets_manager_client
assert field.client == aws_secrets_manager_client
mock_boto3_client.assert_called_once_with(
'secretsmanager', **testing_aws_secrets.aws.as_boto3_client_kwargs(),
)
def test_get_client_cache_hit(mock_boto3_client: mock.Mock,
aws_secrets_manager_client: mock.Mock,
testing_aws_secrets: TestingAWSSecrets):
# Given
field = aws.AWSSecrets()
field.client = aws_secrets_manager_client
# When
result = field.get_client()
# Then
assert result == aws_secrets_manager_client
mock_boto3_client.assert_not_called()