[英]How to check if a unittest.mock.Mock has return_value set?
I have a unittest.mock.Mock
instance m
. 我有一个
unittest.mock.Mock
实例m
。 The only thing I know is that it mocks a class with a foo()
method. 我唯一知道的是它使用
foo()
方法模拟了一个类。 I need to determine whether m.foo.return_value
has been set and if not, provide a default value. 我需要确定是否已设置
m.foo.return_value
,如果未设置,请提供默认值。 Is this possible? 这可能吗?
In other words, how to implement has_return_value_set()
below? 换句话说,如何在下面实现
has_return_value_set()
?
m = unittest.mock.Mock()
# ...
if not has_return_value_set(m.foo):
m.foo.return_value = MY_RETURN_VALUE
I have tried checking m.foo.return_value
directly, but it is initialized to a new mock upon the first access. 我尝试直接检查
m.foo.return_value
,但是在第一次访问时将其初始化为新的模拟。
As long as you haven't actually accessed mock.return_value
yet, you can test if a non-standard return value has been set with: 只要您尚未实际访问过
mock.return_value
,就可以测试是否使用以下方法设置了非标准返回值:
m.foo._mock_return_value is unittest.mock.DEFAULT
The moment you use the mock.return_value
property, if mock._mock_return_value
is set to unittest.mock.DEFAULT
still, a new Mock
instance is created and stored in mock._mock_return_value
for future re-use. 您使用的那一刻
mock.return_value
属性,如果mock._mock_return_value
设置为unittest.mock.DEFAULT
的是,新的Mock
创建实例,并存储在mock._mock_return_value
以备将来再使用。
Note that this attribute is an implementation detail, which is why it starts with an underscore. 请注意,此属性是一个实现细节,这就是为什么它以下划线开头的原因。 It is not documented and may change in a future release.
它没有记录,在将来的发行版中可能会更改。 However, there currently is no other method to check if
mock.return_value
has been set explicitly. 但是,当前没有其他方法可以检查是否已显式设置了
mock.return_value
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.