2

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

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).

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?

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.

2 Answers 2

6

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

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)

Or using a decorator:

def mock_it(f):
    return mock.Mock(side_effect=f)

@mock_it
def mocked_func():
    print('Side effect executed')
    return 'Returned Foo'

Combining return_value and side_effect does not seem to be possible as you already noticed.

2

requires python version >=3.3

0) import unittest.mock.DEFAULT

1) Make the side_effect function returns DEFAULT

def func():
    print('I am func(), and side_effect() called me!!')
    return  DEFAULT

4) Create the mock

 nice_print = 'I am a return value that side_effect() cannot override because 
               side_effect() returns special obj called DEFAULT'
 mocked_func = mock.Mock(side_effect=func, return_value=nice_print)

3) goodluck :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.