0
0
PyTesttesting~5 mins

monkeypatch.setattr in PyTest - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is monkeypatch.setattr used for in pytest?
<p><code>monkeypatch.setattr</code> temporarily replaces an attribute or method in a module or class during a test. It helps simulate different behaviors without changing the real code.</p>
Click to reveal answer
beginner
How does monkeypatch.setattr help in testing functions that depend on external resources?

It allows you to replace calls to external resources (like APIs or databases) with fake functions or values. This makes tests faster and more reliable by avoiding real external calls.

Click to reveal answer
beginner
Example: What does this code do?<br>
monkeypatch.setattr('os.path.exists', lambda path: True)

This replaces the os.path.exists function with a fake one that always returns True. So, any code checking if a file exists will think it does.

Click to reveal answer
intermediate
What happens to the original attribute after the test using monkeypatch.setattr finishes?

The original attribute is restored automatically after the test ends. This keeps tests isolated and prevents side effects on other tests.

Click to reveal answer
intermediate
Can monkeypatch.setattr be used to patch instance attributes as well as module-level functions?

Yes, it can patch both instance attributes and module-level functions or variables by specifying the target correctly.

Click to reveal answer
What does monkeypatch.setattr do in pytest?
ARuns tests in parallel
BPermanently changes the source code
CTemporarily replaces an attribute or method during a test
DGenerates test reports
After using monkeypatch.setattr, what happens to the original attribute after the test ends?
AIt is restored automatically
BIt is deleted
CIt causes an error
DIt stays replaced
Which of these is a good use case for monkeypatch.setattr?
AReplacing a function that calls an external API with a fake one
BChanging the Python interpreter version
CModifying test runner settings
DWriting new test cases
How do you specify the target to patch with monkeypatch.setattr?
ABy creating a new test file
BBy editing the source code file
CBy running a shell command
DBy giving the full import path as a string or the object and attribute name
Can monkeypatch.setattr patch instance attributes?
ANo, only module-level functions
BYes, if the target is specified correctly
COnly for classes, not instances
DOnly for built-in types
Explain how monkeypatch.setattr helps in writing tests that avoid calling real external services.
Think about how you can fake parts of your code during tests.
You got /4 concepts.
    Describe the steps to use monkeypatch.setattr to replace a method in a module for a test.
    Focus on how you specify what to patch and what to replace it with.
    You got /4 concepts.