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.
Asked: 2023-07-14 01:19:38 +0000
Seen: 14 times
Last updated: Jul 14 '23