为什么要模拟添加__nonzero__方法调用?

bit*_*cle 10 python unit-testing mocking

我有一些代码调用集合中每个项目的一系列方法,每个方法返回一个布尔值,表示success = 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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

实际通话

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

...

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

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

澄清

我正在使用mock,它包含在python 3.3中的stdlib中.

Gar*_*tty 16

简短回答:

如果你的模拟函数没有返回的显式return_value或side_effect,你会看到这是因为Python试图评估你的模拟的真实性.确保你的模拟有一个.

用一个初始化它:

item = MagicMock(return_value=True)
Run Code Online (Sandbox Code Playgroud)

或添加一个:

item.return_value = True
Run Code Online (Sandbox Code Playgroud)

说明:

当你这样做时if not x:,你可能在想if x is False.

Python实际上并没有这样做 - 它确实if bool(x) is False(这是Python的真实性概念 - 值评估为TrueFalse),bool(x)实际上是对x.__nonzero__()(或x.__bool__()3.x)的调用.

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