Skip to content

Instantly share code, notes, and snippets.

@arthurio
Last active April 23, 2021 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arthurio/3e399271227dacba0908b49179bc6752 to your computer and use it in GitHub Desktop.
Save arthurio/3e399271227dacba0908b49179bc6752 to your computer and use it in GitHub Desktop.
FastApi - Override pydantic settings

Setup

pip install pytest pydantic

Run

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment