Ask Your Question
3

How can one disregard a .env file while running tests with pytest when using Pydantic settings management and FastAPI?

asked 2023-07-14 01:19:38 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-14 01:23:02 +0000

qstack gravatar image

To disregard a .env file while running tests with pytest when using Pydantic settings management and FastAPI, you can use the env_override parameter while initializing the Settings class.

For example:

from pydantic import BaseSettings

class Settings(BaseSettings):
    api_key: str

    class Config:
        env_file = ".env"
        env_override = True

settings = Settings()

# Use the `env_override` parameter to override the `.env` file during tests
if __name__ == "__main__":
    import uvicorn
    uvicorn.run("myapp:app", host="0.0.0.0", port=8000, reload=True)

Then, in your pytest configuration, you can set an environment variable to override the .env file:

import os
from myapp.settings import Settings

def pytest_configure(config):
    config.addinivalue_line("markers", "integration: mark test as integration")
    settings = Settings(env_file="./.env.test", env_override=True)
    os.environ["API_KEY"] = settings.api_key

In this example, a .env.test file is used to set the environment variables for testing, and env_override is set to True to override the .env file. Finally, the API_KEY variable is set to the value in the settings object using os.environ.

This way, your tests will run with the API_KEY environment variable set to the value in the .env.test file, while disregarding the values from the .env file.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-14 01:19:38 +0000

Seen: 14 times

Last updated: Jul 14 '23