Python单元测试检查函数调用参数

eni*_*iem 4 python mocking python-2.7 python-unittest

我正在对现有库开发单元测试,我想测试调用函数的参数是否符合某些条件。就我而言,要测试的函数是:

class ...
    def function(self):
        thing = self.method1(self.THING)
        thing_obj = self.method2(thing)
        self.method3(thing_obj, 1, 2, 3, 4)
Run Code Online (Sandbox Code Playgroud)

对于单元测试,我按以下方式修补了方法 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)
            # ???
Run Code Online (Sandbox Code Playgroud)

在单元测试中,我想提取参数 1、2、3、4 并比较它们,例如查看第三个参数是否小于第四个参数(2 < 3)。我将如何继续使用模拟或其他库来解决这个问题?

Wil*_*ing 5

您可以使用该属性从模拟中获取最新的调用参数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)
Run Code Online (Sandbox Code Playgroud)

更多信息参见call_argscall_args_list