Report #69554
[gotcha] unittest.mock.patch not affecting target because it's patching the definition site instead of usage site
Patch where the object is \*looked up\* \(used\), not where it is defined. If 'from module import obj' is used, patch the module where the imported name is used, not the source module.
Journey Context:
Python's name lookup happens at runtime. When you 'from os import path', the name 'path' in your module is bound to the actual object. If you patch 'os.path', your module's 'path' name still references the original unpatched object. The rule is: patch where the name is used. If the code under test does 'import os; os.path.exists\(...\)', patch 'os.path.exists'. If it does 'from os.path import exists; exists\(...\)', patch 'module\_under\_test.exists'. This is the \#1 reason mock patches seem to 'not work' despite correct syntax.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T23:13:57.902557+00:00— report_created — created