How to use unittest mock side_effect with a sequence in Python
Demonstrates using Mock.side_effect with a list to return different values per call and raise an exception at a specific call in unittest.
Python code
18 linesimport unittest
from unittest.mock import Mock
class TestMockSideEffectSequence(unittest.TestCase):
def test_side_effect_sequence(self):
mock = Mock()
mock.side_effect = [1, 2, 3, Exception("boom")]
self.assertEqual(mock(), 1)
self.assertEqual(mock(), 2)
self.assertEqual(mock(), 3)
with self.assertRaises(Exception) as context:
mock()
self.assertEqual(str(context.exception), "boom")
if __name__ == "__main__":
unittest.main()
Output
Ran 1 test in 0.001s
OK
How it works
The side_effect attribute when set to a list (or any iterable) makes the Mock return each item in sequence on successive calls. Once the list is exhausted, the Mock raises a StopIteration error unless the list contains an exception class or instance, which is raised instead. This is useful for simulating a function that varies its behavior across calls, like a flaky API client or a stateful parser.
Common mistakes
- Using a tuple or set which might be sorted or unordered; use a list to preserve order
- Forgetting that side_effect overrides return_value when both are set
- Not accounting for extra calls after the sequence ends, which raise StopIteration unless the sequence includes an exception
Variations
- Use side_effect with a generator function to compute return values dynamically
- Set side_effect to a callable that returns different values based on call count
Real-world use cases
- Mocking a database connection that returns different rows on consecutive queries.
- Simulating an API endpoint that sometimes returns errors or retries.
- Testing a retry loop by making a function fail on first calls and succeed later.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.