Automate patching an attribute using monkeypatch.setattr in pytest
Preconditions (2)
✅ Expected Result: The test passes confirming the attribute was successfully patched and the function behaves as expected
import pytest # Original module with function to patch class MyClass: def method(self): return "original value" def function_under_test(obj): return obj.method() # Test function using monkeypatch def test_function_under_test(monkeypatch): # Define a dummy method to replace the original def dummy_method(): return "patched value" # Patch the method attribute of MyClass instance monkeypatch.setattr(MyClass, "method", dummy_method) obj = MyClass() result = function_under_test(obj) # Assert the patched method is used assert result == "patched value"
This test uses pytest's monkeypatch fixture to replace the method of MyClass with a dummy function that returns a fixed string.
When function_under_test calls obj.method(), it gets the patched return value instead of the original.
The assertion checks that the patch worked by verifying the returned string is the patched one.
This approach isolates the test from the original method implementation, allowing controlled testing.
Now add data-driven testing to patch different methods with different return values
monkeypatch.setattr in pytest?get_data in module my_module using monkeypatch in pytest?my_module, the attribute name 'get_data', and the replacement function lambda: 42.import my_module
def test_func(monkeypatch):
def fake_func():
return 10
monkeypatch.setattr(my_module, 'get_value', fake_func)
result = my_module.get_value()
print(result)my_module.get_value is replaced temporarily by fake_func which returns 10.my_module.get_value() inside the test calls fake_func(), so it prints 10.def test_example(monkeypatch):
monkeypatch.setattr('os.path.exists', lambda x: True)
assert os.path.exists('anyfile.txt') == Truemonkeypatch.setattr(os.path, 'exists', lambda x: True) to patch the function properly.fetch_data() that calls requests.get. How can you use monkeypatch.setattr to replace requests.get with a fake function that returns a mock response with status_code=200 and text='OK'?status_code=200 and text='OK'.monkeypatch.setattr(requests, 'get', fake_func) to replace the real HTTP call during the test.Pass the test and this pattern moves unknown