0
0
PyTesttesting~10 mins

Mock return values and side effects in PyTest - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - pytest
PyTest
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
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Create a mock function objectmock_func is a Mock object with no return value or side effect set-PASS
2Set mock_func.return_value to 10mock_func() will return 10 when calledAssert mock_func() == 10PASS
3Change mock_func.return_value to 20mock_func() will now return 20Assert mock_func() == 20PASS
4Set 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 messagePASS
5Set mock_func.side_effect to list [1, 2, 3]mock_func() will return 1, then 2, then 3 on consecutive callsAssert mock_func() returns 1, then 2, then 3 on three callsPASS
Failure Scenario
Failing Condition: If mock_func does not return the expected values or does not raise the expected exception
Execution Trace Quiz - 3 Questions
Test your understanding
What does setting mock_func.return_value do?
AMakes mock_func() raise an exception
BMakes mock_func() print the value
CMakes mock_func() return the specified value when called
DDeletes the mock_func object
Key Result
Using mock's return_value and side_effect allows you to simulate different behaviors of dependencies, making your tests flexible and focused on the code under test.