On Fri, Feb 22, 2008 at 2:43 AM, Giampaolo Rodola' <gnewsg at gmail.com> wrote: > On 21 Feb, 12:30, "Virgil Dupras" <hs... at hardcoded.net> wrote: > > Hi devs, > > > > > > Specifically, I'd like to know about files managements in tests. Is > > every test expected to clean after itself, or is there an automatic > > cleanup mechanism in place? > > 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') > ... > This is a little off-topic but FWIW, bzrlib.tests.TestCase and Twisted's TestCase have a nice helper method called 'addCleanup' that adds a nullary callable to a stack of callable that get popped off and run at the start of tearDown. That would allow your example to be rewritten as: from test.test_support import TESTFN, unlink import unittest class TestCase(unittest.TestCase): def open_file(self, filename, mode): opened_file = open(filename, mode) def close_and_delete(): opened_file.close() unlink(filename) self.addCleanup(close_and_delete) return opened_file def test_something(self): file = self.open_file(TESTFN, 'r') ... This isn't any shorter, but now you can open as many files as you want. It also keeps clutter out of setUp and tearDown. jml
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4