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
相关推荐
汽车仪器仪表相关领域17 小时前
重载工况制动闭环:NHZ-20 型加载式制动检测台机动车安全检测全场景实战指南
人工智能·单元测试·压力测试·可用性测试·安全性测试
Franciz小测测19 小时前
Pytest 并发分组执行引擎(支持UI / 接口自动化测试):从设计到工程落地
pytest
小猪咪piggy20 小时前
【接口自动化】(2) pytest 测试框架
运维·自动化·pytest
忘忧记20 小时前
Pytest + Requests + YAML 数据驱动+日志模块
网络·python·pytest
程序员三藏2 天前
软件测试:白盒测试详解
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
sg_knight2 天前
使用 Claude Code 写单元测试的实战方法
单元测试·log4j·ai编程
汽车仪器仪表相关领域2 天前
动态间隙精准诊断:NHJX-13 型底盘间隙仪机动车底盘安全检测全方案
大数据·人工智能·机器学习·单元测试·压力测试·可用性测试
清水白石0082 天前
pytest Fixture 设计实战指南:作用域、依赖链、自动清理与测试资源高效复用
python·pytest
亚马逊云开发者3 天前
Amazon Nova Act 浏览器自动化测试实战:AI 驱动的端到端测试 + pytest 集成 + OpenClaw 场景落地
人工智能·pytest