[TIP] cleanUp for unittest

Kumar McMillan kumar.mcmillan at gmail.com
Fri Apr 3 12:00:18 PDT 2009

On Fri, Apr 3, 2009 at 1:45 PM, jason pellerin <jpellerin at gmail.com> wrote:
> Taking Michael's version of Kumar's example:
>> Yes - precisely; except in this particular example you would actually do:
>> def setUp(self):
>>    self.db = ScratchDb()
>>    self.db.setup()
>>    self.cleanUp.append(self.db.teardown)
>>    self.tmp = TempIO()
>>    self.cleanUp.append(self.tmp.destroy)
>> :-)
> This is why I don't like the list of funcs: it's engineered to support
> a particular use case that is not universal, and by making that case
> *very* slightly easier, we make handling all other use cases more
> complex, and make the api harder to explain.
> If you want the list of stuff for cleanup in cleanUp and cleanUp is
> just a method, you can do it like this:
> def setUp(self):
>      self._cleanUp = []
>      self.db = ScratchDb()
>      self.db.setup()
>      self._cleanUp.append(self.db.teardown)
>      self.tmp = TempIO()
>      self._cleanUp.append(self.tmp.destroy)
> def cleanUp(self):
>      for func in self._cleanUp:
>            func()
> IMO there's no reason to bake that pattern into unittest. Keep the core simple.

I know Python is all about giving you rope to hang yourself with, but
I really think a non-list version of cleanUp() would be setting up a
huge booby trap for the coder.  Since cleanUp() is called
*unconditionally* after setUp() there are infinite ways to screw that
up.  However, if cleanUp was a list of callables then there is really
no way to screw that up.

Also, as Michael pointed out too I don't think this is a specialized
use case.  I think it is maybe more common to only setup *one*
resource in setUp() but there will come a day when you setup two or
more resources.  It should be trivial to make the jump to setting up
two or more resources.

Again I'd like to emphasize that this new pattern is drastically
different from setUp() / tearDown() since tearDown() is designed to
rely on the fact that setUp() was successful.  That is the point of
having cleanUp as callables.


More information about the testing-in-python mailing list