gpt4 book ai didi

Python3 单元测试 : How to compare with MagicMocks Using Operators

转载 作者:太空宇宙 更新时间:2023-11-04 04:16:00 25 4
gpt4 key购买 nike

最简单的事情就是从一个例子开始......

要测试的示例代码:

type1_instance1 = f1()
type1_instance2 = f2()

compareResult = type1_instance1 < type1_intstance2

if compareResult:
print(type1_instance1.generate_value())

实例 1 和 2 是一些自定义类的实例。

在测试时 f1f2 被模拟以返回 MagicMocks。这样就可以对这些返回值调用自定义类的方法。

执行比较代码时出现错误

'<' not supported between instances of 'MagicMock' and 'MagicMock'

使 MagicMocks 能够与重载运算符一起工作的最佳方法是什么?

这是我的解决方案:

def __lt__(self, other):
return mock.MagicMock

compareable_MagicMock_Instance = MagicMock()
setattr(compareable_MagicMock_Instance, '__lt__', __lt__)

f1.return_value = compareable_MagicMock_Instance
f2.return_value = another_compareable_MagicMock_Instance

最佳答案

您应该改写 MagicMock 对象的 __lt__ 属性的 return_value 属性,并使用 patch使 f1f2 返回自定义的 MagicMock 实例:

from unittest.mock import patch, MagicMock
def f1():
pass
def f2():
pass
compareable_MagicMock_Instance = MagicMock()
compareable_MagicMock_Instance.__lt__.return_value = True
with patch('__main__.f1', return_value=compareable_MagicMock_Instance), patch('__main__.f2', return_value=compareable_MagicMock_Instance):
type1_instance1 = f1()
type1_instance2 = f2()
compareResult = type1_instance1 < type1_instance2
if compareResult:
print('type1_instance1 is less than type1_instance2')

这个输出:

type1_instance1 is less than type1_instance2

关于Python3 单元测试 : How to compare with MagicMocks Using Operators,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55421771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com