Last active
December 25, 2015 17:39
-
-
Save danielrichman/7014326 to your computer and use it in GitHub Desktop.
re-base a class that uses super() in order to unit test it
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
from __future__ import print_function | |
# some library | |
class Base(object): | |
def method(self): | |
return "This is hard to stub" | |
# my code | |
class UUT(Base): | |
def method(self): | |
return "I want to unit test this class " + super(UUT, self).method() | |
print("Vanilla:", UUT().method()) | |
# my tests | |
class MockBase(object): | |
def method(self): | |
return "stubbed!" | |
class Rebaser(type): | |
def __new__(mcs, name, bases, dict): | |
bases += (MockBase, ) | |
return type.__new__(mcs, name, bases, dict) | |
def mro(cls): | |
return (cls, UUT, MockBase) + UUT.__mro__[1:] | |
class TestThis2(UUT): | |
__metaclass__ = Rebaser | |
print("Test:", TestThis2().method()) | |
# output: | |
# Vanilla: I want to unit test this class This is hard to stub | |
# Test: I want to unit test this class stubbed! | |
# (<class '__main__.TestThis2'>, <class '__main__.UUT'>, | |
# <class '__main__.MockBase'>, <class '__main__.Base'>, | |
# <type 'object'>) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment