Want to call a method only once for unittest.TestCase--but not sure how?

Scott David Daniels Scott.Daniels at Acm.Org
Mon Sep 28 10:52:13 EDT 2009


Oltmans wrote:
> ... All of our unit tests are written using built-in 'unittest'
> module. We've a requirement where we want to run a method only once
> for our unit tests....
 > So I'm completely stumped as to how to create a method that will only
 > be called only once for Calculator class. Can you please suggest any
 > ideas? Any help will be highly appreciated. Thanks in advance.

Just inherit your classes from something like (untested):

     class FunkyTestCase(unittest.TestCase):
         needs_initial = True

         def initialize(self):
             self.__class__.needs_initial = False

         def setUp(self):
             if self.needs_initial:
                 self.initialize()


And write your test classes like:

     class Bump(FunkyTestCase):
         def initialize(self):
             super(Bump, self).initialize()
             print 'One time Action'
         ...

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list