Template method invocation order in python
-
03-07-2021 - |
Question
What would be the simplest way to unit-test run function? Here I'm not interested in what fun* functions do, but only if the order of their invocation is correct.
from mock import Mock
(many, arguments, four, fun) = ('many', 'arguments', 'four', 'fun')
class TemplateMethod(object):
def fun1(self, many, parameters, go, here):
raise NotImplementedError()
@classmethod
def fun2(cls, many, parameters, go, here):
pass
@staticmethod
def fun3(many, parameters, go, here):
pass
def run(self):
result1 = self.fun1(many, arguments, four, fun)
result1.do_something()
self.fun2(many, arguments, four, fun)
self.fun3(many, arguments, four, fun)
The only requirement for the solution is non-intrusiveness towards the class under test.
SOLUTION:
This is somewhat of a draft, actually, and this simple class could be fixed and extended in so many ways that I don't care even to think about it. The point is that you can now simply record all the invocations of all the methods in a template method. You can also specify a list of object that shouldn't be mocked by the class (i.e. the function you are recording invocations for).
Special thanks go to @Damian Schenkelman, who gave me some important pointers.
class MockingInvocationRecorder(object):
FUNCTION_TYPES = ('function', 'classmethod', 'staticmethod')
def __init__(self, obj, dont_mock_list):
self._invocation_list = []
name_list = [exc.__name__ for exc in dont_mock_list]
self._wrap_memfuns(obj, name_list)
@property
def invocations(self):
return tuple(self._invocation_list)
def _wrap_single(self, memfun, exclude_list):
def wrapper(*args, **kwargs):
self._invocation_list.append(memfun.__name__)
if memfun.__name__ in exclude_list:
return memfun(*args, **kwargs)
else:
return Mock()
return wrapper
def _wrap_memfuns(self, obj, exclude_list):
for (mem_name, mem) in type(obj).__dict__.iteritems():
if type(mem).__name__ in self.FUNCTION_TYPES:
wrapper = self._wrap_single(getattr(obj, mem_name), exclude_list)
setattr(obj, mem_name, wrapper)
You can now test invocation order by something like this:
tm = TemplateMethod()
ir = MockingInvocationRecorder(tm, [tm.run])
tm.run()
print ir.invocations => ('run', 'fun1', 'fun2', 'fun3')
You can reference a member by class name:
ir = MockingInvocationRecorder(tm, [TemplateMethod.run])
Just be careful that you enlist all the methods that shouldn't be mocked away.
Solution
Monkeypatch fun1, fun2, fun3 functions and use a list to keep track of the call order. After that, assert on the list.
OTHER TIPS
Making use of __call__
could be helpful here.
class Function1(object):
def __call__(self, params, logger=None):
if logger is not None:
logger.append(self.__repr__())
return self.function1(params)
# Or no return if only side effects are needed
def __init__(self, ...):
#...
def __repr__(self):
# Some string representation of your function.
def function1(params):
print "Function 1 stuff here..."
Then do something like
class TemplateMethod(object):
def __init__(self, params):
self.logger = []
self.fun1 = Function1(...)
self.fun1(params, self.logger)
This is pretty hacky; there's probably some ways to clean up what I'm getting at, but encapsulating the functions in classes and then using __call__
is a good way to go.