0
我在模擬消息隊列,我希望它返回2條消息,然後在每次調用時都返回None(模擬消息隊列現在爲空)。但是,在第三個消息調用之後,我從模擬框架中得到一個錯誤,說沒有「下一個」值。Python模擬返回初始預定義值返回默認值
下面是一個例子:
from mock import MagicMock
mock_message_queue = MagicMock(name='message_queue')
expected_messages = ['message 1', 'message 2', None]
mock_message_queue.fetch.side_effect = expected_messages
print('mock_message_queue.fetch() = {}'.format(mock_message_queue.fetch()))
print('mock_message_queue.fetch() = {}'.format(mock_message_queue.fetch()))
print('mock_message_queue.fetch() = {}'.format(mock_message_queue.fetch()))
print('mock_message_queue.fetch() = {}'.format(mock_message_queue.fetch()))
輸出:
mock_message_queue.fetch() = message 1
mock_message_queue.fetch() = message 2
mock_message_queue.fetch() = None
Traceback (most recent call last):
File "/home/wsi/.PyCharm2017.1/config/scratches/mock_message_bus.py", line 10, in <module>
print('mock_message_queue.fetch() = {}'.format(mock_message_queue.fetch()))
File "/usr/local/lib/python3.5/dist-packages/mock/mock.py", line 1062, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/mock/mock.py", line 1121, in _mock_call
result = next(effect)
StopIteration
Process finished with exit code 1
所以基本上我想它總是返回無返回 '消息2' 之後。有人知道怎麼做嗎?