Re: [Pyunit-interest] How to tearDown only after a failed test ?
Brought to you by:
purcell
From: Steve P. <ste...@ya...> - 2004-08-15 17:45:55
|
On Saturday 14 August 2004 21:26, Antoine Brenner wrote: > Hi ! > > Is there a (or more exactely what is the) way to run some kind of super > tearDown only after an error or a failure of a test ? > > I still need the regular tearDown after each test, but failed ones need > a special cleanup that is slow and unnecessary when tests run OK. Hi Antoine, This is not directly supported, but you can get the effect you want by wrapping test methods in an object that calls a clean-up method for you, as shown below. It's a bit hacky, and maybe in future it would be a good idea to add 'onFail()' hook methods to TestCase. Opinions, anyone? Best wishes, -Steve --------- import unittest class AddExceptionHook: def __init__(self, method, hook_method): self.method, self.hook_method = method, hook_method def __call__(self): try: return self.method() except: self.hook_method() raise class MyTestCase(unittest.TestCase): def tearDown(self): print "normal tearDown" def test_that_may_fail(self): raise Exception("deliberate failure") ## Additional tear-down hook def on_fail(): print "Tearing down because we failed" classmethod(on_fail) ## Add clean-up hooks to relevant methods test_that_may_fail = AddExceptionHook(test_that_may_fail, on_fail) if __name__ == '__main__': unittest.main() -- Steve Purcell http://www.pythonconsulting.com |