0
0
PyTesttesting~5 mins

unittest.mock.patch in PyTest

Choose your learning style9 modes available
Introduction

unittest.mock.patch helps you replace parts of your code during tests. This lets you control what those parts do, so you can test your code easily.

When you want to replace a function that calls an external service to avoid real calls during tests.
When you want to simulate different return values from a function to test how your code reacts.
When you want to replace a class or object temporarily to isolate the part you are testing.
When you want to avoid slow or complex operations during testing by mocking them.
When you want to check if a function was called without running its real code.
Syntax
PyTest
from unittest.mock import patch

@patch('module_name.function_name')
def test_function(mock_function):
    mock_function.return_value = expected_value
    # your test code here

Use the full path to the function or object you want to replace, like 'package.module.function'.

The patched object is replaced only during the test and restored after it finishes.

Examples
This replaces math.sqrt with a mock that always returns 3 during the test.
PyTest
from unittest.mock import patch

@patch('math.sqrt')
def test_sqrt(mock_sqrt):
    mock_sqrt.return_value = 3
    result = mock_sqrt(9)
    assert result == 3
This uses patch as a context manager to mock requests.get only inside the with block.
PyTest
from unittest.mock import patch
import requests

def test_api_call():
    with patch('requests.get') as mock_get:
        mock_get.return_value.status_code = 200
        response = requests.get('http://example.com')
        assert response.status_code == 200
Sample Program

This test replaces requests.get with a mock that returns a response with status_code 404. The test checks if fetch_status returns 404 as expected.

PyTest
from unittest.mock import patch
import requests

def fetch_status(url):
    response = requests.get(url)
    return response.status_code

@patch('requests.get')
def test_fetch_status(mock_get):
    mock_get.return_value.status_code = 404
    status = fetch_status('http://fakeurl.com')
    assert status == 404
    print('Test passed')

if __name__ == '__main__':
    test_fetch_status()
OutputSuccess
Important Notes

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

Remember to set return_value or side_effect on the mock to control its behavior.

Using patch as a decorator or context manager depends on how long you want the mock to last.

Summary

unittest.mock.patch lets you replace parts of your code during tests to control behavior.

Use patch to avoid real calls and test your code in isolation.

Patch can be used as a decorator or context manager for flexible mocking.