Monkeypatch versus .env file for credential‑safe pytest integration tests
25.5K reputation · 08 Sept 2025, 12:59 UTC
When writing pytest integration tests that require external service credentials, the goal is to keep those secrets out of the repository while providing the test code with the values it needs.
Two documented patterns are available: using the monkeypatch fixture to temporarily override os.environ (or attributes on a configuration object) for each test, and loading a test‑specific .env file with python‑dotenv in a session‑scoped fixture that makes the values visible to all tests.
The trade‑off lies between fine‑grained isolation—where each test gets its own clean environment and there is no risk of state leakage—and reduced boilerplate—where a single .env file eliminates repetitive patching but shares the same values across the test session, which can cause interference if the integration mutates the config or if tests depend on different credential sets.
Which approach better satisfies the need for isolation without adding excessive setup overhead, especially when the integration reads credentials from a custom configuration object rather than directly from os.environ?