Python unittest 检查函数调用参数
Python unittest check function call args
我正在为现有库开发单元测试,我想测试调用函数的参数是否符合特定条件。在我的例子中,要测试的函数是:
class ...
def function(self):
thing = self.method1(self.THING)
thing_obj = self.method2(thing)
self.method3(thing_obj, 1, 2, 3, 4)
对于单元测试,我按以下方式对方法 1、2 和 3 进行了修补:
import unittest
from mock import patch, Mock
class ...
def setUp(self):
patcher1 = patch("x.x.x.method1")
self.object_method1_mock = patcher1.start()
self.addCleanup(patcher1.stop)
...
def test_funtion(self)
# ???
在单元测试中,我想提取参数 1、2、3、4 并进行比较,例如查看第三个参数是否小于第四个参数(2 < 3)。我将如何继续使用 mock 或其他库来解决这个问题?
您可以使用 call_args
属性从模拟中获取最新的调用参数。如果你想比较 self.method3()
调用的参数,那么你应该可以这样做:
def test_function(self):
# Call function under test etc.
...
# Extract the arguments for the last invocation of method3
arg1, arg2, arg3, arg4, arg5 = self.object_method3_mock.call_args[0]
# Perform assertions
self.assertLess(arg3, arg4)
有关 call_args
和 call_args_list
的更多信息 here。
我正在为现有库开发单元测试,我想测试调用函数的参数是否符合特定条件。在我的例子中,要测试的函数是:
class ...
def function(self):
thing = self.method1(self.THING)
thing_obj = self.method2(thing)
self.method3(thing_obj, 1, 2, 3, 4)
对于单元测试,我按以下方式对方法 1、2 和 3 进行了修补:
import unittest
from mock import patch, Mock
class ...
def setUp(self):
patcher1 = patch("x.x.x.method1")
self.object_method1_mock = patcher1.start()
self.addCleanup(patcher1.stop)
...
def test_funtion(self)
# ???
在单元测试中,我想提取参数 1、2、3、4 并进行比较,例如查看第三个参数是否小于第四个参数(2 < 3)。我将如何继续使用 mock 或其他库来解决这个问题?
您可以使用 call_args
属性从模拟中获取最新的调用参数。如果你想比较 self.method3()
调用的参数,那么你应该可以这样做:
def test_function(self):
# Call function under test etc.
...
# Extract the arguments for the last invocation of method3
arg1, arg2, arg3, arg4, arg5 = self.object_method3_mock.call_args[0]
# Perform assertions
self.assertLess(arg3, arg4)
有关 call_args
和 call_args_list
的更多信息 here。