Daniel Roy Greenfeld: TIL: Set... Note

Daniel Roy Greenfeld: TIL: Setting environment variables for pytest

The pytest-env package facilitates setting environment variables for pytest tests in a manageable way. It avoids direct modification of os.environ, promoting cleaner and more predictable tests. Installation is straightforward using pip or uv package managers. Configuration is handled conveniently within the pyproject.toml file under the [tool.pytest_env] section. Define your desired environment variables and their values within this section. No additional code or configuration is needed in the tests themselves. When you run pytest, the environment variables are automatically set. This is particularly useful for testing code that relies on environment variables for configuration. It allows for testing against mock replies or test instances of services. Using pytest-env ensures tests operate in a controlled and isolated environment.