You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fromtypingimportDictfrompydanticimportBaseSettings, Field, validatorclassGlobalConfig(BaseSettings):
"""Global configurations."""AUTH_USER: str=Field(
default=None,
description="Mutually exclusive with AUTH_TOKEN.",
)
AUTH_PASSWORD: str=Field(
default=None,
description="Mutually exclusive with AUTH_TOKEN.",
)
AUTH_TOKEN: str=Field(
default=None,
description="Mutually exclusive with AUTH_PASSWORD and AUTH_USER.",
)
@validator("AUTH_TOKEN", always=True)defset_auth_token(cls, val, values: Dict):
"""Set TOKEN if USER & PASSWORD are supplied."""ifnotval:
ifall((values['AUTH_USER'], values['AUTH_PASSWORD'])):
returnf"{values['AUTH_USER']}:{values['AUTH_PASSWORD']}"raiseValueError(
"'AUTH_USER & AUTH_PASSWORD' or 'AUTH_TOKEN' must be set."
)
returnvalconfig=GlobalConfig()
test_config.py
import pytest
from pydantic import ValidationError
from _pytest.monkeypatch import MonkeyPatch
def test_user_password_token_set():
with pytest.raises(ValidationError):
from min_config import config
print(config)
def test_user_password_is_set(monkeypatch: MonkeyPatch):
monkeypatch.setenv("AUTH_USER", "user")
monkeypatch.setenv("AUTH_PASSWORD", "password")
from min_config import config
assert config.AUTH_TOKEN == "user:password"
With my current setup config is instantiated every time I import it, which makes it tricky to test.
On top of that, I'm getting the error if both test functions run, if one of them is removed it works fine.
pydantic.errors.ConfigError: duplicate validator function "min_config.GlobalConfig.set_auth_token"; if this is intended, set `allow_reuse=True`
pydantic/class_validators.py:144: ConfigError
Can anyone help me please how to can I test BaseSettings I browsed the internet and it seems to be a more general problem and suggested solutions were not very helpful.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hello, I'm using BaseSettings and I'd like to test the validators.
I use settings in another module as described here: https://fastapi.tiangolo.com/advanced/settings/#settings-in-another-module (I'm not using FastAPI though)
Here is my setup:
min_config.py
test_config.py
With my current setup
config
is instantiated every time I import it, which makes it tricky to test.On top of that, I'm getting the error if both test functions run, if one of them is removed it works fine.
Can anyone help me please how to can I test
BaseSettings
I browsed the internet and it seems to be a more general problem and suggested solutions were not very helpful.Thank you!
Beta Was this translation helpful? Give feedback.
All reactions