Your mock.patch has no effect. Where should you patch?
Question
should_alert(tank) returns True when the tank's level is below 3. The test should replace the sensor with a fake that returns 2, so no real device is needed. But the test still calls the real sensor and fails with RuntimeError: no device in tests.
Why does the patch have no effect? Fix the test. Also make it check that the sensor was asked about the right tank.
# sensor.py def read_level(tank): raise RuntimeError("no device in tests") # alarm.py from sensor import read_level def should_alert(tank): return read_level(tank) < 3 # test_alarm.py from unittest.mock import patch import alarm def test_low_level_alerts(): with patch("sensor.read_level", return_value=2): assert alarm.should_alert("tank-west") is True
Show hints (3)
- "WHAT THE IMPORT DOES"
from sensor import read_levelruns once, whenalarmis imported. It creates a name insidealarm. What does that name point to, and does patchingsensorchange it? - "WHICH NAME IS USED"
should_alertlooks upread_levelin its own module each time it runs. The test replacedsensor.read_level. Is that the nameshould_alertuses? - "THE RIGHT TARGET"
Patch the name in the module under test:
alarm.read_level. Writewith patch(...) as fake_readso you can assert how the fake was called.
Show checked explanation
Patch where the name is looked up, not where it is defined. from sensor import read_level creates a separate name in alarm, and should_alert uses that one. Patching sensor.read_level leaves it pointing to the real function. Patch alarm.read_level instead, and assert that the fake was called once with "tank-west".
# test_alarm.py from unittest.mock import patch import alarm import sensor def test_low_level_alerts(): with patch("alarm.read_level", return_value=2) as fake_read: assert alarm.should_alert("tank-west") is True fake_read.assert_called_once_with("tank-west") assert alarm.read_level is sensor.read_level if __name__ == "__main__": test_low_level_alerts() print("test passed")
test passed
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
from sensor import read_level runs once, when alarm is imported. It creates a new name inside alarm that points to the same function. Now there are two names:
| name | points to |
|---|---|
sensor.read_level | the real function |
alarm.read_level | the same real function |
Later changes to sensor don't touch the name inside alarm.
patch("sensor.read_level", ...) replaces only the first name. But should_alert looks up read_level in its own module, alarm, each time it runs. That name still points to the real function. So the test reaches the device code and gets RuntimeError.
patch("alarm.read_level", ...) replaces the name that should_alert really uses. The fake returns 2, and 2 < 3, so should_alert returns True.
The unittest.mock docs give the rule: patch where an object is looked up. That is not always where it is defined.
Asserting the call matters too. assert_called_once_with("tank-west") fails if the code asked about another tank, or asked twice. Without it, code that reads the wrong tank could still return True and pass.
When the with block ends, patch puts the original function back. It does this even if the block raised an exception. The last line of the test shows it: after the block, alarm.read_level is the real function again. So the next test starts with the real function.
Common mistakes
- Catching the
RuntimeErrorin the test to make it pass. The test then proves nothing aboutshould_alert. Fix the patch target instead. - Replacing the function by hand:
alarm.read_level = fake. Nothing puts the original back, so every test that runs after this one also gets the fake. - Patching every helper inside
alarm. The test then breaks every time you refactor. Patch the one outside dependency, the sensor, and assert on the result the caller cares about. - Treating this test as proof that the sensor works. It only covers the
< 3rule for a reading of 2. The real device needs its own integration test.
Follow-up questions
- "What if
alarmusedimport sensorand calledsensor.read_level(tank)?" Thenshould_alertlooks upread_levelon thesensormodule each time it runs. Sopatch("sensor.read_level")is now the right target.patch("alarm.read_level")fails withAttributeError, becausealarmno longer has that name. - "What other cases would you test?" A level of 3 gives
False, because<is strict. A level of 0 givesTrue. For a sensor timeout, patch withside_effect=TimeoutError.should_alerthas notry, so the error reaches the caller. Assert that it raises. That is the right behaviour: if a timeout becameFalse, a broken sensor would look like a normal level. - "How could you test this without
patch?" Pass the reader in as a parameter:def should_alert(tank, read_level=read_level). A test then callsshould_alert("tank-west", read_level=lambda tank: 2). There is no patch target to get wrong. The cost is an extra parameter in the function's signature.
What a strong answer covers
Explains that from ... import creates a second name, and patches the name the code under test looks up. Asserts both the result and the call arguments. Knows that with patch restores the original, and that the target changes with import sensor.
Open in interactive practice deck →