s3rvac s3rvac - 1 year ago 92
Python Question

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

I have a

. The only thing I know is that it mocks a class with a
method. I need to determine whether
has been set and if not, provide a default value. Is this possible?

In other words, how to implement

m = unittest.mock.Mock()
# ...
if not has_return_value_set(m.foo):
m.foo.return_value = MY_RETURN_VALUE

I have tried checking
directly, but it is initialized to a new mock upon the first access.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download