0
0
PyTesttesting~3 mins

Why unittest.mock.patch in PyTest? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could test your code without waiting for slow or unreliable external services every time?

The Scenario

Imagine you have a function that calls an external service, like fetching weather data from the internet. To test your function, you try running it manually and checking the results each time.

This means you wait for the real service to respond, which can be slow or unreliable.

The Problem

Manually testing this way is slow because you depend on the external service's speed and availability.

It is also error-prone since the service might change or be down, causing your tests to fail for reasons unrelated to your code.

You might also get different results each time, making it hard to know if your code works correctly.

The Solution

Using unittest.mock.patch lets you replace the real external call with a fake one during tests.

This fake call returns controlled, predictable data instantly, so your tests run fast and reliably.

You can focus on testing your code's logic without worrying about outside services.

Before vs After
Before
def test_weather():
    result = get_weather_from_internet()
    assert result == expected_data
After
from unittest.mock import patch

@patch('module.get_weather_from_internet')
def test_weather(mock_get):
    mock_get.return_value = expected_data
    result = mock_get()
    assert result == expected_data
What It Enables

It enables fast, reliable, and isolated tests by controlling external dependencies easily.

Real Life Example

When testing an app that sends emails, you don't want to send real emails every time. Using unittest.mock.patch, you fake the email sending function so tests run quickly and no real emails are sent.

Key Takeaways

Manual tests with real external calls are slow and unreliable.

unittest.mock.patch replaces real calls with fake ones during tests.

This makes tests fast, stable, and focused on your code.