keep-it-secret/tests/ext/vault/test_VaultSecrets.py
2024-02-08 20:52:08 +00:00

110 lines
2.3 KiB
Python

# -*- coding: utf-8 -*-
# type: ignore
from __future__ import annotations
import os
from unittest import mock
import pytest
from pytest_mock import MockerFixture
from keep_it_secret.ext import vault
@pytest.fixture
def mock_hvac_client(mocker: MockerFixture) -> mock.Mock:
return mocker.patch.object(vault.hvac, 'Client')
@pytest.fixture
def hvac_client() -> mock.Mock:
return mock.Mock()
def test_init():
# When
result = vault.VaultSecrets()
# Then
assert result.client is None
@mock.patch.dict(
os.environ,
{
'VAULT_URL': 'https://vault.work/',
'VAULT_TOKEN': 'test_vault_token',
'VAULT_CLIENT_CERT_PATH': '/tmp/vault_client_cert.pem',
'VAULT_CLIENT_KEY_PATH': '/tmp/vault_client_key.pem',
'VAULT_SERVER_CERT_PATH': '/tmp/vault_server_cert.pem',
},
)
def test_as_hvac_client_kwargs():
# Given
secrets = vault.VaultSecrets()
# When
result = secrets.as_hvac_client_kwargs()
# Then
assert result == {
'url': 'https://vault.work/',
'token': 'test_vault_token',
'cert': ('/tmp/vault_client_cert.pem', '/tmp/vault_client_key.pem'),
'verify': '/tmp/vault_server_cert.pem',
}
@mock.patch.dict(
os.environ,
{
'VAULT_URL': 'https://vault.work/',
'VAULT_TOKEN': 'test_vault_token',
},
)
def test_as_hvac_client_kwargs_without_optional_fields():
# Given
secrets = vault.VaultSecrets()
# When
result = secrets.as_hvac_client_kwargs()
# Then
assert result == {
'url': 'https://vault.work/',
'token': 'test_vault_token',
}
def test_get_client_cache_miss(mock_hvac_client: mock.Mock,
hvac_client: mock.Mock):
# Given
mock_hvac_client.return_value = hvac_client
secrets = vault.VaultSecrets()
# When
result = secrets.get_client()
# Then
assert result == hvac_client
assert secrets.client == hvac_client
mock_hvac_client.assert_called_once_with(**secrets.as_hvac_client_kwargs())
def test_get_client_cache_hit(mock_hvac_client: mock.Mock,
hvac_client: mock.Mock):
# Given
secrets = vault.VaultSecrets()
secrets.client = hvac_client
# When
result = secrets.get_client()
# Then
assert result == hvac_client
mock_hvac_client.assert_not_called()