What if you could test your code without waiting for slow or unreliable external services every time?
Why unittest.mock.patch in PyTest? - Purpose & Use Cases
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.
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.
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.
def test_weather():
result = get_weather_from_internet()
assert result == expected_datafrom 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
It enables fast, reliable, and isolated tests by controlling external dependencies easily.
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.
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.