[Python-Dev] Unit Test Guide

Neal Norwitz nnorwitz at gmail.com
Fri Feb 22 05:56:20 CET 2008


On Thu, Feb 21, 2008 at 7:43 AM, Giampaolo Rodola' <gnewsg at gmail.com> wrote:
>
>  I have usually seen a lot of tests implemented like this:
>
>  from test.test_support import TESTFN, unlink
>  import unittest
>
>  class TestCase(unittest.TestCase):
>
>     def setUp(self):
>         self.file = None
>
>     def tearDown(self):
>         if self.file is not None:
>             self.file.close()
>         unlink(TESTFN)
>
>     def test_something(self):
>         self.file = open(TESTFN, 'r')
>         ...

Yes, but this is not as robust as it could be.  It's better to also
unlink/rmtree in the setUp.  That way if the file doesn't get cleaned
up (interpreter crash, KeyboardInterrupt, file not closed on Windows,
exception in tearDown, etc), the test won't fail on the next run or
the next test that assumes TESTFN doesn't exist won't fail.

n


More information about the Python-Dev mailing list