python - 如何经典地删除 TemporaryDirectory(没有 `with` 语句)
问题描述
Tempfile
with
通常与语句结合使用。我想在没有它的单元测试类中使用它。测试会创建许多不会相互干扰的文件。因此,我计划只创建一个临时目录,在其中将它们全部转储并在测试类完成时删除该目录。但是,我找不到如何删除 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
解决方案
推荐阅读
- amazon-web-services - Terraform 中的条件集参数
- sql - 如何在没有公共 ID 的情况下返回另一个表中尚不存在的行
- vue.js - 使用 Vue 和 Cypress 使用 Slots 测试组件
- php - 如何将变量名称链接到活动日志描述中?拉拉维尔 8
- java - 如何每 x 米在多边形内创建标记
- firebase - 请求被中止,因为没有可用的实例
- javascript - 如果在 Python 中解析后没有提取下载链接,如何从网站中提取链接。而且 href 属性是 javascript:void(0)
- identityserver4 - GetPropertiesOfSecretVersionsAsync 不包含“WhereAwait”的定义
- php - 什么时候应该使用 RedBean 连接到我的数据库?
- c# - 通过 HTTP 请求使用 C# 读取 Json