[Baypiggies] Question about unittest, setUp and suites
amax at redsymbol.net
Mon May 4 22:24:42 CEST 2009
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:
first_time = True
T.first_time = False
# initial setup
print '**doing first-time setup'
if '__main__' == __name__:
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__.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 , and possibly py.test as well .
More information about the Baypiggies