Bird
Raised Fist0
PyTesttesting~20 mins

Mock return values and side effects in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Mock Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this pytest mock with return_value?
Consider the following pytest test code using mock. What will be printed when the test runs?
PyTest
from unittest.mock import Mock

def fetch_data():
    return 'real data'

mock_fetch = Mock(return_value='mocked data')

result = mock_fetch()
print(result)
Amocked data
Breal data
CNone
DTypeError
Attempts:
2 left
💡 Hint
The mock object returns what you set as return_value when called.
❓ assertion
intermediate
2:00remaining
Which assertion correctly tests a mock's side effect raising an exception?
You have a mock object with side_effect set to raise a ValueError. Which assertion correctly verifies that calling the mock raises this error?
PyTest
from unittest.mock import Mock
import pytest

mock_func = Mock(side_effect=ValueError('error'))
A
with pytest.raises(ValueError):
    mock_func()
Bassert mock_func() == ValueError
Cassert mock_func.side_effect == ValueError
Dassert mock_func() raises ValueError
Attempts:
2 left
💡 Hint
Use pytest.raises context manager to check exceptions.
🔧 Debug
advanced
2:00remaining
Why does this mock side_effect list cause an error on the third call?
Examine the code below. What error occurs on the third call to mock_func and why?
PyTest
from unittest.mock import Mock

mock_func = Mock(side_effect=[1, 2])
print(mock_func())
print(mock_func())
print(mock_func())
AStopIteration because side_effect list is exhausted
BIndexError because list index out of range
CTypeError because side_effect is not callable
DNo error, prints 1, 2, None
Attempts:
2 left
💡 Hint
side_effect list acts like an iterator and raises StopIteration when empty.
🧠 Conceptual
advanced
2:00remaining
What is the difference between return_value and side_effect in mocks?
Choose the best explanation of how return_value and side_effect differ in mock objects.
Areturn_value sets the value returned by the mock; side_effect can be a function, exception, or iterable to control behavior
Breturn_value raises exceptions; side_effect returns fixed values
Creturn_value is used only for async mocks; side_effect only for sync mocks
Dreturn_value and side_effect are interchangeable and do the same thing
Attempts:
2 left
💡 Hint
Think about how you can simulate different behaviors with side_effect.
❓ framework
expert
3:00remaining
How to mock a function to return different values on consecutive calls in pytest?
You want to mock a function so that it returns 10 on the first call, 20 on the second, and then raises RuntimeError on the third call. Which mock setup achieves this?
Amock_func = Mock(side_effect=[10, 20, RuntimeError('fail')])
Bmock_func = Mock(side_effect=[10, 20, lambda: (_ for _ in ()).throw(RuntimeError('fail'))])
Cmock_func = Mock(side_effect=[10, 20, RuntimeError])
Dmock_func = Mock(return_value=[10, 20, RuntimeError('fail')])
Attempts:
2 left
💡 Hint
side_effect list can include values or callables; exceptions must be raised, not returned.

Practice

(1/5)
1. What does setting mock.return_value do in a pytest mock object?
easy
A. It delays the mock response by a set time.
B. It defines a fixed value that the mock returns when called.
C. It records the number of times the mock was called.
D. It raises an exception when the mock is called.

Solution

  1. Step 1: Understand the role of return_value

    The return_value attribute sets a fixed return value for the mock when it is called.
  2. Step 2: Differentiate from other mock features

    Unlike side_effect which can raise exceptions or return different values, return_value always returns the same fixed value.
  3. Final Answer:

    It defines a fixed value that the mock returns when called. -> Option B
  4. Quick Check:

    return_value = fixed return [OK]
Hint: return_value sets fixed output for mock calls [OK]
Common Mistakes:
  • Confusing return_value with side_effect
  • Thinking return_value raises exceptions
  • Assuming return_value tracks call count
2. Which of the following is the correct way to set a mock to raise an exception when called?
easy
A. mock.side_effect = Exception('Error')
B. mock.return_value = Exception('Error')
C. mock.raise_exception = Exception('Error')
D. mock.throw = Exception('Error')

Solution

  1. Step 1: Identify how to raise exceptions with mocks

    Setting side_effect to an exception causes the mock to raise that exception when called.
  2. Step 2: Check syntax correctness

    Only mock.side_effect = Exception('Error') is valid syntax to raise an exception on call.
  3. Final Answer:

    mock.side_effect = Exception('Error') -> Option A
  4. Quick Check:

    side_effect raises exceptions [OK]
Hint: Use side_effect to raise exceptions in mocks [OK]
Common Mistakes:
  • Using return_value to raise exceptions
  • Using non-existent attributes like raise_exception
  • Confusing syntax for exception raising
3. What will be the output of this pytest mock code?
from unittest.mock import Mock
mock = Mock()
mock.side_effect = [1, 2, 3]
print(mock())
print(mock())
print(mock())
medium
A. 1 2 3
B. [1, 2, 3] [1, 2, 3] [1, 2, 3]
C. None None None
D. Error on third call

Solution

  1. Step 1: Understand side_effect as a list

    When side_effect is a list, each call to the mock returns the next item in the list.
  2. Step 2: Trace each call output

    First call returns 1, second returns 2, third returns 3, so printed outputs are 1, 2, 3.
  3. Final Answer:

    1 2 3 -> Option A
  4. Quick Check:

    side_effect list returns items in order [OK]
Hint: side_effect list returns next item each call [OK]
Common Mistakes:
  • Expecting entire list returned each call
  • Confusing return_value with side_effect list
  • Assuming calls after list ends raise error
4. Identify the error in this pytest mock setup:
from unittest.mock import Mock
mock = Mock()
mock.side_effect = Exception('Fail')
mock.side_effect = [1, 2, 3]
print(mock())
medium
A. side_effect cannot be assigned twice
B. Exception object should be raised, not assigned to side_effect
C. The second assignment overwrites the first, no error occurs
D. Mock must be called before setting side_effect

Solution

  1. Step 1: Analyze multiple side_effect assignments

    The second assignment to side_effect replaces the first one; no error occurs.
  2. Step 2: Understand mock call behavior

    After setting side_effect = [1, 2, 3], the mock returns 1 on first call, so print(mock()) outputs 1.
  3. Final Answer:

    The second assignment overwrites the first, no error occurs -> Option C
  4. Quick Check:

    Last side_effect assignment wins [OK]
Hint: Last side_effect assignment replaces previous ones [OK]
Common Mistakes:
  • Thinking multiple side_effect assignments cause errors
  • Expecting exception to be raised immediately
  • Confusing assignment with raising exceptions
5. You want a mock to return 10 on the first call, raise a ValueError on the second, and return 20 on the third call. Which setup achieves this?
hard
A. mock.side_effect = [10, ValueError('bad'), 20]
B. mock.return_value = 10 mock.side_effect = ValueError('bad') mock.return_value = 20
C. mock.side_effect = lambda: [10, ValueError('bad'), 20]
D. mock.side_effect = [10, lambda: (_ for _ in ()).throw(ValueError('bad')), 20]

Solution

  1. Step 1: Understand side_effect list behavior

    When side_effect is a list, the mock returns successive items from the list on each call. Non-callable items like numbers or exception instances are returned directly.
  2. Step 2: Recognize exception raising in side_effect list

    Placing an exception instance directly returns it as a value, not raises it. To raise, use a generator expression that throws the exception.
  3. Step 3: Analyze options

    mock.side_effect = [10, ValueError('bad'), 20] returns the exception object instead of raising it. mock.side_effect = [10, lambda: (_ for _ in ()).throw(ValueError('bad')), 20] uses a generator expression to raise ValueError on second call, returning 10 and 20 on first and third calls respectively.
  4. Final Answer:

    mock.side_effect = [10, lambda: (_ for _ in ()).throw(ValueError('bad')), 20] -> Option D
  5. Quick Check:

    Use generator throw to raise exceptions in side_effect list [OK]
Hint: Use generator throw to raise exceptions in side_effect list [OK]
Common Mistakes:
  • Putting exception instance directly in side_effect list
  • Trying to set multiple return_values
  • Using lambda returning list instead of generator throw
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard