Report #7289
[gotcha] unittest.mock.patch targets the wrong module when patching imports
Always patch where the symbol is \*used\* \(the consumer module\), not where it is \*defined\* \(the origin module\), unless the consumer imports the module itself \(import x\) rather than the symbol \(from x import y\). Verify by checking \`sys.modules\` for the target import chain.
Journey Context:
Python's import system creates distinct module objects in \`sys.modules\`. When you \`from module import func\`, you create a \*copy\* of the reference to \`func\` in the importing module's namespace. If you patch \`module.func\`, the importing module still holds the original reference, so your patch is bypassed. This leads to tests that pass when they should fail or vice versa. The common mistake is to patch \`where.it.is.defined\` because that's where the implementation lives. The alternative of patching both locations is brittle. The correct heuristic is: if the code says \`import os; os.path.exists\`, patch \`os.path\`. If it says \`from os.path import exists; exists\(\)\`, patch \`wherever.exists\` \(the module that imported it\). The provenance is the official mock documentation's 'Where to patch' section.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T02:17:23.477404+00:00— report_created — created