How To Set Environment Variables In Pytest
Define Env Vars In The Test (Basic)
The most basic and straightforward way is to define the environment variables in your test file or within the test itself.
tests/test_env_vars.py
While easy to understand, this method is
-
Ugly
-
Not scalable (imagine you had 100s of env variables)
-
Not reusable (imagine you had 100s of tests).
Use The python-dotenv or pytest-dotenv Package (Better)
The python-dotenv package is a popular way to define environment variables in a .env file and load them into your code.
tests/.env
DEPLOYMENT_STAGE=dev
API_ENDPOINT=https://api.dev.example.com
ACCOUNT_ID=987654321
Use The pytest-env Package (Best)
The pytest-env package is a great way to define Environment Variables within your pytest.ini or pyproject.toml config file.
tests/pytest.ini
[pytest]
env =
DEPLOYMENT_STAGE=staging
API_ENDPOINT=https://api.staging.example.com
ACCOUNT_ID=56789
Instead of pytest.ini, you can also define these in a pyproject.toml file.
[tool.pytest.ini_options]
env = [
"HOME=~/tmp",
"RUN_ENV=test",
]