Skip to content

Instantly share code, notes, and snippets.

@barahilia
Last active July 28, 2016 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barahilia/350f2c998199af6ef1b56536b431fa50 to your computer and use it in GitHub Desktop.
Save barahilia/350f2c998199af6ef1b56536b431fa50 to your computer and use it in GitHub Desktop.
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