0
0
PyTesttesting~5 mins

monkeypatch fixture in PyTest - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
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.
Example:<br><pre>def fake_func():
    return 'fake'

import module

def test_func(monkeypatch):
    monkeypatch.setattr(module, 'func', fake_func)
    assert module.func() == 'fake'</pre>
Click to reveal answer
intermediate
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
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
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
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
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
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.