0
0
PyTesttesting~5 mins

Mock return values and side effects in PyTest - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a mock return value in pytest?
A mock return value is a preset value that a mocked function returns when called during a test. It helps simulate behavior without running the real code.
Click to reveal answer
intermediate
What does the side_effect attribute do in a pytest mock?
The side_effect attribute lets you define custom behavior for a mock, like raising exceptions or returning different values on each call.
Click to reveal answer
intermediate
How do you set a mock to return different values on consecutive calls?
Use side_effect with a list of values. Each call to the mock returns the next value in the list.
Click to reveal answer
beginner
Example: What will this mock return on the first and second call?
mocked_function.side_effect = [10, 20]
On the first call, it returns 10. On the second call, it returns 20. After that, it raises StopIteration.
Click to reveal answer
intermediate
Why use side_effect to raise an exception in a mock?
To test how your code handles errors without causing real failures. It simulates exceptions from dependencies.
Click to reveal answer
In pytest, how do you set a mock to always return the value 5?
Amock.return_value = 5
Bmock.side_effect = 5
Cmock.return = 5
Dmock.value = 5
What happens if side_effect is set to a list of values?
AThe mock returns values from the list on each call, then raises StopIteration.
BThe mock always returns the whole list.
CThe mock raises an exception immediately.
DThe mock ignores the list and returns None.
How can you simulate an exception being raised by a mock?
ASet side_effect to the exception class or instance.
BSet return_value to the exception.
CCall mock.raise_exception()
DSet mock.error = True
Which attribute would you use to make a mock return different values on multiple calls?
Aside_effect
Breturn_value
Ccall_count
Dmock_values
If you want a mock to behave like a function that sometimes raises an error, what should you do?
AUse side_effect with a function that raises the error conditionally.
BSet return_value to None.
CSet side_effect to a list of only values.
DUse return_value with an error message.
Explain how to use mock return_value and side_effect in pytest to control mock behavior.
Think about how to simulate normal and error cases with mocks.
You got /4 concepts.
    Describe a real-life scenario where you would use side_effect to raise an exception in a mock.
    Imagine testing how your app reacts when a service is down.
    You got /4 concepts.