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
相关推荐
中智凯灵6 分钟前
采纳率从3%到80%:智能单元测试生成的进化之路
单元测试
汽车仪器仪表相关领域9 小时前
NHXJ-02汽车悬架检验台 实操型实战手册
人工智能·功能测试·测试工具·算法·安全·单元测试·可用性测试
我的xiaodoujiao1 天前
API 接口自动化测试详细图文教程学习系列9--Requests模块
python·学习·测试工具·pytest
我的xiaodoujiao1 天前
API 接口自动化测试详细图文教程学习系列10--Requests模块2--举例说明
python·学习·测试工具·pytest
程序员zgh1 天前
C/C++ 单元测试系统 构建
c语言·开发语言·c++·学习·单元测试
汽车仪器仪表相关领域1 天前
广州文明机电 新能源汽车运行安全性能检验解决方案
人工智能·功能测试·安全·单元测试·汽车·压力测试·可用性测试
兰.lan2 天前
【黑马ai测试】黑马头条登录功能测试-发布功能测试-其他功能模块设计
软件测试·人工智能·笔记·python·功能测试·ai·单元测试
超梦梦梦梦2 天前
playwright&pytest
pytest
淼淼7632 天前
Qt单元测试
单元测试
Parasoft中国3 天前
单元测试告别人工!PARASOFT步入AI智能体时代!
单元测试