patch where it is looked up¶
Level: 301 · for Python programmers
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The bullets below are the questions the finished page has to answer.
One line: unittest.mock.patch('mod.name') replaces the attribute name in module mod for the duration of a test, so a function that did from time import time keeps its own reference and is unaffected by patching time.time, while patching mymodule.time works — the target is where the name is looked up at call time, which is a chapter-4 fact about names wearing a testing hat.
What the finished page has to answer¶
- The rule from the
mockdocumentation, measured:import time; time.time()looks the name up at the call and sees the patch;from time import timebound a second name at import, and does not. patchas a decorator and as a context manager, and the argument order when several decorators are stacked, which is A decorator is a call bottom-up.autospec=True, and why without it aMockaccepts any call and any attribute, so a misspelledassert_called_once_wihtused to pass silently; theassert_*names have raisedAttributeErrorsince 3.5, andunsafe=Trueturns that back off.patch.objectfor one attribute of one object,patch.dictforos.environ.datetime.datetimeis a C type and cannot be patched in place; patch the name in the module that uses it.- What a patch does to a name captured in a closure or a default argument before the test ran, which is A default is computed once.
See also¶
- Assignment does not copy and A closure captures the variable, not the value: the two facts about names this page rests on
- Where to patch ↗ in the
unittest.mockdocumentation - A test double by hand ↗ in the Rust library, where there is no
patchand the seam has to be a trait