[Baypiggies] Question about unittest, setUp and suites

Shannon -jj Behrens jjinux at gmail.com
Tue May 5 01:59:04 CEST 2009

On Mon, May 4, 2009 at 1:24 PM, Aaron Maxwell <amax at redsymbol.net> wrote:
> Hi Herbert.
> On Monday 04 May 2009 11:29:26 am Herbert Pfennig wrote:
>> Hi All,
>> Long time lurker with a simple question about unittest. I have googled
>> around and have not really found a good answer to the following question.
>> How do I define a _setUp_ that only get's called before a suite of tests is
>> run? (_not_ for every test)
> I believe that using a global like you did is the best approach under plain
> unittest.  An alternative is to use a class variable:
> {{{
> import unittest
> class T(unittest.TestCase):
>    first_time = True
>    def setUp(self):
>        if T.first_time:
>            T.first_time = False
>            # initial setup
>            print '**doing first-time setup'
>    def test_a(self):
>        self.assertTrue(True)
>    def test_b(self):
>        self.assertTrue(True)
> if '__main__' == __name__:
>    unittest.main()
> }}}
> It's less maintainable because the class name appears 3 times, and you have to
> remember somehow to update all 3 if it changes.  A workaround is to use
> self.__class__ instead:
> {{{
>    def setUp(self):
>        if self.__class__.first_time:
>            self.__class__.first_time = False
> }}}
> Some people, like myself, would prefer the global-variable method anyway.  To
> me it seems easier to understand quickly when I look at the code again weeks
> later.  In particular, setting the class attribute is kind of obscure - it
> does what you need because of how unittest processes test cases, but if
> you're not familiar with those internals, you might look at it and go, "Huh?
> how come this works?"  Maybe you could encapsulate it in a well-documented
> function or method.
> Anyway, some other test frameworks that build upon unittest have explicit
> support for this test pattern, so if you're doing this a lot you might want
> to look into them.  Nose in particular [0], and possibly py.test as well [1].
> [0] http://somethingaboutorange.com/mrl/projects/nose/
> [1] http://codespeak.net/py/dist/test/test.html

This is one of the things I prefer about Nose.  Go
http://somethingaboutorange.com/mrl/projects/nose/, and look for
"setup".  You can do both per-module and per-test setup and teardown.

Best Regards,

In this life we cannot do great things. We can only do small things
with great love. -- Mother Teresa

More information about the Baypiggies mailing list