TIL: Setting environment variables for pytest
Briefly

TIL: Setting environment variables for pytest
"When writing tests in pytest, often there's a need to set environment variables for your tests. Instead of modifying `os.environ` directly, which can lead to side effects and make tests harder to manage, here's how to do it with the [pytest-env](https://pypi.org/project/pytest-env/) package. First, install the package. ```sh pip install pytest-env # classic but works great uv add pytest-env # if you're one of us cool kids using uv uv add pytest-env --group test # if you use a specific test group of dependencies ```"
"A lot of people use `pytest.ini` to configure pytest, but I prefer using `pyproject.toml` for a more modern approach. Here's how you can set environment variables in `pyproject.toml`: ```toml [tool.pytest_env] # Test value for the SUPER_SECRET_KEY environment variable SUPER_SECRET_KEY = "ABC123" ``` Then run your tests just like you would normally do, and now the environment variable will be picked up by whatever test or code is looking for it. That's correct, you don't need to do any further configuration."
Use the pytest-env package to set environment variables for pytest tests instead of modifying os.environ directly to avoid side effects and improve test isolation. Install pytest-env via pip or alternative package managers. Configure environment variables declaratively in pyproject.toml under [tool.pytest_env], for example setting SUPER_SECRET_KEY = "ABC123". Run pytest normally and the configured environment variables will be available to tests and code. This approach ensures controlled test environments for SDKs that read configuration from environment variables and supports running tests with mock responses or against test instances.
Read at daniel.feldroy.com
Unable to calculate read time
[
|
]