Ale*_*exC 6 python unit-testing mocking python-3.x
I am trying to mock a coroutine. As such, this mock's __next__() and close() are called. While mocking close() works, I cannot mock __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()
Run Code Online (Sandbox Code Playgroud)
What am I missing? How to make sure my mock's __next__() method is called?
For now, I am using the following:
class MockCoroutine:
def __next__(self):
self.called_next = True
def close(self):
self.called_exit = True
Run Code Online (Sandbox Code Playgroud)
However, I very much rather use a standard mock.
You need to use MagicMock, not Mock, to have magic methods like __next__ available by default:
>>> from unittest import mock
>>> mock_coroutine = mock.MagicMock()
>>> mock_coroutine.__next__()
<MagicMock name='mock.__next__()' id='4464126552'>
>>> mock_coroutine.__next__.assert_called_with()
Run Code Online (Sandbox Code Playgroud)
Quoting from the documentation:
Mockallows you to assign functions (or otherMockinstances) to magic methods and they will be called appropriately. TheMagicMockclass is just aMockvariant that has all of the magic methods pre-created for you (well, all the useful ones anyway).
So, alternatively, you could still use the regular Mock object, but then you need to explicitly add that attribute:
>>> mock_coroutine = mock.Mock()
>>> mock_coroutine.__next__ = mock.Mock()
>>> mock_coroutine.__next__()
<Mock name='mock.__next__()' id='4464139232'>
Run Code Online (Sandbox Code Playgroud)
That's because although Mock creates attributes on the fly as you access them, any attributes with leading and trailing underscores are explicitly exempted from that. See this footnote:
唯一的例外是魔术方法和属性(具有前导和尾随双下划线的那些)。Mock 不会创建这些,而是会引发一个
AttributeError. 这是因为解释器经常会隐式地请求这些方法,并且当它期望一个魔术方法时,会非常困惑地获取一个新的 Mock 对象。如果您需要魔术方法支持,请参阅魔术方法。
但请注意,魔术方法通常是在类上查找,而不是在实例上查找,因此直接将__next__属性添加到Mock实例仍然可能失败;该MagicMock课程会为您处理这个特定问题。
| 归档时间: |
|
| 查看次数: |
1291 次 |
| 最近记录: |