gpt4 book ai didi

python - 如何模拟对 __next__ 的调用

转载 作者:太空狗 更新时间:2023-10-30 02:59:14 24 4
gpt4 key购买 nike

我正在尝试模拟协程。因此,此模拟的 __next__()close() 被调用。虽然模拟 close() 有效,但我无法模拟 __next__():

    mock_coroutine = mock.Mock()
mock_coroutine.some_call(1, 2, 3)
mock_coroutine.some_call.assert_called_with(1, 2, 3)
mock_coroutine.close()
mock_coroutine.close.assert_called_with()
#this fails
mock_coroutine.__next__()
mock_coroutine.__next__.assert_called_with()

我错过了什么?如何确保调用模拟的 __next__() 方法?

目前,我正在使用以下内容:

class MockCoroutine:
def __next__(self):
self.called_next = True

def close(self):
self.called_exit = True

但是,我更愿意使用标准模拟。

最佳答案

您需要使用 MagicMock,而不是 Mock,才能默认使用像 __next__ 这样的魔术方法:

>>> from unittest import mock
>>> mock_coroutine = mock.MagicMock()
>>> mock_coroutine.__next__()
<MagicMock name='mock.__next__()' id='4464126552'>
>>> mock_coroutine.__next__.assert_called_with()

引自the documentation :

Mock allows you to assign functions (or other Mock instances) to magic methods and they will be called appropriately. The MagicMock class is just a Mock variant that has all of the magic methods pre-created for you (well, all the useful ones anyway).

因此,或者,您仍然可以使用常规的 Mock 对象,但是您需要显式添加该属性:

>>> mock_coroutine = mock.Mock()
>>> mock_coroutine.__next__ = mock.Mock()
>>> mock_coroutine.__next__()
<Mock name='mock.__next__()' id='4464139232'>

那是因为尽管 Mock 在您访问它们时即时创建属性,但任何带有前导和尾随下划线的属性都被明确排除在外。参见 this footnote :

The only exceptions are magic methods and attributes (those that have leading and trailing double underscores). Mock doesn’t create these but instead raises an AttributeError. This is because the interpreter will often implicitly request these methods, and gets very confused to get a new Mock object when it expects a magic method. If you need magic method support see magic methods.

但请注意,魔术方法通常是要在类中查找的,而不是实例,因此直接将 __next__ 属性添加到 Mock 实例仍然会失败; MagicMock 类会为您处理这个特定问题。

关于python - 如何模拟对 __next__ 的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32051246/

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