本文介绍了当 python 模拟同时具有返回值和副作用列表时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法理解某些测试代码中发生的情况.它看起来像这样:
导入pytest从 unittest.mock 导入 MagicMock从 my_module 导入 MyClass混淆模拟 = MagicMock(return_value=b"",副作用=[连接错误(),b"another_return_value?",b"another_another_return_value?"])mocked_class = MyClass()monkeypatch.setattr(模拟类,method_to_call_thrice",混淆模拟)
我知道:
side_effect
是在调用模拟时调用的函数- 但是如果
side_effect
是可迭代的,那么对模拟的每次调用都会从迭代中返回下一个值"(感谢 pytest文档) - 文档还说,如果函数传递给
side_effect
返回DEFAULT
,然后模拟将从中返回它的正常值return_value
但这是我没有得到的:
- 当我提供同时一个副作用列表和一个返回值?
- 每次调用
MyClass.method_to_call_thrice
时我应该看到什么?
解决方案
side_effect
被使用.列表值可以包含mock.DEFAULT
,函数可以返回mock.DEFAULT
,表示使用return_value
属性的值.
I'm having trouble understanding what's happening in some test code. It looks like this:
import pytest
from unittest.mock import MagicMock
from my_module import MyClass
confusing_mock = MagicMock(
return_value=b"",
side_effect=[
ConnectionError(),
b"another_return_value?",
b"another_another_return_value?"
])
mocked_class = MyClass()
monkeypatch.setattr(mocked_class, "method_to_call_thrice", confusing_mock)
I know that:
side_effect
is a function to be called whenever the mock is called- but if
side_effect
is an iterable, then "each call to the mock willreturn the next value from the iterable" (thanks pytestdocs) - the docs also say that if the function passed to
side_effect
returnsDEFAULT
, then the mock will return it's normal value fromreturn_value
But here's what I don't get:
- What happens when I provide both a list of side effects and areturn value?
- What should I expect to see on each call of
MyClass.method_to_call_thrice
?
解决方案
side_effect
is used. A list value can contain mock.DEFAULT
, and a function can return mock.DEFAULT
, to indicate that the value of the return_value
attribute be used.
>>> import unittest.mock
>>> m = unittest.mock.Mock(return_value="foo",
... side_effect=[1, 2, unittest.mock.DEFAULT, 4, 5])
>>> m()
1
>>> m()
2
>>> m()
'foo'
>>> m()
4
>>> m()
5
>>> unittest.mock.Mock(return_value="foo",
... side_effect=lambda: unittest.mock.DEFAULT)()
'foo'
这篇关于当 python 模拟同时具有返回值和副作用列表时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!