Files

64 lines
2.2 KiB
Python

"""Unittests for the check_env function."""
import os
import unittest
from python_utils import check_env
class TestCheckEnv(unittest.TestCase):
set_vars: list[str]
unset_var: str
@classmethod
def setUpClass(cls) -> None:
"""Set up test environment variables."""
cls.set_vars = ["A", "B", "C"]
for var in cls.set_vars:
os.environ[var] = f"value_{var.lower()}"
cls.unset_var = "D"
if os.getenv(cls.unset_var) is not None:
raise unittest.SkipTest(
f"Environment variable '{cls.unset_var}' should not be set for this test."
)
@classmethod
def tearDownClass(cls) -> None:
for var in cls.set_vars:
if var in os.environ:
del os.environ[var]
os.environ.pop(var, None)
def test_check_env_accepts_single_string(self) -> None:
"""Test check_env function with a valid single string."""
check_env(self.set_vars[0])
def test_check_env_accepts_list_of_strings(self) -> None:
"""Test check_env function with a valid list of strings."""
check_env(self.set_vars)
def test_check_env_accepts_set_of_strings(self) -> None:
"""Test check_env function with a valid set of strings."""
check_env(set(self.set_vars))
def test_check_env_accepts_tuple_of_strings(self) -> None:
"""Test check_env function with a valid tuple of strings."""
check_env(tuple(self.set_vars))
def test_check_env_rejects_empty_list(self) -> None:
"""Test check_env function with an empty list."""
with self.assertRaises(ValueError):
check_env([])
def test_check_env_raises_error_on_missing_vars(self) -> None:
"""Test check_env function with missing environment variables."""
with self.assertRaises(OSError):
check_env(self.unset_var)
def test_check_env_does_not_raise_error_when_missing_ok_flag_set(self) -> None:
"""Test that check_env does not raise an error when the environment variable is missing and missing_ok=True.
The 'missing_ok' flag allows the function to skip raising an error if the specified environment variable(s) are not set.
"""
check_env(self.unset_var, missing_ok=True)