Test Overview
This test checks how to use mocks in pytest to simulate different return values and side effects of a function. It verifies that the mocked function returns expected values and raises exceptions as planned.
This test checks how to use mocks in pytest to simulate different return values and side effects of a function. It verifies that the mocked function returns expected values and raises exceptions as planned.
import pytest from unittest.mock import Mock def test_mock_return_and_side_effect(): mock_func = Mock() # Set return value mock_func.return_value = 10 assert mock_func() == 10 # Change return value mock_func.return_value = 20 assert mock_func() == 20 # Set side effect to raise exception mock_func.side_effect = ValueError("Mock error") with pytest.raises(ValueError) as exc_info: mock_func() assert str(exc_info.value) == "Mock error" # Set side effect to a list of return values mock_func.side_effect = [1, 2, 3] assert mock_func() == 1 assert mock_func() == 2 assert mock_func() == 3
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Create a mock function object | mock_func is a Mock object with no return value or side effect set | — | PASS |
| 2 | Set mock_func.return_value to 10 | mock_func() will return 10 when called | Assert mock_func() == 10 | PASS |
| 3 | Change mock_func.return_value to 20 | mock_func() will now return 20 | Assert mock_func() == 20 | PASS |
| 4 | Set mock_func.side_effect to raise ValueError("Mock error") | Calling mock_func() raises ValueError with message 'Mock error' | Assert that calling mock_func() raises ValueError with correct message | PASS |
| 5 | Set mock_func.side_effect to list [1, 2, 3] | mock_func() will return 1, then 2, then 3 on consecutive calls | Assert mock_func() returns 1, then 2, then 3 on three calls | PASS |
mock.return_value do in a pytest mock object?return_valuereturn_value attribute sets a fixed return value for the mock when it is called.side_effect which can raise exceptions or return different values, return_value always returns the same fixed value.side_effect to an exception causes the mock to raise that exception when called.mock.side_effect = Exception('Error') is valid syntax to raise an exception on call.from unittest.mock import Mock mock = Mock() mock.side_effect = [1, 2, 3] print(mock()) print(mock()) print(mock())
side_effect is a list, each call to the mock returns the next item in the list.from unittest.mock import Mock
mock = Mock()
mock.side_effect = Exception('Fail')
mock.side_effect = [1, 2, 3]
print(mock())side_effect replaces the first one; no error occurs.side_effect = [1, 2, 3], the mock returns 1 on first call, so print(mock()) outputs 1.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.Pass the test and this pattern moves unknown