Last active
July 28, 2016 06:46
-
-
Save barahilia/350f2c998199af6ef1b56536b431fa50 to your computer and use it in GitHub Desktop.
Tampering class method in python (temporarily replacing/mocking/faking for unit test)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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