gpt4 book ai didi

python - 为什么 mock 会添加 __nonzero__ 方法调用?

转载 作者:太空狗 更新时间:2023-10-29 18:23:20 24 4
gpt4 key购买 nike

我有一些代码可以调用集合中每个项目的一系列方法,每个方法返回一个 bool 值,指示成功 = True/failure = False。

def monkey(some_collection, arg1, arg2):
for item in some_collection:
if not item.foo(arg1, arg2):
continue
if not item.bar(arg1, arg2):
continue
if not item.baz(arg1, arg2):
continue

而且,这是我的单元测试示例:

import mock
def TestFoo(unittest.TestCase):
def test_monkey(self):
item = MagicMock()
some_collection = [item]
collection_calls = []
foo_call = mock.call().foo(some_collection, 1, 2)
bar_call = mock.call().bar(some_collection, 1, 2)
baz_call = mock.call().baz(some_collection, 1, 2)
collection_calls = [foo_call, bar_call, baz_call]
my_module.monkey(some_collection, 1, 2)
item.assert_has_calls(collection_calls) # requires the correct call order/sequence

实际调用

  1. call().foo(<MagicMock id='12345'>, 1, 2)
  2. call().foo.__nonzero__()

...

注意:此单元测试失败,因为它看到了 __nonzero__()方法调用。

问题

为什么要添加非零方法调用?

澄清

我正在使用 mock ,自 python 3.3 起包含在 stdlib 中。

最佳答案

简答:

如果您的模拟函数没有返回的显式 return_value 或 side_effect,您将在 Python 尝试评估模拟的真实性时看到这一点。确保您的模拟有一个。

要么用一个初始化它:

item = MagicMock(return_value=True)

或添加一个:

item.return_value = True

说明:

当您执行 if not x: 时,您可能会想 if x is False

Python 实际上并不这样做 - 它会if bool(x) is False(这是 Python 的 truthiness 概念 - 值计算为 TrueFalse),而 bool(x) 实际上是对 x.__nonzero__()(或 x. __bool__() 在 3.x 中)。

这是为了提供 Python 的良好 if 行为 - 当您执行 if []: 时,许多语言会将任何对象视为 True,但 Python 旨在使代码可读,因此它委托(delegate)并且列表的 __nonzero__() 方法将返回 False 如果它是空的。这允许更多的代码阅读起来更自然,并解释了为什么您会看到这些调用。

关于python - 为什么 mock 会添加 __nonzero__ 方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14046237/

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