Questions on unittest behaviour
Roy Smith
roy at panix.com
Sat Aug 19 10:08:49 EDT 2006
In article <mailman.9529.1155958679.27775.python-list at python.org>,
"Collin Winter" <collinw at gmail.com> wrote:
> While working on a test suite for unittest these past few weeks, I've
> run across some behaviours that, while not obviously wrong, don't
> strike me as quite right, either. Submitted for your consideration:
>
> 1) TestCase.tearDown() is only run if TestCase.setUp() succeeded. It
> seems to me that tearDown() should always be run, regardless of any
> failures in setUp() or the test method itself.
I look at setUp() as a constructor. It's the constructor's job to either
completely construct an object, or clean up after itself. With your
example:
> > def setUp(self)
> > lock_file(testfile) # open_socket(), connect_to_database(), etc
> >
> > something_that_raises_an_exception()
> >
> > def tearDown(self):
> > if file_is_locked(testfile):
> > unlock_file(testfile)
It would be cleaner to just do:
def setUp(self):
lock_file()
try:
something_that_raises_an_exception()
except
unlock_file()
raise
> In this pseudo-code example, the file won't be unlocked if some later
> operation in setUp() raises an exception. I propose that
> TestCase.run() be changed to always run tearDown(), even if setUp()
> raise an exception.
While this might simplify setUp() methods, it complicates tearDown()s,
because now they can't be sure what environment they're running in. One
way or the other, somebody has to deal with exceptions in setUp(). Keeping
the exception handling code as close to the source of the exception seems
like the right thing to do.
More information about the Python-list
mailing list