[TIP] cleanUp for unittest
Michael Foord
fuzzyman at voidspace.org.uk
Fri Apr 3 10:53:08 PDT 2009
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
>>>
>>>
>> I should have listed the relevant issue: http://bugs.python.org/issue5538
>>
>> The idea is that as you allocate resources that need cleaning up, you
>> push the corresponding clean up function onto the list. It is what trial
>> uses.
>>
>> It sounds like a very simple system to me.
>>
>
> The idea as I understand it is that you would build the list of clean
> up functions dynamically. I could be wrong though as I don't use
> Trial much.
>
> E.G.
>
> 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())
>
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)
:-)
Michael
> vs. one cleanUp method, which could get very ugly with all the if
> statements you would need to ensure it is safe to clean up a resource
> that may or may not exist:
>
> def cleanUp(self):
> if hasattr(self, 'db'):
> self.db.teardown()
> if hasattr(self, 'tmp'):
> self.tmp.destroy()
>
> the problem cleanUp solves that tearDown cannot currently solve is,
> for example, this scenario : self.db.setup() succeeds but TempIO()
> does not. In today's world tearDown() would not get called so you
> would be left with a database that was never torn down.
>
--
http://www.ironpythoninaction.com/
http://www.voidspace.org.uk/blog
More information about the testing-in-python
mailing list