首页 > 解决方案 > 如何经典地删除 TemporaryDirectory(没有 `with` 语句)

问题描述

Tempfilewith通常与语句结合使用。我想在没有它的单元测试类中使用它。测试会创建许多不会相互干扰的文件。因此,我计划只创建一个临时目录,在其中将它们全部转储并在测试类完成时删除该目录。但是,我找不到如何删除 tearDownClass(cls) 中的 TemporaryDirectory?我必须做任何事情吗。有更好的方法吗?


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

标签: pythonpython-unittesttemporary-files

解决方案


推荐阅读