Bird
Raised Fist0
PyTesttesting~10 mins

monkeypatch fixture in PyTest - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to patch the function using monkeypatch.

PyTest
def test_example(monkeypatch):
    def fake_return():
        return 42
    monkeypatch.[1]('module.function', fake_return)
    assert module.function() == 42
Drag options to blanks, or click blank then click option'
Apatch
Bsetattr
Creplace
Dmock
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'patch' which is from unittest.mock, not monkeypatch.
Using 'replace' which is not a valid monkeypatch method.
2fill in blank
medium

Complete the code to patch an environment variable using monkeypatch.

PyTest
def test_env(monkeypatch):
    monkeypatch.[1]('ENV_VAR', 'test_value')
    assert os.getenv('ENV_VAR') == 'test_value'
Drag options to blanks, or click blank then click option'
Asetenv
Bsetattr
Cpatchenv
Dmockenv
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'setattr' which patches attributes, not environment variables.
Using 'patchenv' which does not exist.
3fill in blank
hard

Fix the error in patching a dictionary key using monkeypatch.

PyTest
def test_dict(monkeypatch):
    config = {'key': 'original'}
    monkeypatch.[1](config, 'key', 'patched')
    assert config['key'] == 'patched'
Drag options to blanks, or click blank then click option'
Asetenv
Bsetattr
Cpatchitem
Dsetitem
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'setattr' which works on object attributes, not dict keys.
Using 'setenv' which is for environment variables.
4fill in blank
hard

Fill both blanks to patch a function and check its call count.

PyTest
def test_call_count(monkeypatch):
    calls = {'count': 0}
    def fake_func():
        calls['count'] += 1
    monkeypatch.[1]('module.func', fake_func)
    module.func()
    assert calls['count'] [2] 1
Drag options to blanks, or click blank then click option'
Asetattr
B==
C>=
Dsetitem
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'setitem' to patch a function (wrong for attributes).
Using '>=' instead of '==' for exact call count.
5fill in blank
hard

Fill all three blanks to patch environment, attribute, and dictionary key correctly.

PyTest
def test_all(monkeypatch):
    monkeypatch.[1]('ENV', 'value')
    class Obj:
        attr = 5
    obj = Obj()
    monkeypatch.[2](obj, 'attr', 10)
    data = {'key': 'old'}
    monkeypatch.[3](data, 'key', 'new')
    assert os.getenv('ENV') == 'value'
    assert obj.attr == 10
    assert data['key'] == 'new'
Drag options to blanks, or click blank then click option'
Asetenv
Bsetattr
Csetitem
Dpatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'patch' which is not a monkeypatch method.
Mixing up 'setattr' and 'setitem' for objects and dicts.

Practice

(1/5)
1. What is the primary purpose of the monkeypatch fixture in pytest?
easy
A. To temporarily replace parts of the code during tests
B. To permanently change the source code
C. To speed up the pytest installation
D. To generate test reports automatically

Solution

  1. Step 1: Understand monkeypatch usage

    The monkeypatch fixture is used to temporarily replace or modify parts of the code during test execution.
  2. Step 2: Differentiate temporary vs permanent changes

    It does not permanently change source code but only affects the test runtime environment.
  3. Final Answer:

    To temporarily replace parts of the code during tests -> Option A
  4. Quick Check:

    Temporary code replacement = B [OK]
Hint: Remember monkeypatch changes code only during tests [OK]
Common Mistakes:
  • Thinking monkeypatch changes code permanently
  • Confusing monkeypatch with test report tools
  • Assuming monkeypatch speeds up pytest installation
2. Which of the following is the correct way to use monkeypatch to replace a function get_data in a module my_module?
easy
A. monkeypatch.replace('my_module.get_data', lambda: 'mocked')
B. monkeypatch.setattr(my_module.get_data, lambda: 'mocked')
C. monkeypatch.setattr('my_module.get_data', lambda: 'mocked')
D. monkeypatch.patch('my_module.get_data', lambda: 'mocked')

Solution

  1. Step 1: Recall monkeypatch syntax

    The correct method to replace an attribute or function is monkeypatch.setattr(target, value) where target is a string path.
  2. Step 2: Identify correct target format

    The target must be a string like 'my_module.get_data', not the function object itself.
  3. Final Answer:

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

    Use setattr with string target = A [OK]
Hint: Use setattr with string path to replace functions [OK]
Common Mistakes:
  • Passing function object instead of string path
  • Using non-existent monkeypatch methods like replace or patch
  • Confusing monkeypatch with unittest.mock syntax
3. Given the code below, what will be the output of the test?
def get_value():
    return 10

def test_value(monkeypatch):
    monkeypatch.setattr('__main__.get_value', lambda: 5)
    assert get_value() == ?
medium
A. 10
B. 5
C. AssertionError
D. TypeError

Solution

  1. Step 1: Understand monkeypatch effect on get_value

    The monkeypatch replaces get_value in the __main__ module with a lambda returning 5.
  2. Step 2: Evaluate the assertion

    Calling get_value() now returns 5, so assert get_value() == 5 passes.
  3. Final Answer:

    5 -> Option B
  4. Quick Check:

    Patched function returns 5 = A [OK]
Hint: Patched function returns new value, not original [OK]
Common Mistakes:
  • Expecting original return value 10
  • Thinking monkeypatch causes error
  • Confusing module path for patching
4. What is wrong with this test code using monkeypatch?
def test_env(monkeypatch):
    monkeypatch.setenv('API_KEY')
    assert os.getenv('API_KEY') is None
medium
A. monkeypatch cannot patch environment variables
B. os.getenv cannot be used in tests
C. assertion should check for empty string, not None
D. setenv requires two arguments: key and value

Solution

  1. Step 1: Check monkeypatch.setenv usage

    The setenv method requires both a key and a value to set an environment variable.
  2. Step 2: Identify missing argument

    Here, only the key 'API_KEY' is given, missing the value argument.
  3. Final Answer:

    setenv requires two arguments: key and value -> Option D
  4. Quick Check:

    setenv needs key and value = C [OK]
Hint: Always provide key and value to setenv [OK]
Common Mistakes:
  • Calling setenv with only one argument
  • Assuming os.getenv is not usable in tests
  • Thinking monkeypatch can't patch env variables
5. You want to test a function that reads a config file using open. How can you use monkeypatch to avoid reading a real file and instead provide fake content?
hard
A. Use monkeypatch.setattr to replace builtins.open with a function returning a StringIO with fake data
B. Use monkeypatch.setenv to set a fake file path environment variable
C. Use monkeypatch.setitem to replace the file path in a dictionary
D. Use monkeypatch.delattr to delete the open function

Solution

  1. Step 1: Identify how to fake file reading

    Replacing open with a function returning a StringIO object simulates file reading without disk access.
  2. Step 2: Use monkeypatch.setattr on builtins.open

    Monkeypatch can replace builtins.open with a lambda or function returning StringIO containing fake content.
  3. Final Answer:

    Use monkeypatch.setattr to replace builtins.open with a function returning a StringIO with fake data -> Option A
  4. Quick Check:

    Patch open with StringIO = D [OK]
Hint: Patch builtins.open with StringIO for fake file content [OK]
Common Mistakes:
  • Trying to delete open instead of replacing it
  • Using setenv which doesn't fake file reading
  • Replacing dictionary keys instead of open function
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