[TIP] cleanUp for unittest

jason pellerin jpellerin at gmail.com
Fri Apr 3 11:45:36 PDT 2009


On Fri, Apr 3, 2009 at 1:53 PM, Michael Foord <fuzzyman at voidspace.org.uk> wrote:
> Kumar McMillan wrote:
>> On Fri, Apr 3, 2009 at 12:16 PM, Michael Foord
>>
>>>> Doesn't matter to me, but I'm wondering... why a list of functions?
>>>>
>>>> --titus

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.

JP



More information about the testing-in-python mailing list