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.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 12 views 0 copies

Requires third-party packages — install first
pip install pytest

Python code

13 lines
Python 3.9+
import 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

stdout
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

  1. Use `monkeypatch.setenv` with a lambda for dynamic values
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Testing & modern typing

Related tutorials and quizzes for this topic.