title: Using a class decorator, how to override a method without redefining the class?
body: <p>For unit tests (using the <code>unittest</code> module) that use the <a href="http://code.google.com/appengine/docs/python/tools/localunittesting.html" rel="nofollow">App Engine testbed</a>, I need <code>setUp</code> and <code>tearDown</code> methods to activate and deactivate the testbed, respectively (slightly simplified):</p>
  
  <pre><code>class SomeTest(unittest.TestCase):
  
    def setUp(self):
      self.testbed = testbed.Testbed()
      self.testbed.activate()
  
    def tearDown(self):
      self.testbed.deactivate()
  
    def testSomething(self):
      ...
  </code></pre>
  
  <p>This quickly becomes a burden to write. I could write a base class <code>TestCaseWithTestbed</code>, but then I'd have to remember to call the superclass method each time I need a custom <code>setUp</code> in one of the test cases.</p>
  
  <p>I thought it would be more elegant to solve this with a class decorator instead. So I'd like to write:</p>
  
  <pre><code>@WithTestbed
  class SomeTest(unittest.TestCase):
  
    def testSomething(self):
      ...
  </code></pre>
  
  <p>With this decorator applied, the testbed should just be activated magically. So... how to implement the <code>WithTestbed</code> decorator? I currently have the following:</p>
  
  <pre><code>def WithTestbed(cls):
    class ClsWithTestbed(cls):
  
      def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        cls.setUp(self)
  
      def tearDown(self):
        cls.tearDown(self)
        self.testbed.deactivate()
  
    return ClsWithTestbed
  </code></pre>
  
  <p>This works for simple cases, but has some serious problems:</p>
  
  <ul>
  <li>The name of the test class becomes <code>ClsWithTestbed</code> and this shows up in the test output.</li>
  <li>Concrete test classes calling <code>super(SomeTestClass, self).setUp()</code> end up in an infinite recursion, because <code>SomeTestClass</code> is now equal to <code>WithTestbed</code>.</li>
  </ul>
  
  <p>I'm a bit hazy on Python's runtime type manipulation. So, how to do this the Right Way?</p>