Skip to content

Instantly share code, notes, and snippets.

@torufurukawa
Created October 12, 2011 22:42
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/1282865 to your computer and use it in GitHub Desktop.
Save torufurukawa/1282865 to your computer and use it in GitHub Desktop.
setup と teardown を呼び出してくれる TestCase クラス
class CascadingTestCaseMeta(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 CascadingTestCase(unittest.TestCase):
__metaclass__ = CascadingTestCaseMeta
class TestBedTestCase(CascadingTestCase):
def _setup_testbed(self):
from google.appengine.ext import testbed
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
self.testbed.init_taskqueue_stub()
def _teardown_testbed(self):
self.testbed.deactivate()
def setUp(self):
self._setup_testbed()
def tearDown(self):
self._teardown_testbed()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment