pip install pytest pydantic
pytest
from functools import lru_cache | |
from pydantic import BaseSettings | |
class Settings(BaseSettings): | |
debug: bool = False | |
@lru_cache() | |
def get_settings(): | |
return Settings() |
import pytest | |
@pytest.fixture | |
def override_settings(): | |
import helpers | |
yield helpers.override_settings |
import contextlib | |
from config import get_settings # See https://fastapi.tiangolo.com/advanced/settings/?h=settings#settings-in-a-dependency | |
@contextlib.contextmanager | |
def override_settings(**overrides): | |
settings = get_settings() | |
original = {} | |
try: | |
for key, value in overrides.items(): | |
original[key] = getattr(settings, key) | |
setattr(settings, key, value) | |
yield | |
finally: | |
for key, value in original.items(): | |
setattr(settings, key, value) |
import pytest | |
from config import get_settings | |
import helpers | |
def test_override_settings(override_settings): | |
settings = get_settings() | |
assert settings.debug is True | |
with override_settings(debug=False): | |
assert settings.debug is False | |
assert settings.debug is True | |
# Make sure first valid params are reverted to their original values | |
with pytest.raises(AttributeError, match="'Settings' object has no attribute 'not_existant'"): | |
with override_settings(debug=False, not_existant=True): | |
pass | |
assert settings.debug is True | |
@helpers.override_settings(debug=False) | |
def test_override_settings_decorator(): | |
settings = get_settings() | |
assert settings.debug is False | |
def test_settings(): | |
settings = get_settings() | |
assert settings.debug is True |