How to Test Environment Variables with pytest monkeypatch in Python
Shows how to use pytest's monkeypatch fixture to set and delete environment variables for isolated tests.
pip install pytest
Python code
13 linesimport os
import pytest
def get_database_url():
return os.getenv("DATABASE_URL", "postgres://default")
def test_database_url_with_env(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgres://test-db")
assert get_database_url() == "postgres://test-db"
def test_database_url_default(monkeypatch):
monkeypatch.delenv("DATABASE_URL", raising=False)
assert get_database_url() == "postgres://default"
Output
Run the snippet in the editor to inspect the return value or side effect.
How it works
The monkeypatch fixture automatically reverts changes after each test, keeping tests isolated. monkeypatch.setenv sets an environment variable for the duration of the test, while monkeypatch.delenv removes it. The code under test reads the variable with os.getenv, which returns the default if unset. This pattern makes it easy to test behavior under different configurations without touching the real environment.
Common mistakes
- Forgetting to use `raising=False` with `delenv` to avoid errors when the variable doesn't exist
- Not using the monkeypatch fixture, relying on manual `os.environ` cleanup that can leak state between tests
Variations
- Use `monkeypatch.setenv` with a lambda for dynamic values
- Use `monkeypatch.setitem` on `os.environ` directly
Real-world use cases
- Testing configuration loading functions that depend on environment variables.
- Simulating different deployment environments (prod, staging) in integration tests.
- Ensuring default values are used when environment variables are missing.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.