pytest unittest temp path单元测试创建临时文件

参考了这个:Test Files Creating a Temporal Directory in Python Unittests | Simple IT 🤘 Rocks

并使用pathlib做了优化:

python 复制代码
import tempfile
import unittest
from pathlib import Path


class TestExample(unittest.TestCase):
    def test_example(self):
        with tempfile.TemporaryDirectory() as tmpdirname:
            print("created temporary directory", tmpdirname)
            assert isinstance(tmpdirname, str)
            tmp_path = Path(tmpdirname)
            tmp_file = tmp_path / "output.txt"
            tmp_file.write_text("hehe")
            assert tmp_file.exists()
            assert tmp_file.read_text() == "hehe"


if __name__ == "__main__":
    unittest.main()

================

注:pytest的话,自带了tmp_path,直接用即可,例如

python 复制代码
# test_a.py
from pathlib import Path
def test_xxx(tmp_path):
    assert isinstance(tmp_path, Path)
    assert tmp_path.is_dir()
    p = tmp_path / 'a.txt'
    p.write_text('haha')
    assert p.read_text() == 'haha'
bash 复制代码
pytest test_a.py
相关推荐
虫无涯5 小时前
Coverity 如何结合 GJB8114-2013使用?
git·单元测试·嵌入式测试·coverity·静态扫描
茉莉玫瑰花茶2 天前
GO [ 单元测试 ]
golang·单元测试·log4j
测试员周周3 天前
【jev应用到测试】94 条 UI 报错交给 Jev,三档判对 85.1%,开单闸门定在 0.6
人工智能·python·测试工具·单元测试·测试用例
霍格沃兹测试学院-小舟畅学3 天前
AI+Swagger:一键生成500条pytest接口用例
人工智能·pytest
ebiobiz5 天前
STM32F4 Unity 单元测试与多次测试失败率统计详细步骤
stm32·unity·单元测试
Glitch4047 天前
LLM 数据管线缺陷实录:两个单元测试无法覆盖的运行时问题
单元测试
钱栈up7 天前
全量 21 个失败、单跑全绿:泄漏进连接池的 SQL 变量
sql·单元测试·测试
冬奇Lab7 天前
LLM 自动化测试系列(03):单元测试生成——TestGen-LLM 与 Qodo Cover
人工智能·单元测试·测试
慧都小项12 天前
Python 跨文件重构怎么验证?PyCharm 用法查找、重构预览与测试流程
python·重构·pycharm·单元测试
把头塞进显示器12 天前
电商平台-测试报告
python·selenium·pytest