Settings management in Pydantic makes it easy to override settings, like below.
# override settings
settings.env = "production"However, if you want to change the setting value in each test suite in your test code,
You need to change the values at the beginning of the test and roll back the values at the end of the test.
from app.core.config import settings # Pydantic settings
def test_settings():
# override setting value
env = settings.ENV
settings.ENV = "production"
# assertions
...
# rollback setting value, because in order not to affect other tests
settings.ENV = envThis causes a lot of code duplication. So, in order to remove the code that occurs repeatedly, created a decorator for tests.
You can easily override the setting value by applying a decorator to the test function.
Also, when the test function is finished, the settings are automatically roll back.
That's all.
# for sync tests
@override_settings(settings=settings, ENV="production")
# for async tests
@async_override_settings(settings=settings, ENV="production")pip install override-pydantic-settingsfrom pydantic import BaseSettings
from override_pydantic_settings import override_settings
class MySettings(BaseSettings):
ENV: str = "dev"
NAME: str = "Junki"
EMAIL: str = "[email protected]"
settings = MySettings()
@override_settings(settings=settings, ENV="production", NAME="Junki Yoon")
def test_function():
...@pytest.mark.asyncio
@async_override_settings(settings=settings, ENV="production", EMAIL="[email protected]")
async def test_function():
...You cannot override the setting value that does not exist.
Compatible with Python >= 3.6
Python >= 3.10, we can create async decorators using the
async context manager.
It seems that async & sync can be integrated into one function.
$ python -m venv venv
(venv)$ source venv/bin/acitave
(venv)$ pip install -r requirements.txt
(venv)$ pytestThis project is licensed under the MIT license.