how do i make pytest run my expecting test?

I’m unable to make a test that handles when the key value name does not exist:

if not self.key_vault_name:
    raise ValueError("Key Vault name is not set in the environment variables.")

this is the class implementation:

from azure.identity import ClientSecretCredential
from azure.keyvault.secrets import SecretClient
from dotenv import load_dotenv
import os


class SecretHandler:
    """
    Handles the retrieval of secrets from an Azure Key Vault.

    This class uses Azure's ClientSecretCredential for authentication and
    SecretClient for accessing the secrets stored in the Azure Key Vault.
    The credentials and Key Vault name are loaded from environment variables.
    """

    def __init__(self, dotenv_file: str = "srcconfig.env") -> None:
        """
        Initializes the SecretHandler instance by loading environment variables
        and setting up the credential for Azure Key Vault access using client ID,
        tenant ID, and client secret.
        """
        load_dotenv(dotenv_path=dotenv_file)

        self.key_vault_name = os.getenv("KEY_VAULT_NAME")
        if not self.key_vault_name:
            raise ValueError("Key Vault name is not set in the environment variables.")

        try:
            self.credential = ClientSecretCredential(
                client_id=os.getenv("AZURE_CLIENT_ID"),
                tenant_id=os.getenv("AZURE_TENANT_ID"),
                client_secret=os.getenv("AZURE_CLIENT_SECRET"),
            )
        except Exception as e:
            raise ValueError(f"Failed to obtain credential: {e}")

        self.secrets = {}

    def retrieve_secrets(self) -> None:
        """
        Retrieves all secrets from the Azure Key Vault.

        This method uses the SecretClient to list all the secret properties
        in the Key Vault and then retrieves the actual secret values, storing
        them in the `self.secrets` dictionary.
        """
        secret_client = SecretClient(
            vault_url=f"https://{self.key_vault_name}.vault.azure.net/",
            credential=self.credential,
        )

        try:
            secret_properties = secret_client.list_properties_of_secrets()
            for secret_property in secret_properties:
                secret = secret_client.get_secret(secret_property.name)
                self.secrets[secret.name] = secret.value
        except Exception as e:
            raise ValueError(f"Failed to retrieve secrets: {e}")

Here is my test:

@patch("src.config.secret_handler.ClientSecretCredential", autospec=True)
def test_init_secret_handler_wrong_key_vault(mock_client_secret_credential):
    # Mock setup for successful credential initialization
    client_secret_credential_instance = Mock()
    mock_client_secret_credential.return_value = client_secret_credential_instance

    # Mock environment without KEY_VAULT_NAME
    with patch.dict('os.environ', {'AZURE_CLIENT_ID': 'test_client_id',
                                   'AZURE_TENANT_ID': 'test_tenant_id',
                                   'AZURE_CLIENT_SECRET': 'test_client_secret'}):
        
        # Test initialization expecting ValueError from SecretHandler
        with pytest.raises(ValueError, match="Key Vault name is not set in the environment variables."):
            SecretHandler(dotenv_file="test/config/failed_env.env")

When running pytest, I got the following:

FAILED test/config/test_secret_handler.py::test_init_secret_handler_wrong_key_vault – Failed: DID NOT RAISE <class ‘ValueError’>

Any suggestions?

patch.dict (documentation) adds extra values to a dictionary. It does not remove existing ones unless you pass clear=True.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật