Skip to content

Instantly share code, notes, and snippets.

@danielrichman
Last active December 25, 2015 17:39
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 danielrichman/7014326 to your computer and use it in GitHub Desktop.
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
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