首页 > 解决方案 > Python unittest检查函数调用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)。我将如何使用模拟或其他库来解决这个问题?

标签: pythonpython-2.7mockingpython-unittest

解决方案


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


推荐阅读