Challenge - 5 Problems
Monkeypatch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of monkeypatch.setattr on a function attribute
What will be the output of this pytest test function when monkeypatch.setattr is used to replace a function?
PyTest
def greet(): return "Hello" def test_greet(monkeypatch): def fake_greet(): return "Hi" monkeypatch.setattr(__name__, "greet", fake_greet) result = greet() print(result)
Attempts:
2 left
💡 Hint
Think about what monkeypatch.setattr does to the function greet inside the test.
✗ Incorrect
monkeypatch.setattr replaces the greet function with fake_greet during the test, so calling greet() returns 'Hi'.
❓ assertion
intermediate2:00remaining
Correct assertion after monkeypatch.setattr on an object attribute
Given this code, which assertion correctly verifies the monkeypatched attribute value?
PyTest
class User: active = True def test_user_active(monkeypatch): monkeypatch.setattr(User, "active", False) user = User() # Which assertion is correct here?
Attempts:
2 left
💡 Hint
monkeypatch.setattr changes the attribute value on the class User.
✗ Incorrect
monkeypatch.setattr sets User.active to False, so user.active will also be False.
🔧 Debug
advanced2:00remaining
Identify the error in monkeypatch.setattr usage
What error will this test raise when run with pytest?
PyTest
def test_patch(monkeypatch): import os monkeypatch.setattr(os.path, "exists", lambda x: True) print(os.path.exists("anyfile.txt"))
Attempts:
2 left
💡 Hint
Check the first argument to monkeypatch.setattr and what it expects.
✗ Incorrect
monkeypatch.setattr expects a module, class, or instance as first argument, not a string.
🧠 Conceptual
advanced2:00remaining
Understanding monkeypatch.setattr scope and cleanup
Which statement about monkeypatch.setattr is TRUE regarding its effect and cleanup?
Attempts:
2 left
💡 Hint
Think about test isolation and why monkeypatch is useful.
✗ Incorrect
monkeypatch.setattr automatically reverts changes after the test to keep tests isolated.
❓ framework
expert3:00remaining
Best practice for monkeypatching a method in a class instance
You want to monkeypatch the method 'calculate' of an instance 'obj' of class 'Calculator' during a pytest test. Which code snippet correctly patches the method only for this test?
PyTest
class Calculator: def calculate(self, x): return x * 2 def test_calculate(monkeypatch): obj = Calculator() # Which monkeypatch code is correct here?
Attempts:
2 left
💡 Hint
Remember monkeypatch.setattr needs the object and attribute name as separate arguments.
✗ Incorrect
To patch a method on an instance, pass the instance and method name as arguments, then the replacement function.