0
0
PyTesttesting~5 mins

pytest-mock for enhanced mocking

Choose your learning style9 modes available
Introduction

We use pytest-mock to easily replace parts of our code during tests. This helps us check how our code behaves without running everything for real.

When you want to test a function that calls an external service without actually calling it.
When you want to simulate a specific return value from a function to test different scenarios.
When you want to check if a function was called with the right arguments.
When you want to avoid slow or unreliable parts of your code during testing.
When you want to isolate the part of the code you are testing from others.
Syntax
PyTest
def test_example(mocker):
    mock_function = mocker.patch('module.function_to_mock')
    mock_function.return_value = 'mocked value'
    result = module.function_to_test()
    assert result == 'expected result'

The mocker fixture is provided by pytest-mock automatically.

Use mocker.patch() to replace the target function or object during the test.

Examples
This replaces math.sqrt to always return 3, no matter the input.
PyTest
import math

def test_mock_return_value(mocker):
    mocker.patch('math.sqrt', return_value=3)
    assert math.sqrt(16) == 3
This checks if func was called once with the argument 'hello'.
PyTest
def test_mock_called_with(mocker):
    mock_func = mocker.patch('module.func')
    module.call_func()
    mock_func.assert_called_once_with('hello')
This uses a side effect function to change the behavior of double during the test.
PyTest
def test_mock_side_effect(mocker):
    def side_effect(x):
        return x * 2
    mocker.patch('module.double', side_effect=side_effect)
    assert module.double(4) == 8
Sample Program

This test replaces math.sqrt to return 10 instead of 5. It checks if calculate() returns the mocked value.

PyTest
import math

def calculate():
    return math.sqrt(25)

def test_calculate(mocker):
    mocker.patch('math.sqrt', return_value=10)
    result = calculate()
    assert result == 10
    print('Test passed')
OutputSuccess
Important Notes

Always patch the function or object where it is used, not where it is defined.

pytest-mock works well with pytest and makes mocking simpler and cleaner.

Remember to keep mocks simple and only mock what is necessary for the test.

Summary

pytest-mock helps replace parts of code during tests easily.

Use mocker.patch() to mock functions or objects.

Check calls and return values to verify your code behavior.