Skip to content

Instantly share code, notes, and snippets.

@torufurukawa
Created October 2, 2011 03:29
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 torufurukawa/1256990 to your computer and use it in GitHub Desktop.
Save torufurukawa/1256990 to your computer and use it in GitHub Desktop.
親クラスの setUp と tearDown を呼び出す TestCase クラス
import unittest
class TestCaseMeta(type):
"""Metaclass for TestCase class
This metaclass make setUp method calls all setUp methods in base classes
and then calls defined setUp method. Likewise tearDown but in opposite
order.
"""
def __init__(cls, name, bases, ns):
for method_name, reverse in [('setUp',False), ('tearDown', True)]:
setattr(cls, method_name,
cls._create_method(method_name, bases, ns, reverse=False))
@classmethod
def _create_method(self, method_name, bases, ns, reverse=True):
"""return a method that calls all methods with given name in class
hierarchy
"""
# create method sequence in parent and current classes
methods = [getattr(base, method_name, lambda self: None)
for base in bases]
methods.append(ns.get(method_name, lambda self: None))
# reverse order if necessary
if reverse:
methods.reverse()
# define method to call all methods
def call_methods(self):
for method in methods:
method(self)
# return the caller method
return call_methods
class TestCase(unittest.TestCase):
__metaclass__ = TestCaseMeta
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment