We use monkeypatch.setenv to temporarily change environment variables during tests. This helps us test how code behaves with different settings without changing the real environment.
0
0
monkeypatch.setenv in PyTest
Introduction
When you want to test how your code reacts to different environment variables.
When you need to simulate missing or changed environment variables in a test.
When you want to avoid changing your system's real environment variables during testing.
When testing code that reads configuration from environment variables.
When you want isolated tests that do not affect each other or the system.
Syntax
PyTest
monkeypatch.setenv(name, value, prepend=False)name is the environment variable name as a string.
value is the new value to set for that variable.
Examples
Sets the environment variable
API_KEY to 12345 for the test.PyTest
monkeypatch.setenv('API_KEY', '12345')
Adds
/my/custom/path at the start of the PATH variable temporarily.PyTest
monkeypatch.setenv('PATH', '/my/custom/path', prepend=True)
Sample Program
This test shows how monkeypatch.setenv changes the environment variable MY_VAR temporarily. It prints the original, new, and restored values.
PyTest
import os def test_env(monkeypatch): # Before patching original_value = os.getenv('MY_VAR') # Set environment variable temporarily monkeypatch.setenv('MY_VAR', 'test_value') # Check the new value new_value = os.getenv('MY_VAR') # Assert the value changed assert new_value == 'test_value' # After test, environment is restored monkeypatch.undo() restored_value = os.getenv('MY_VAR') print(f'Original: {original_value}') print(f'New: {new_value}') print(f'Restored: {restored_value}')
OutputSuccess
Important Notes
monkeypatch automatically restores changes after the test ends, so no permanent changes happen.
Use monkeypatch.setenv inside test functions that accept the monkeypatch fixture.
Calling monkeypatch.undo() manually can restore changes early if needed.
Summary
monkeypatch.setenv lets you change environment variables safely during tests.
It helps test different scenarios without affecting your real system.
Changes are temporary and automatically cleaned up after each test.