s3rvac s3rvac - 4 months ago 9
Python Question

How to check if a unittest.mock.Mock has return_value set?

I have a

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.

Answer

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.