Skip to content

Instantly share code, notes, and snippets.

@barahilia

barahilia/tamper.py

Last active Jul 28, 2016
Embed
What would you like to do?
Tampering class method in python (temporarily replacing/mocking/faking for unit test)
import functools
def tamper(target, attr_name, mock_obj):
def decor(func):
@functools.wraps(func)
def worker(*args, **kwargs):
backup = getattr(target, attr_name)
try:
setattr(target, attr_name, mock_obj)
func(*args, **kwargs)
finally:
setattr(target, attr_name, backup)
return worker
return decor
def tamper_class_method(method, mock_obj):
"""Temporarily replace class method with another object
>>> class A:
... def foo(self):
... print 'foo', self
...
>>> A().foo()
foo
>>> def goo(self): print 'goo', self
...
>>> @tamper(A.foo, goo)
... def test():
... A().foo()
...
>>> test()
goo
"""
target = method.im_class
attr_name = method.im_func.__name__
return tamper(target, attr_name, mock_obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment