Bird
Raised Fist0
PyTesttesting~20 mins

monkeypatch.setattr in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Monkeypatch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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)
AHi
BHello
CAttributeError
DTypeError
Attempts:
2 left
💡 Hint
Think about what monkeypatch.setattr does to the function greet inside the test.
❓ assertion
intermediate
2: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?
Aassert user.active is False
Bassert User.active is True
Cassert user.active is True
Dassert User.active is None
Attempts:
2 left
💡 Hint
monkeypatch.setattr changes the attribute value on the class User.
🔧 Debug
advanced
2: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"))
ANameError: name 'os' is not defined
BPrints True
CTypeError: setattr() arg 1 must be module, class, or instance
DAttributeError: module 'os' has no attribute 'path'
Attempts:
2 left
💡 Hint
Check the first argument to monkeypatch.setattr and what it expects.
🧠 Conceptual
advanced
2:00remaining
Understanding monkeypatch.setattr scope and cleanup
Which statement about monkeypatch.setattr is TRUE regarding its effect and cleanup?
AChanges made by monkeypatch.setattr persist after the test finishes
Bmonkeypatch.setattr permanently deletes the original attribute
Cmonkeypatch.setattr only affects the patched attribute during the test and reverts after
Dmonkeypatch.setattr requires manual cleanup to restore original attributes
Attempts:
2 left
💡 Hint
Think about test isolation and why monkeypatch is useful.
❓ framework
expert
3: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?
Amonkeypatch.setattr(obj.calculate, lambda x: 42)
Bmonkeypatch.setattr(Calculator, "calculate", lambda self, x: 42)
Cmonkeypatch.setattr("Calculator", "calculate", lambda self, x: 42)
Dmonkeypatch.setattr(obj, "calculate", lambda x: 42)
Attempts:
2 left
💡 Hint
Remember monkeypatch.setattr needs the object and attribute name as separate arguments.

Practice

(1/5)
1. What is the main purpose of monkeypatch.setattr in pytest?
easy
A. To temporarily replace an attribute or function during a test
B. To permanently change code in the source files
C. To skip a test function
D. To run tests in parallel

Solution

  1. Step 1: Understand monkeypatch.setattr usage

    It is used to temporarily replace or modify attributes or functions during a test to isolate behavior.
  2. Step 2: Differentiate from other pytest features

    It does not permanently change code or skip tests; it only affects the test scope temporarily.
  3. Final Answer:

    To temporarily replace an attribute or function during a test -> Option A
  4. Quick Check:

    Temporary replacement = A [OK]
Hint: Think 'temporary change' during test only [OK]
Common Mistakes:
  • Confusing temporary patching with permanent code changes
  • Thinking it skips tests
  • Assuming it runs tests in parallel
2. Which of the following is the correct syntax to patch the function get_data in module my_module using monkeypatch in pytest?
easy
A. monkeypatch.setattr('get_data', my_module, lambda: 42)
B. monkeypatch.setattr('my_module.get_data', lambda: 42)
C. monkeypatch.setattr(my_module, 'get_data', lambda: 42)
D. monkeypatch.setattr('my_module', 'get_data', 42)

Solution

  1. Step 1: Identify correct monkeypatch.setattr signature

    The correct usage is monkeypatch.setattr(target_object, attribute_name, new_value).
  2. Step 2: Match parameters to patch get_data function

    We pass the module object my_module, the attribute name 'get_data', and the replacement function lambda: 42.
  3. Final Answer:

    monkeypatch.setattr(my_module, 'get_data', lambda: 42) -> Option C
  4. Quick Check:

    Object, attribute, new value = A [OK]
Hint: Pass object, attribute name, then new value [OK]
Common Mistakes:
  • Passing attribute as a string path instead of object and attribute
  • Swapping parameters order
  • Passing value instead of function for patching
3. Given the code below, what will be the output of the test?
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)
medium
A. None
B. Original value from my_module.get_value()
C. AttributeError
D. 10

Solution

  1. Step 1: Understand monkeypatch effect on get_value

    The original my_module.get_value is replaced temporarily by fake_func which returns 10.
  2. Step 2: Evaluate the call and print output

    Calling my_module.get_value() inside the test calls fake_func(), so it prints 10.
  3. Final Answer:

    10 -> Option D
  4. Quick Check:

    Patched function returns 10 [OK]
Hint: Patched function output replaces original during test [OK]
Common Mistakes:
  • Expecting original function output instead of patched
  • Thinking patch is permanent outside test
  • Assuming print outputs None
4. What is wrong with the following pytest test using monkeypatch?
def test_example(monkeypatch):
    monkeypatch.setattr('os.path.exists', lambda x: True)
    assert os.path.exists('anyfile.txt') == True
medium
A. The lambda function should accept no arguments
B. The first argument to setattr should be the module object, not a string
C. os.path.exists cannot be patched
D. The assert statement is incorrect

Solution

  1. Step 1: Check monkeypatch.setattr usage

    The first argument must be the module or object, not a string path.
  2. Step 2: Identify correct usage

    It should be monkeypatch.setattr(os.path, 'exists', lambda x: True) to patch the function properly.
  3. Final Answer:

    The first argument to setattr should be the module object, not a string -> Option B
  4. Quick Check:

    Object, not string path = B [OK]
Hint: Pass object, not string path, as first argument [OK]
Common Mistakes:
  • Passing string path instead of module object
  • Incorrect lambda parameters
  • Assuming some functions cannot be patched
5. You want to test a function 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'?
hard
A. Define a fake function returning a mock object, then patch with monkeypatch.setattr(requests, 'get', fake_func)
B. Patch requests.get with a string 'mock' using monkeypatch.setattr
C. Use monkeypatch.setattr('requests.get', fake_func) with a lambda returning 200
D. Replace fetch_data with a fake function instead of patching requests.get

Solution

  1. Step 1: Create a fake function returning a mock response

    Define a function that returns an object with status_code=200 and text='OK'.
  2. Step 2: Patch requests.get with monkeypatch.setattr

    Use monkeypatch.setattr(requests, 'get', fake_func) to replace the real HTTP call during the test.
  3. Final Answer:

    Define a fake function returning a mock object, then patch with monkeypatch.setattr(requests, 'get', fake_func) -> Option A
  4. Quick Check:

    Patch requests.get with fake function = D [OK]
Hint: Patch requests.get with a fake function returning mock response [OK]
Common Mistakes:
  • Passing string path instead of module object
  • Patching with wrong types like strings
  • Replacing the wrong function instead of requests.get
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard