Stop 10 · Testing & Code QualityTopics · 3/8

Mocking with unittest.mock

Part of the Python Roadmap

In short

Tests that call a real weather API or payment gateway are slow, flaky and sometimes cost money. Mocking swaps those parts for fakes during the test, so you test your own logic in milliseconds.

Mocking replaces slow or unreliable parts, such as network calls, databases or the current time, with fake objects during tests. unittest.mock.patch swaps them in temporarily and lets you check how they were called.

On a film set, the jaadu in a director's chair points a megaphone at a cardboard cut-out of a delivery rider standing in for the real one beside a camera on a tripod.

Think of it like this

The stunt double

When the hero has to jump off a train, the film crew uses a stunt double. The scene looks the same, the director controls exactly what happens, and nobody gets hurt. A mock is a stunt double for a risky dependency: it plays the part, says the lines you script, and reports what was done to it.

Watch it happen

Testing get_temperature without the internet

test
weather.py
mock requests.get

patch + return_value

1/5The test replaces requests.get and scripts its answer: json() returns {"temp_c": 31.5}.

The big ideas

What you need to know

patch swaps temporarily

with patch("module.name") replaces an object only inside the block, then restores the original automatically.

Patch where it's looked up

If weather.py does from requests import get, patch "weather.get", not "requests.get".

Script the behaviour

return_value sets what a call returns. side_effect can raise an exception or return a sequence of values.

Check the calls

assert_called_once_with(...) and call_count prove your code talked to the dependency correctly.

See it in code

Walk through the code

python
1# weather.py2import requests3 4URL = "https://api.example.com/weather"5 6 7def get_temperature(city: str) -> float:8    response = requests.get(URL, params={"city": city}, timeout=5)9    response.raise_for_status()10    return response.json()["temp_c"]11 12 13# test_weather.py14from unittest.mock import patch15 16import pytest17import requests18 19import weather20 21 22def test_reads_temperature_from_json() -> None:23    with patch("weather.requests.get") as fake_get:24        fake_get.return_value.json.return_value = {"temp_c": 31.5}25        assert weather.get_temperature("Jaipur") == 31.526        fake_get.assert_called_once_with(weather.URL, params={"city": "Jaipur"}, timeout=5)27 28 29def test_timeout_is_passed_up() -> None:30    with patch("weather.requests.get", side_effect=requests.Timeout):31        with pytest.raises(requests.Timeout):32            weather.get_temperature("Shimla")

1/4The real function makes a network call. We want to test its logic, not the weather service.

No internet needed. Both tests run in milliseconds and give the same result every time.

Save yourself the pain

Common mistakes

Oops

Patching "requests.get" when the module did from requests import get.

Do this instead

Patch the name where your code looks it up: "weather.get".

Oops

Mocking the very function you are trying to test.

Do this instead

Mock only the edges: network, database, clock, randomness. Let your own logic run for real.

Oops

Mocking so much that the test only checks that mocks were called.

Do this instead

Assert on real outputs and behaviour first. Call checks are a supplement, not the whole test.

Your mission

Fake the clock

~25 min

Quick check

shop.py contains from payments import charge. Which target should you patch in tests for shop.py?

Go deeper

  1. 1Mock requests.get in a test for a function that calls a weather API.
  2. 2Use assert_called_once_with to check the arguments passed.
  3. 3Patch the name where it is used, not where it is defined.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge