I have a unittest.mock.Mock
instance m
. The only thing I know is that it mocks a class with a foo()
method. I need to determine whether m.foo.return_value
has been set and if not, provide a default value. Is this possible?
In other words, how to implement has_return_value_set()
below?
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.
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:
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.