Consider this test
import shutil, tempfile
from os import path
import unittest
from pathlib import Path
class TestExample(unittest.TestCase):
def setUp(self):
# Create a temporary directory
self.test_dir = tempfile.TemporaryDirectory()
self.test_dir2 = tempfile.mkdtemp()
def tearDown(self):
# Remove the directory after the test
shutil.rmtree(self.test_dir2)
shutil.rmtree(self.test_dir.name) #throws error
def test_something(self):
self.assertTrue(Path(self.test_dir.name).is_dir())
self.assertTrue(Path(self.test_dir2).is_dir())
if __name__ == '__main__':
unittest.main()
In tearDown
however an error is raised
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpxz7ts7a7'
which refers to self.test_dir.name
.
According to the source code for tempfile
, both elements are the same.
def __init__(self, suffix=None, prefix=None, dir=None):
self.name = mkdtemp(suffix, prefix, dir)
self._finalizer = _weakref.finalize(
self, self._cleanup, self.name,
warn_message="Implicitly cleaning up {!r}".format(self))
And I'm not using it within a context, so __exit__()
shouldn't be called as far as I understand.
What is happening?
tempfile
, which is the python module being used.temporary-files
can be misleading. – bluesmonk Jun 1 '18 at 19:09TemporaryDirectory
is automatically deleted when the corresponding object is garbage collected. That said, I have no idea why it's being garbage collected before thetearDown
function has finished executing. – Aran-Fey Jun 1 '18 at 19:16shutil.rmtree(self.test_dir.name)
and not the finalizer forself.test_dir
? have you tried not to clean it up, isn't it cleaned up when exiting context/when it's garbage collected? "On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem." – Jean-François Fabre♦ Jun 1 '18 at 19:16