[TIP] cleanUp for unittest

Michael Foord fuzzyman at voidspace.org.uk
Fri Apr 3 10:56:46 PDT 2009

Victoria G. Laidler wrote:
> Kumar's example code:
>> def setUp(self):
>>    self.db = ScratchDb()
>>    self.db.setup()
>>    self.cleanUp.append(lambda: self.db.teardown())
>>    self.tmp = TempIO()
>>    self.cleanUp.append(lambda: self.tmp.destroy())
> This looks clean to me except for the lambda, which I don't understand 
> - help?

There is no need for the lambdas in the above example.

> and I'm dithering on whether I think it ought to be a list, as 
> proposed, or something else.
> My usual case for cleanup behavior is file deletion, with different 
> files to be deleted depending on how far I got. Would this work?
> self.cleanUp.append(os.unlink(somefile))

You do need a lambda (or function) to do this however. :-)

self.cleanUp.append(lambda: os.unlink(somefile))

The benefit of cleanUp as a list is precisely that you can just push 
clean up tasks like this onto the queue without having to track how far 
your test got - or wrap each resource allocation in a try finally.


> Vicki


More information about the testing-in-python mailing list