unittest_mock
Import
Usage
Production Code
Test Code
Patched Function Path
For the full function namespace path in @patch()
, you need to use the namespace of the file that contains the function you're testing, not the file where the patched function is defined.
Example:
file_1.py
contains functiondef add(a, b)
file_2.py
contains functiondef add_and_print()
, which calls functionadd()
You're writing a unit test for function
add_and_print()
in a separatetest.py
fileWhen you patch
add()
, you would use the namespace offile_2.py
like:@patch("path.to.file_2.add")
Even though the function is defined at
path.to.file_1
, when it gets imported intofile_2.py
, it takes on the namespace offile_2.py
Last updated