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 |