help: Unit test fixture returning the same object

Michael McCracken michael_mccracken at mac.com
Tue Aug 3 19:33:26 EDT 2004


Hi, I have a problem with unittest.TestCase that I could really use
some help with.

I have a class File in module File. The important thing about File for
this discussion is that it's simple - no pool of objects are involved,
and subsequent invocations of File.File('filename') should return
distinct objects (and indeed, they do on the command line). Also,
__repr__ prints out the value of id(self) for File, so I can tell
what's going on here..

I also have a suite of tests that test File in testFile.py 
Within, I have a TestCase subclass that looks like this:

class FileReadingTestCase(unittest.TestCase):
    def setUp(self):
        self.testfilename = "filename" 
        self.testfile = File.File(self.testfilename)
        print 'setup:', self.testfile

    def tearDown(self):
        print 'teardown:', self.testfile
        self.testfile.close()
        self.testfile = None
	print 'teardown:', self.testfile

... followed by a bunch of tests that use self.testfile.

The problem is that in each test case, setUp and tearDown are called
as expected according to the print statements, but they don't seem to
have any effect after the first invocation. self.testfile is always
the same instance as reported by id().

There are two strange things going on here:
1 - in tearDown(), self.testfile is indeed being set to None, but in
the subsequent invocation of setUp(), self.testfile is pointing right
back to the same object.

2 - Of course, you can't print the value of self.testfile in setUp()
before it's assigned, that works as expected, but when calling the
constructor for File, you get the same object with the same id.

This doesn't happen in any other context, so I think there is
something about the unittest framework (or just Python) that I don't
understand. Does anyone have any insight?

my python is 2.3, as distributed with Mac OS X 10.3

Thanks,
-mike



More information about the Python-list mailing list