I have a very simple python class with a constructor:
from utils.util import Singleton
class VaultAuth(object):
__metaclass__ = Singleton
def __init__(self, prefix_path, address):
self.path = prefix_path
self.vault_url = address
self.is_authenticated = False
def get_secrets(self, region):
print self.is_authenticated
if not self.is_authenticated:
raise RuntimeError("Failed to fetch secrets")
else:
return True
where Singleton class looks as follows:
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
To write unit tests I have:
@pytest.mark.unit_test
def test_get_secrets(monkeypatch):
def mock_init_auth_false(self, *args, **kwargs):
self.path = "dummy_path"
self.vault_url = "dummy_url"
self.is_authenticated = False
def mock_init_auth_true(self, *args, **kwargs):
self.path = "dummy_path"
self.vault_url = "dummy_url"
self.is_authenticated = True
# Negative case - auth is false
monkeypatch.setattr(vault1.VaultAuth, "__init__", mock_init_auth_false)
secrets_manager = vault1.VaultAuth(prefix_path="prefix", address="https://vault")
with pytest.raises(RuntimeError) as exception:
secret_data = secrets_manager.get_secrets(region="test_region")
assert "Failed to fetch secrets" in str(exception.value)
monkeypatch.undo()
# Positive case - auth is true
monkeypatch.setattr(vault1.VaultAuth, "__init__", mock_init_auth_true)
secrets_manager = vault1.VaultAuth(prefix_path="prefix", address="https://vault")
assert secrets_manager.get_secrets(region="test_region")
The first test print is_authenticated value as False as per expectation but the second test also prints it as False. If I reverse the order of the tests both print True. Any pointers? The class is singleton. How to test a singleton class function?
from Unable to overwrite init value of a function once set by monkeypatch for singleton class
No comments:
Post a Comment