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.
monkeypatch.setenv in 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.
API_KEY to 12345 for the test.monkeypatch.setenv('API_KEY', '12345')
/my/custom/path at the start of the PATH variable temporarily.monkeypatch.setenv('PATH', '/my/custom/path', prepend=True)
This test shows how monkeypatch.setenv changes the environment variable MY_VAR temporarily. It prints the original, new, and restored values.
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}')
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.
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.
Practice
What is the main purpose of monkeypatch.setenv in pytest?
Solution
Step 1: Understand the role of monkeypatch in pytest
Monkeypatch is used to temporarily modify or replace parts of the environment during tests without permanent effects.Step 2: Focus on setenv method
The setenv method specifically changes environment variables only for the duration of the test.Final Answer:
Temporarily change environment variables during a test -> Option CQuick Check:
monkeypatch.setenv = temporary env change [OK]
- Thinking setenv changes env variables permanently
- Confusing setenv with creating new system variables
- Assuming changes persist after test ends
Which of the following is the correct syntax to set an environment variable API_KEY to 12345 using monkeypatch.setenv in a pytest test function?
def test_api_key(monkeypatch):
# Your code here
assert ...Solution
Step 1: Check method signature of setenv
setenv takes two string arguments: the variable name and its value.Step 2: Identify correct string usage
The value must be a string, so '12345' is correct, not integer 12345.Final Answer:
monkeypatch.setenv('API_KEY', '12345') -> Option AQuick Check:
setenv('VAR', 'value') syntax [OK]
- Passing integer instead of string as value
- Using keyword arguments instead of positional
- Trying to assign value with '=' outside method call
What will be the output of the following pytest test?
import os
def test_env(monkeypatch):
monkeypatch.setenv('MODE', 'test')
mode = os.getenv('MODE')
assert mode == 'test'
print(mode)Solution
Step 1: Understand monkeypatch.setenv effect
It sets environment variable 'MODE' to 'test' temporarily during the test.Step 2: Check os.getenv call and assertion
os.getenv('MODE') returns 'test', so assertion passes and print outputs 'test'.Final Answer:
test -> Option DQuick Check:
setenv sets env var, getenv reads it [OK]
- Expecting None because env var not set globally
- Thinking assertion fails
- Confusing variable name with value
Identify the error in this pytest test using monkeypatch.setenv:
def test_path(monkeypatch):
monkeypatch.setenv(PATH)
assert os.getenv('PATH') == '/usr/bin'Solution
Step 1: Check setenv method call
setenv requires two arguments: variable name and value. Here only one argument is given.Step 2: Verify assertion and imports
Assertion syntax is correct and os module import is assumed; error is in setenv call.Final Answer:
setenv missing value argument -> Option BQuick Check:
setenv needs two args: name and value [OK]
- Calling setenv with only one argument
- Forgetting to import os module
- Miswriting assertion statement
You want to test a function that behaves differently based on the environment variable FEATURE_FLAG. Which pytest test code correctly uses monkeypatch.setenv to test the function with FEATURE_FLAG set to enabled and ensures the environment is restored after the test?
def test_feature(monkeypatch):
# Your code here
result = feature_function()
assert result == 'Feature Enabled'Solution
Step 1: Identify correct usage of monkeypatch.setenv
setenv requires two string arguments: variable name and value, passed positionally.Step 2: Understand environment restoration
Using monkeypatch.setenv ensures the env var is set only during the test and restored after, unlike direct os.environ assignment.Final Answer:
monkeypatch.setenv('FEATURE_FLAG', 'enabled') -> Option AQuick Check:
Use monkeypatch.setenv for temporary env changes [OK]
- Directly modifying os.environ without monkeypatch
- Using keyword arguments in setenv
- Trying to assign value outside setenv call
Ready to prove it?
Pass the test and this pattern moves unknown
