Noro
Noro

Reputation: 41

Unable to patch pydentic settings for unit tests- getting wrong values

I'm use a Pydentic settings object in my project which I populate from a .env file. I'm trying to use it during unit tests with a different .env file called .test.env and I'm getting a behaviour I can't understand.

setting.py

class Settings(BaseSettings):
   a: str | None = None
   b str | None = None
   
def get_settings():
    return Settings()

def get_settings_override():
    return Settings(_env_file=".test.env")
.env
a=a
b=b
.test.env
a=a_test
b=b_test

conftest.py (also tried with monekypatch)

@pytest.fixture(scope="session", autouse=True)
def override_settings():
    with patch("project.setting.get_settings", new=get_settings_override):
        yield

I followed this doc loading a different env file: https://docs.pydantic.dev/latest/concepts/pydantic_settings/ for

However I keep getting values from .env file instead of .test.env. At first I thought it happens because I import the settings module before the fixture but in get_settings and get_settings override I create a new instance so I'm not sure how it's related.

In addition I tried just instantiating settings in a script and I still get the wrong values

def main():
    settings = get_settings_override() # returns .env values instead of .test.env

if __name__ == "__main__":
    main()

The only way I can get the values from .test.env is when I delete my .env file (and restart the IDE which I don't get how it can affect this). Other then that I keep getting the .env values

So, I want to patch the pydentic settings object for unit tests with a different env file other then .env and I'm getting the values from the wrong file. How can I achieve that?

Upvotes: 0

Views: 128

Answers (0)

Related Questions