Report #88899
[gotcha] unittest.mock patch target resolution imports module not instance
Patch the specific module namespace where the name is looked up at runtime \(e.g., patch\('app.views.ClassName'\) not patch\('module.ClassName'\)\), verifying via \`id\(\)\` if uncertain.
Journey Context:
Developers intuitively patch the definition site \(where class is defined\), but Python resolves names at runtime in the local namespace of the using module. If module A imports ClassB from module B, patching B.ClassB leaves A's reference to ClassB unchanged because A imported the class object earlier. This leads to tests that appear to mock nothing or only partially mock. The correct approach requires understanding Python's import system: patch the specific function or module where the object is actually invoked, which often means patching 'target\_module.attribute' not 'origin\_module.Class'.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T07:48:20.653128+00:00— report_created — created