[TIP] setUp and tearDown behavior

Olemis Lang olemis at gmail.com
Tue Jan 19 06:40:48 PST 2010


On Tue, Jan 19, 2010 at 9:06 AM, Michael Foord
<fuzzyman at voidspace.org.uk> wrote:
> On 19/01/2010 13:53, Olemis Lang wrote:
>>
>> [snip...]
>>>
>>> In case this is expected, is there a way to do it just once for all the
>>> methods?
>>>
>>
>> Using standard `unittest` module ? well ... no.
>
> Well - you can make setup *effectively* only run the first time using a
> class attribute:
>
>
> class SomeTest(unittest.TestCase):
> doneSetup = False
> def setUp(self):
> if not self.__class__.doneSetup:
> self.__class__.doneSetup = True
> self.setUpClass()
> ...
>

Ok, you're right. Let me say it somehow different :

  `unittest` does not provide support to do that OOTB just like you'd
  do it with JUnit `AfterClass` and `BeforeClass` annotations . There
  are ways (beyond the API ;o) to get it done, or you could use a
  testing framework compatible with `unittest` ...

> Making tearDown only run the *last* time is a bit harder

Yes, and there's also another puzzle that I've not been able to solve
(I have some candidates ;o):

Q:
  - What happens if an exception is raised inside suite-level
`tearDown` method ?

> (you could hack it
> in with a counter in setUp and only execute tearDown when the counter ==
> number of test methods).

What I'd do in this case is to implement that behavior in a custom
test suite thus having a more flexible way to control the scope of the
shared fixture (e.g. span over multiple test classes ...)

;o)

> Builtin support for class level fixtures in
> unittest would be good,

... and provide shortcuts like `AfterClass` and `BeforeClass` but
using the more general infrastructure.

> even if they are ripe for abuse (shared state
> between fixtures).
>

Something that practical people use and need (e.g. something like that
can be found in Trac test code to solve problems similar to that ones
I mentioned before, and Trac devs are much more «practical» than
myself ).

> All the best,
>

:o)

PS: Don't worry . Just my opinion, not a suggestion for stdlib .

-- 
Regards,

Olemis.

Blog ES: http://simelo-es.blogspot.com/
Blog EN: http://simelo-en.blogspot.com/

Featured article:
New! Writing doctests for Trac plugins WAS: [Trac] Re: Writing ...  -
http://feedproxy.google.com/~r/TracGViz-full/~3/_wCvZJTu--s/msg00152.html



More information about the testing-in-python mailing list