The monkeypatch fixture lets you change parts of your code during tests without changing the real code. It helps test tricky parts safely.
monkeypatch fixture in PyTest
def test_example(monkeypatch): monkeypatch.setattr(target, "name", new_value) monkeypatch.setenv("VAR_NAME", "value") monkeypatch.delattr(target, "name", raising=False)
monkeypatch is a special argument you add to your test function.
You can change attributes, environment variables, or delete attributes safely.
module.func with fake_func during the test.def test_replace_function(monkeypatch): def fake_func(): return "fake" monkeypatch.setattr("module.func", fake_func) assert module.func() == "fake"
API_KEY just for the test.def test_change_env(monkeypatch): monkeypatch.setenv("API_KEY", "12345") assert os.getenv("API_KEY") == "12345"
def test_remove_attribute(monkeypatch): monkeypatch.delattr("module.Class.attr", raising=False) assert not hasattr(module.Class, "attr")
This test uses monkeypatch to set and delete an environment variable API_KEY. It checks that get_api_key() returns the right value depending on the environment.
import os def get_api_key(): return os.getenv("API_KEY", "no-key") def test_api_key(monkeypatch): monkeypatch.setenv("API_KEY", "test123") assert get_api_key() == "test123" monkeypatch.delenv("API_KEY", raising=False) assert get_api_key() == "no-key"
Always use monkeypatch inside tests to avoid changing real code or environment.
Changes made by monkeypatch last only during the test and are undone automatically.
Use raising=False to avoid errors if the attribute or env variable does not exist.
monkeypatch helps change code or environment safely during tests.
It is useful to replace functions, set environment variables, or remove attributes temporarily.
Changes are only for the test and do not affect other tests or real code.
Practice
monkeypatch fixture in pytest?Solution
Step 1: Understand monkeypatch usage
The monkeypatch fixture is used to temporarily replace or modify parts of the code during test execution.Step 2: Differentiate temporary vs permanent changes
It does not permanently change source code but only affects the test runtime environment.Final Answer:
To temporarily replace parts of the code during tests -> Option AQuick Check:
Temporary code replacement = B [OK]
- Thinking monkeypatch changes code permanently
- Confusing monkeypatch with test report tools
- Assuming monkeypatch speeds up pytest installation
monkeypatch to replace a function get_data in a module my_module?Solution
Step 1: Recall monkeypatch syntax
The correct method to replace an attribute or function ismonkeypatch.setattr(target, value)where target is a string path.Step 2: Identify correct target format
The target must be a string like 'my_module.get_data', not the function object itself.Final Answer:
monkeypatch.setattr('my_module.get_data', lambda: 'mocked') -> Option CQuick Check:
Use setattr with string target = A [OK]
- Passing function object instead of string path
- Using non-existent monkeypatch methods like replace or patch
- Confusing monkeypatch with unittest.mock syntax
def get_value():
return 10
def test_value(monkeypatch):
monkeypatch.setattr('__main__.get_value', lambda: 5)
assert get_value() == ?Solution
Step 1: Understand monkeypatch effect on get_value
The monkeypatch replacesget_valuein the__main__module with a lambda returning 5.Step 2: Evaluate the assertion
Callingget_value()now returns 5, soassert get_value() == 5passes.Final Answer:
5 -> Option BQuick Check:
Patched function returns 5 = A [OK]
- Expecting original return value 10
- Thinking monkeypatch causes error
- Confusing module path for patching
def test_env(monkeypatch):
monkeypatch.setenv('API_KEY')
assert os.getenv('API_KEY') is NoneSolution
Step 1: Check monkeypatch.setenv usage
Thesetenvmethod requires both a key and a value to set an environment variable.Step 2: Identify missing argument
Here, only the key 'API_KEY' is given, missing the value argument.Final Answer:
setenv requires two arguments: key and value -> Option DQuick Check:
setenv needs key and value = C [OK]
- Calling setenv with only one argument
- Assuming os.getenv is not usable in tests
- Thinking monkeypatch can't patch env variables
open. How can you use monkeypatch to avoid reading a real file and instead provide fake content?Solution
Step 1: Identify how to fake file reading
Replacingopenwith a function returning a StringIO object simulates file reading without disk access.Step 2: Use monkeypatch.setattr on builtins.open
Monkeypatch can replacebuiltins.openwith a lambda or function returning StringIO containing fake content.Final Answer:
Use monkeypatch.setattr to replace builtins.open with a function returning a StringIO with fake data -> Option AQuick Check:
Patch open with StringIO = D [OK]
- Trying to delete open instead of replacing it
- Using setenv which doesn't fake file reading
- Replacing dictionary keys instead of open function
Ready to prove it?
Pass the test and this pattern moves unknown
