如果要验证thirdparty函数是否正确调用,可以模拟它并检查是否使用正确的参数调用了mock。作为
ThirdPartyLib
from unittest import mock
@mock.patch('third_party_lib.ThirdPartyLib')
def test_my_decorator(mocked_lib):
decorator = MyDecorator()
@decorator()
def example_func():
return 42
example_func()
mocked_lib.return_value.send.assert_called_once_with(value=42)
如果在更多测试中需要修饰函数,可以将其包装在函数中:
def decorated_func():
decorator = MyDecorator()
@decorator()
def example_func():
return 42
return example_func
@mock.patch('third_party_lib.ThirdPartyLib')
def test_my_decorator(mocked_lib):
decorated_func()()
mocked_lib.return_value.send.assert_called_once_with(value=42)