Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Mocking & test isolationSeniorCommonPractical

What does `unittest.mock.patch` do, and why must you patch a name where it is looked up rather than where it is defined?

Answer

`patch` temporarily replaces an attribute (often a function, class, or object) with a `Mock` for the duration of a test, and automatically restores the original afterward even if the test fails. The critical, frequently-misunderstood rule is that you must patch the name as imported into the module under test, not where the original object lives, because `from module_a import func; func()` inside `module_b` creates a separate binding to `func` inside `module_b`'s own namespace — patching `module_a.func` after that import has already happened does not touch `module_b`'s already-bound reference at all.

Strong answer includes

  • temporarily replaces an attribute with a Mock, restores it automatically after the test
  • patch the name as looked up in the module under test, not where it's originally defined
  • an already-completed import binds a separate name in the importing module's namespace

Practical example

If `service.py` does

Python example
from utils import fetch_data

, a test must patch `service.fetch_data` , not `utils.fetch_data` , because `service` 's namespace already holds its own reference to the original `fetch_data` .

#testing#mocking#gotchas

Sources

unittest — Unit testing frameworkPython Software Foundation · Baseline test-case, mock and assertion semantics shared across Python test toolingpytest documentationpytest · Fixture scope, parametrization, markers and plugin architecture