@David Maze Thanks for the response, I am not fully understanding how this works. Can you give me some more advice?
For more context I am using a streamlit app.
Here's what I am trying:
Remove code, settings = Settings() remove from settings.py
Add code settings = Settings() to config.py
Make modules import from config from .config import settings
This will make sure settings are declared once, prevent side effects of Settings() being ran every time I import settings.py, and I can patch it in Pytest.
So here would be the the new implementation based on what you said...
# settings.py
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import Field
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
)
env_var: str = Field(description="blah blah blah")
# ...
env_var_d: str = Field(description="blah blah blah")
# config.py
from .settings import Settings
def get_settings()
return Settings()
# some_module.py
from .config import get_settings
def some_func()
settings = get_settings()
# conftest.py
import pytest
from .settings import Settings
from unittest.mock import patch
# Does not work as expected
@pytest.fixture(autouse=True, scope="session")
def settings():
with patch('pckg.config.get_settings', Settings(_env_file=".env.test")):
yield