0
0
PyTesttesting~10 mins

unittest.mock.patch in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses unittest.mock.patch to replace a function with a mock during the test. It verifies that the patched function is called with expected arguments and returns the mocked value.

Test Code - pytest
PyTest
from unittest.mock import patch
import pytest

def get_data():
    # Imagine this fetches data from a slow external source
    return "real data"

def process_data():
    data = get_data()
    return f"Processed {data}"

@patch('__main__.get_data')
def test_process_data(mock_get_data):
    mock_get_data.return_value = "mocked data"
    result = process_data()
    mock_get_data.assert_called_once()
    assert result == "Processed mocked data"
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsTest runner initializes pytest environment-PASS
2Patch '__main__.get_data' with a mock objectThe get_data function is replaced by mock_get_data during test-PASS
3Call process_data(), which calls the patched get_data()process_data calls mock_get_data instead of real get_data-PASS
4mock_get_data returns 'mocked data' as set by return_valueprocess_data receives 'mocked data' from mock_get_data-PASS
5Assert mock_get_data was called exactly oncemock_get_data call count is 1mock_get_data.assert_called_once()PASS
6Assert process_data() returned 'Processed mocked data'Result string is 'Processed mocked data'assert result == 'Processed mocked data'PASS
7Test ends successfullyAll assertions passed, test completes-PASS
Failure Scenario
Failing Condition: If process_data does not call get_data or returns wrong result
Execution Trace Quiz - 3 Questions
Test your understanding
What does the patch decorator do in this test?
ARuns the real get_data function
BReplaces get_data with a mock during the test
CSkips the test
DChanges process_data to return a fixed value
Key Result
Use unittest.mock.patch to replace slow or external functions with mocks during tests. This helps isolate the code under test and control its dependencies.