python - 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)。我将如何使用模拟或其他库来解决这个问题?
解决方案
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
。
推荐阅读
- c# - 有没有一种方法可以让我从 .net 标准 2.0 访问配置文件
- python - Python 冒泡排序 - 对元素进行多次排序
- android - 无法解决:appcompat-v7 android studio 3.2.1
- r - R合并数据/扩展数据集
- c# - C# 将字符串传递给 Sqlite 参数
- postgresql - 通过给定 ID 获取多行的比率
- javascript - 当a:href链接存在时,Vue.js @click不执行功能
- google-chrome - 为什么我不能检查 cypress.io 中的元素
- ruby-on-rails - 设计身份验证令牌 current_user 返回 nil
- jenkins - 詹金斯构建脚本无法从远程仓库 git pull