unittest.Mock-结合return_value和side_effect [英] unittest.Mock - Combining return_value and side_effect
问题描述
是否有可能使Mock
对象在调用时返回值并在调用时执行语句?例如:
Is it possible to have a Mock
object return a value when called as well as execute a statement when called? For example this:
> mocked_func = Mock(return_value='Returned foo',
side_effect=lambda: print('Side effect executed')
)
> print(mocked_func())
Side effect executed
None
这里的文档似乎有点模棱两可,但在我看来,当使用side_effect
时,将完全忽略return_value
,并且仅返回side_effect
函数的结果(在print()
情况下为None
).
The documentation seems a little ambiguous here but it seems to me that when side_effect
is used, then return_value
is ignored altogether and only the result of side_effect
function is returned (which in case of print()
is None
).
由于Python并不真正支持多语句lambda(AFAIK,最好的办法是将表达式放在元组中,但随后将返回整个元组)-是否可以将两个参数组合在一起?
Since Python does not really support multi-statement lambdas (AFAIK, the best you can do is put expressions in a tuple, but then the whole tuple would be returned) - is it possible to combine the two arguments?
我想避免定义一个新函数并将其用作side_effect
,我觉得在Mock
中声明这两个函数更干净.
I want to avoid having to define a new function and using that as the side_effect
, I feel having both declared in a Mock
is cleaner.
推荐答案
答案为是否有可能使Mock
对象在调用时返回值并在调用时执行语句?"显然是的,只需使side_effect
做所有事情即可:
The answer to "is it possible to have a Mock
object return a value when called as well as execute a statement when called?" is obviously yes, just make side_effect
do everything:
import unittest.mock as mock
def side_effect():
print('Side effect executed')
return 'Returned Foo'
mocked_func = mock.Mock(side_effect=side_effect)
print(mocked_func())
# output
Side effect executed
Returned Foo
当然,您也可以使用lambda来做到这一点:
Of course you can do it with a lambda too:
import unittest.mock as mock
mocked_func = mock.Mock(
side_effect=lambda: (print('Side effect executed'), 'Returned Foo')[1]
)
print(mocked_func())
# output
Side effect executed
Returned Foo
在我看来,它看起来并不干净,但对每个人来说却如此.如果您只是想避免污染名称空间,则可以执行以下操作:
It does not look any cleaner to me but to each their own. If you just want to avoid polluting your namespace you can do this:
def mocked_func():
print('Side effect executed')
return 'Returned Foo'
mocked_func = mock.Mock(side_effect=mocked_func)
或使用装饰器:
def mock_it(f):
return mock.Mock(side_effect=f)
@mock_it
def mocked_func():
print('Side effect executed')
return 'Returned Foo'
像您已经注意到的那样,将return_value
和side_effect
合并似乎是不可能的.
Combining return_value
and side_effect
does not seem to be possible as you already noticed.
这篇关于unittest.Mock-结合return_value和side_effect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!