Let's say we have two files:
to_patch.py
from unittest.mock import patch
def patch_a_function():
print("Patching!")
patcher = patch("to_be_patched.function")
patcher.start()
print("Done patching!")
to_be_patched.py
from to_patch import patch_a_function
def function():
pass
patch_a_function()
function()
And we run python -m to_be_patched
. This will output:
Patching!
Patching!
- Why isn't
Done patching!
ever printed? - Why is
Patching!
printed twice?
I've narrowed the answer to (2) down; the call to patch.start
seems to trigger patch_a_function
again. I suspect this is because it's imported in to_be_patched.py
, but am not sure why the function itself would run for a second time. Similarly, I'm not sure why the Done patching!
line is not reached in either of the calls to patch_a_function
. patcher.start()
can't be blocking, because the program exits nicely instead of hanging there... right?
from Why does unittest's `mock.patch.start` re-run the function in which the patcher is started?
No comments:
Post a Comment