Instantly share code, notes, and snippets.

What would you like to do?
re-base a class that uses super() in order to unit test it
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