1

Tempfile is normaly used in combination with the with statement. I would like to use it without it in a unittest class. The tests create a number of files which do not interfer with each other. Thus, I planned to just create a temp dir in which I dump them all and remove the dir when the test class finished. However, I could not find how to remove the TemporaryDirectory in tearDownClass(cls)? Do I have to do anything at all. Is there a better approach?


import pathlib
import tempfile
import unittest


class MyTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls) -> None:
        cls.temp_dir = tempfile.TemporaryDirectory()

    @classmethod
    def tearDownClass(cls) -> None:
        # How can I close the tempfile here?
        # cls.temp_dir.close() <- does not exist

    def test_save_file(self):
        file_path = pathlib.Path(temp_dir.name) / "my_file.abc"
        # Function which saves stuff into file

    # more tests which store other files into the temp_dir

Molitoris
  • 935
  • 1
  • 9
  • 31

0 Answers0