Skip to content

Commit

Permalink
Try to add the missing tests from CodeCov
Browse files Browse the repository at this point in the history
  • Loading branch information
mathijswesterhof committed Oct 1, 2024
1 parent 46e70c5 commit 8e8c7df
Show file tree
Hide file tree
Showing 2 changed files with 158 additions and 0 deletions.
108 changes: 108 additions & 0 deletions tests/unit/plugins/module_utils/test_hashi_vault_module.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2024 Mathijs Westerhof (@mathijswesterhof)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later

import pytest

from ansible_collections.community.hashi_vault.tests.unit.compat import mock
from .....plugins.module_utils._hashi_vault_common import ( # pylint: disable=unused-import
HashiVaultHVACError,
HashiVaultHelper,
)
from .....plugins.module_utils._hashi_vault_module import HashiVaultModule


@pytest.fixture
def generate_argspec():
return HashiVaultModule.generate_argspec(
want_exception=dict(type='bool'),
)


@pytest.fixture
def mock_hashi_vault_helper():
"""Fixture to mock HashiVaultHelper for testing"""
with mock.patch('ansible_collections.community.hashi_vault.plugins.module_utils._hashi_vault_common.HashiVaultHelper') as mock_helper:
yield mock_helper


class TestHashiVaultModule:

def test_init_success(self, generate_argspec, mock_hashi_vault_helper):
"""Test successful initialization of HashiVaultModule."""
module = HashiVaultModule(argument_spec=generate_argspec, supports_check_mode=True)

# Check if HashiVaultHelper was initialized
mock_hashi_vault_helper.assert_called_once()

# Ensure that the helper, adapter, connection options, and authenticator are set correctly
assert module.helper is not None
assert module.adapter is not None
assert module.connection_options is not None
assert module.authenticator is not None

def test_init_hvac_error(self, generate_argspec):
"""Test that HashiVaultHVACError triggers a call to fail_json."""
# Mock HashiVaultHelper to raise HashiVaultHVACError
with mock.patch('ansible_collections.community.hashi_vault.plugins.module_utils._hashi_vault_common.HashiVaultHelper',
side_effect=HashiVaultHVACError("Error occurred", "error_trace")):
module = HashiVaultModule(argument_spec=generate_argspec, supports_check_mode=True)

# Ensure that fail_json was called with the appropriate message and exception
module.fail_json.assert_called_once_with(
msg="Error occurred",
exception="error_trace"
)

def test_generate_argspec(self):
"""Test that generate_argspec correctly combines connection, authentication, and extra arguments."""
extra_args = {'extra_param': dict(type='str', required=False)}

# Call the class method generate_argspec
argspec = HashiVaultModule.generate_argspec(**extra_args)

# Ensure the argument specification includes connection and authentication specs
assert 'url' in argspec # From HashiVaultConnectionOptions.ARGSPEC
assert 'auth_method' in argspec # From HashiVaultAuthenticator.ARGSPEC

# Ensure extra parameters are included in the argument spec
assert 'extra_param' in argspec

def test_generate_retry_callback(self, generate_argspec):
"""Test the _generate_retry_callback method and ensure it calls warn on retry action 'warn'."""
module = HashiVaultModule(argument_spec=generate_argspec, supports_check_mode=True)

# Mock the `warn` method
module.warn = mock.MagicMock()

# Generate a retry callback with the 'warn' action
retry_callback = module._generate_retry_callback('warn')

# Create a mock retry object with retries remaining
mock_retry_obj = mock.MagicMock(total=2)

# Call the retry callback
retry_callback(mock_retry_obj)

# Ensure the warn method was called with the correct message
module.warn.assert_called_once_with('community.hashi_vault: 2 retries remaining.')

def test_generate_retry_callback_no_warn(self, generate_argspec):
"""Test the _generate_retry_callback method when no warning is issued."""
module = HashiVaultModule(argument_spec=generate_argspec, supports_check_mode=True)

# Mock the `warn` method
module.warn = mock.MagicMock()

# Generate a retry callback with no retry action
retry_callback = module._generate_retry_callback('no_warn')

# Create a mock retry object with retries remaining
mock_retry_obj = mock.MagicMock(total=2)

# Call the retry callback
retry_callback(mock_retry_obj)

# Ensure the warn method was not called
module.warn.assert_not_called()
50 changes: 50 additions & 0 deletions tests/unit/plugins/modules/test_vault_pki_generate_certificate.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@
import pytest
import json

from ansible_collections.community.hashi_vault.tests.unit.compat import mock

from .....plugins.modules import vault_pki_generate_certificate
from .....plugins.module_utils._hashi_vault_common import HashiVaultValueError
from .....plugins.module_utils._authenticator import HashiVaultAuthenticator


pytestmark = pytest.mark.usefixtures(
'patch_ansible_module',
Expand All @@ -18,6 +23,23 @@
)


@pytest.fixture
def failed_authenticator():
authenticator = HashiVaultAuthenticator
authenticator.validate = mock.Mock(side_effect=HashiVaultValueError("Authentication failed"))
authenticator.authenticate = mock.Mock(wraps=lambda client: 'throwaway')

return authenticator


@pytest.fixture
def patch_failed_authenticator(failed_authenticator):
with mock.patch(
'ansible_collections.community.hashi_vault.plugins.module_utils._hashi_vault_module.HashiVaultAuthenticator',
new=failed_authenticator):
yield


def _connection_options():
return {
'auth_method': 'token',
Expand Down Expand Up @@ -113,3 +135,31 @@ def test_vault_pki_generate_certificate_vault_exception(self, vault_client, capf
vault_pki_generate_certificate.main()

assert e.value.code != 0

@pytest.mark.parametrize('patch_ansible_module', [_combined_options()], indirect=True)
def test_vault_pki_generate_certificate_authenticator_exception(self, pki_generate_certificate_response, patch_failed_authenticator, vault_client, capfd):
client = vault_client
client.secrets.pki.generate_certificate.return_value = pki_generate_certificate_response

with pytest.raises(SystemExit) as e:
vault_pki_generate_certificate.main()

out, err = capfd.readouterr()

try:
result = json.loads(out)
except json.JSONDecodeError:
pytest.fail(f"Output is not valid JSON: {out}")

assert 'msg' in result, "'msg' not found in module output"
assert 'exception' in result, "'exception' not found in module output"

assert result['msg'] == 'Authentication failed', (
f"Expected msg to be 'Authentication failed', got '{result['msg']}'"
)

assert 'Traceback' in result['exception'], (
"Expected 'exception' to contain 'Traceback', but it does not."
)

assert e.value.code != 0, "Expected non-zero exit code when authentication fails"

0 comments on commit 8e8c7df

Please sign in to comment.