0
0
PyTesttesting~10 mins

pytest-mock for enhanced mocking - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses pytest-mock to mock a function call and verify that it was called with expected arguments. It checks that the mocked function returns the mocked value and that the call count and arguments are correct.

Test Code - pytest
PyTest
import pytest

def fetch_data():
    # Imagine this fetches data from a remote API
    return "real data"

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

def test_process_data_calls_fetch_data(mocker):
    mock_fetch = mocker.patch(__name__ + ".fetch_data", return_value="mocked data")
    result = process_data()
    assert result == "Processed mocked data"
    mock_fetch.assert_called_once()
    mock_fetch.assert_called_with()
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2mocker.patch replaces fetch_data with a mock returning 'mocked data'fetch_data function is mocked-PASS
3process_data() is called, which internally calls mocked fetch_dataprocess_data calls mocked fetch_data, receives 'mocked data'-PASS
4Assert that process_data() returns 'Processed mocked data'Returned value is 'Processed mocked data'assert result == 'Processed mocked data'PASS
5Assert that fetch_data was called exactly onceMock call count is 1mock_fetch.assert_called_once()PASS
6Assert that fetch_data was called with no argumentsMock call arguments are emptymock_fetch.assert_called_with()PASS
7Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: fetch_data is not called or returns unexpected value
Execution Trace Quiz - 3 Questions
Test your understanding
What does mocker.patch do in this test?
ASkips the fetch_data call
BRuns the real fetch_data function
CReplaces fetch_data with a mock that returns 'mocked data'
DRaises an exception
Key Result
Use pytest-mock's mocker.patch to replace functions during tests. This lets you control return values and verify calls without changing real code.