views:

46

answers:

2

Am doing a bit of unit testing on a function which attempts to open a new file, but should fail if the file already exists. when the function runs sucessfully, the new file is created, so i want to delete it after every test run, but it doesn't seem to be working:

class MyObject_Initialisation(unittest.TestCase):
    def setUp(self):
        if os.path.exists(TEMPORARY_FILE_NAME):
            try:
                os.remove(TEMPORARY_FILE_NAME)
            except WindowsError:
                #TODO: can't figure out how to fix this...
                #time.sleep(3)
                #self.setUp() #this just loops forever
                pass

    def tearDown(self):
        self.setUp()

any thoughts? The Windows Error thrown seems to suggest the file is in use... could it be that the tests are run in parallel threads?

I've read elsewhere that it's 'bad practice' to use the filesystem in unit testing, but really? Surely there's a way around this that doesn't invole dummying the filesystem?

+1  A: 

If you're just looking for a temporary file, have a look at tempfile - this should handle the clean-up all on its own.

Oli
actually, the .dispose() method i found earlier didn't reliably release file system resources. the tempfile framework seems to provide a neater solution (albeit one that involves giving up on creating and tidying my tempfiles manually, or knowing how to properly release resources)
hwjp
Ignorance is bliss. If it works, it works ;)
Oli
+1  A: 

Do you remember to explicitly close file handler that operates on TEMPORARY_FILE_NAME?

From Python Documentation:

On Windows, attempting to remove a file that is in use causes an exception to be raised;

zifot
hi, that's pretty much right - although i don't explicitly open a file handler, i wasn't tidying up properly in my tests. i eventually found a .dispose() method in the sqlalchemy api i was using that releases the connection and the lock on the file, so the os.removes now work fine.
hwjp