What is the purpose of the monkeypatch fixture in pytest?
The monkeypatch fixture allows you to safely modify or replace attributes, dictionaries, environment variables, or functions during a test, without affecting other tests.
Click to reveal answer
beginner
How do you use monkeypatch to change an environment variable in a test?
Use monkeypatch.setenv('VAR_NAME', 'value') to set or change an environment variable temporarily during the test.
Click to reveal answer
beginner
What happens to changes made by monkeypatch after the test finishes?
All changes made by monkeypatch are automatically undone after the test, restoring the original state to avoid side effects on other tests.
Click to reveal answer
intermediate
Show an example of using monkeypatch to replace a function during a test.
Why is monkeypatch preferred over directly modifying global variables or functions in tests?
Because monkeypatch safely isolates changes to the test scope and automatically reverts them, preventing unexpected side effects and making tests more reliable.
Click to reveal answer
What does monkeypatch.setattr() do in pytest?
ARuns a test multiple times
BReplaces an attribute or function temporarily during a test
CPermanently changes a function in the codebase
DSkips a test
✗ Incorrect
monkeypatch.setattr() temporarily replaces an attribute or function only during the test, then restores it after.
How does monkeypatch affect environment variables during a test?
AIt permanently changes them
BIt copies environment variables to a file
CIt ignores environment variables
DIt temporarily sets or deletes them for the test duration
✗ Incorrect
monkeypatch.setenv() and monkeypatch.delenv() temporarily modify environment variables only during the test.
What happens if you forget to use monkeypatch and modify globals directly in tests?
AOther tests may fail due to leftover changes
BTests run faster
CNothing, tests are isolated automatically
DThe test framework will fix it
✗ Incorrect
Direct global changes can cause side effects, making other tests fail unpredictably.
Which of these is NOT a feature of monkeypatch?
ATemporarily replace functions or attributes
BModify environment variables temporarily
CAutomatically generate test data
DAutomatically undo changes after test
✗ Incorrect
monkeypatch does not generate test data; it only modifies code or environment temporarily.
How do you use monkeypatch in a pytest test function?
AAdd <code>monkeypatch</code> as a parameter to the test function
BImport and call <code>monkeypatch()</code> inside the test
CUse a decorator <code>@monkeypatch</code>
DCall <code>pytest.monkeypatch()</code> globally
✗ Incorrect
pytest injects the monkeypatch fixture when you add it as a parameter to your test function.
Explain how the monkeypatch fixture helps keep tests isolated and reliable.
Think about how changing something only during a test helps avoid problems.
You got /3 concepts.
Describe a scenario where you would use monkeypatch.setattr() in a test.
Imagine you want to test code that calls a function you can't or don't want to run.
You got /3 concepts.
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
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 A
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
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.
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 C
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?
Step 1: Understand monkeypatch effect on get_value
The monkeypatch replaces get_value in the __main__ module with a lambda returning 5.
Step 2: Evaluate the assertion
Calling get_value() now returns 5, so assert get_value() == 5 passes.
Final Answer:
5 -> Option B
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
Step 1: Check monkeypatch.setenv usage
The setenv method 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 D
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
Step 1: Identify how to fake file reading
Replacing open with a function returning a StringIO object simulates file reading without disk access.
Step 2: Use monkeypatch.setattr on builtins.open
Monkeypatch can replace builtins.open with 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 A
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 unknownstrongwhile earning +1 Grip toward your certificate.