【问题标题】:Python unittest check function call argsPython unittest检查函数调用args
【发布时间】:2018-06-01 11:34:38
【问题描述】:

我正在为现有库开发单元测试,并且我想测试调用函数的参数是否符合某些标准。就我而言,要测试的功能是:

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

【问题讨论】:

    标签: python python-2.7 mocking python-unittest


    【解决方案1】:

    您可以使用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)
    

    更多信息herecall_argscall_args_list

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2021-04-03
      • 2015-02-21
      • 2019-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      相关资源
      最近更新 更多