Created
July 24, 2018 20:38
-
-
Save TomFaulkner/55c8b446eb5a111789157999dab2b57b to your computer and use it in GitHub Desktop.
Patch the parents of a class for unit testing
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
# source: https://stackoverflow.com/a/24577389/9893423 | |
# The MockFoo class still has the methods of the Foo class and it doesn't | |
# have the methods defined in the parent because the parent is now a Mock class. | |
from contextlib import contextmanager | |
@contextmanager | |
def patch_parent(class_): | |
""" | |
Mock the bases | |
""" | |
yield type(class_.__name__, (Mock,), dict(class_.__dict__)) | |
# After this, you can use the patch_parent like this: | |
class Bar(): | |
def method(self, param1, param2...): | |
pass | |
class Foo(Bar): | |
pass | |
with patch_parent(Foo) as MockFoo: | |
f = MockFoo() | |
print f | |
print f.method() | |
# <Foo id='15488016'> | |
# <Foo name='mock.method()' id='15541520'> | |
# >>> s = Foo() | |
# >>> s.method() | |
# Traceback (most recent call last): | |
# File "<stdin>", line 1, in <module> | |
# TypeError: method() takes exactly 3 arguments (1 given) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment