-2

Using mock's capabilities within Python 3, I want to wrap a function and have it perform all of its normal functionality, and I simply want to mock its return value. In other words, I don't want to mock the entire function, just its return value, and I don't know how to make that happen.

def func():
    # do something
    # do something else
    # do lots of other things
    retval = 123
    return retval

with mock.patch('func') as mocked:
    mocked.return_value = 456
    # And now, I want to run the function so that when
    # it's called, "do something",  "do something else",
    # and "do lots of other things" still get performed,
    # but that 456 gets returned instead of 123.
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
HippoMan
  • 2,119
  • 2
  • 25
  • 48
  • 1
    That doesn't make any sense at all as a test. Are you trying to test `func`, or something that *calls* `func`? – jonrsharpe Mar 08 '18 at 15:55
  • What `func` does in my case is initialize logging in flask, create a logging object, and set up an exception handler. The logging object is used within the exception handler. Then, the function returns the logging object. I want to test it by having it perform all of its standard initialization, but to return a mocked logging object that I can use for unit testing the logger. – HippoMan Mar 08 '18 at 15:59
  • Those should be (at least) two separate tests, then. One calls the real `func` and makes sure it does the right things by mocking its collaborators. Another mocks out `func` and tests whatever is consuming the logging object. – jonrsharpe Mar 08 '18 at 16:01
  • Yes, that's what I've been doing. But I was hoping I could simplify this by simply mocking the return value. I guess this is not possible using standard `mock` facilities. – HippoMan Mar 08 '18 at 16:02
  • 1
    I'm not sure you've really understood the point of mocking: it allows you to test those two things in isolation. You should also integration test them working together, but then you wouldn't be mocking either of them. – jonrsharpe Mar 08 '18 at 16:04
  • You're right that this isn't strictly "mocking", and perhaps `mock` is the wrong tool for this purpose. Are there different python tools that might enable me to do what I want? And yes, integration testing is also being done. – HippoMan Mar 08 '18 at 16:05
  • It's not clear what you do want. Also recommendations for tools are off topic here. – jonrsharpe Mar 08 '18 at 16:06

1 Answers1

-1

I found this, which I had previously overlooked, and which allows me to do what I want:

How to call mocked method in Python mock

Thanks to jonrsharpe for helping me clarify what I am actually looking for.

This is but one of many unit and integration tests that are being performed, and I understand that it, in and of itself, is of limited (but not nonexistent) value.

HippoMan
  • 2,119
  • 2
  • 25
  • 48