Decorator can also be used in class. Remember patch is used for test, so
only function name starts with test_ will be treat as test function
only class derives from unittest.TestCase will be treat as test class
1 2 3 4 5 6 7 8 9 10
@patch("demo.func") classMyTest(unittest.TestCase): deftest_1(self, mock_func): ... deftest_2(self, mock_func): ... # patch is not working defmytest_func(self): ...
target: target object’s path, remember it must be a string looks like package.module.className. If the object is defined in the same file, please use __main__.className.
new: default is MagicMock(), it can be a value or a actual object.
# don't recommend to assign a value to new defmain(): mock_func = patch("demo.func", new_callable = return_100) mock_func.start() demo.func # 100 mock_func.end()
Cannot use ‘new’ and ‘new_callable’ together!
1
patch("demo.func", new = xxx, new_callable = xxx) # error
how to patch a whole class
1 2 3 4 5 6 7 8 9
# util.py classObject: def__init__(self, x, y): self.x = x self.y = y defshow(self): print(f"x = {x}, y = {y}") return0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# keep this the same as __init__ defconstructor(self, x, y): self = Mock(spec = Object) self.x = 2 * x self.y = 2 * y self.show.return_value = 100 return self
@patch("util.Object", new = constructor) deftest_patch_with_new(): o = Object(10, 10) res = o.show() # x = 20, y = 20 print(res) # 100 o.x = 1000 print(o.x) # 1000
patch.object
Used to mock methods in one class.
1 2 3 4 5 6 7 8
import Object
# only mock func inside Object class @patch.object(Object, "func") deftest_patch_object(mock_func): mock_func.return_value = 100 o = Object() o.func() # 100
patch.dict
1 2 3 4
m = {"a": 1, "b": 2}
with patch.dict(m, {"a": 10, "b": 20}, clear=True): m["a"] # 10