3

How can I test that a python function was called, without changing its behavior at all ?

There are many related posts but I could not find one of them that covers it all:

Basically, I just need to spy the function to know whether or not it was called.

For instance, the following snippet has extremely surprising behavior

from unittest.mock import patch

def func(a,b):
    print('was called')
    return a * b

with patch('test.func') as patched_function:
    print(func(4,5))

print(patched_function.called)

Output:

<MagicMock name='func()' id='1721737249456'>
True
was called
20
False

While I was only expecting

was called
20
True
Overdrivr
  • 6,296
  • 5
  • 44
  • 70

1 Answers1

0

You should create a decorator for the function like so:

class CheckCall(object):
    called = False

    def __init__(self, func):
        self.func = func

    def __call__(self *args, **kwargs):
        self.called = True
        return self.func(*args, **kwargs)

Then you can apply your decorator like so

with patch('test.func') as patched_function:
    patched_function = CheckCall(patched_function)
    print(patched_function.called) # Prints False
    patched_function(...)
    print(patched_function.called) # Prints True
TDk
  • 1,019
  • 6
  • 18
  • I thought it would be already implemented in unittest. If there are no answers using unittest I'll accept yours – Overdrivr Aug 02 '17 at 17:23