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?✗ 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?✗ 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?✗ Incorrect
Direct global changes can cause side effects, making other tests fail unpredictably.
Which of these is NOT a feature of
monkeypatch?✗ Incorrect
monkeypatch does not generate test data; it only modifies code or environment temporarily.
How do you use
monkeypatch in a pytest test function?✗ 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.