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
相关推荐
Apifox.13 分钟前
测试用例越堆越多?用 Apifox 测试套件让自动化回归更易维护
运维·前端·后端·测试工具·单元测试·自动化·测试用例
潇凝子潇2 小时前
在 Maven 中跳过单元测试进行本地打包或排除某个项目进行打包
java·单元测试·maven
凯子坚持 c2 小时前
C++大模型SDK开发实录(二):DeepSeek模型接入、HTTP通信实现与GTest单元测试
c++·http·单元测试
大熊猫侯佩2 小时前
Swift 6.2 列传(第十八篇·大结局):冯衡的“过目不忘”与语言的圆满
单元测试·macro·test·evaluate·swift testing·swift 6.2·大结局
不吃鱼的羊2 小时前
单元测试基础
单元测试
纯纯沙口17 小时前
pytest - 基础使用教程
pytest
oscar99920 小时前
CI_CD 管道:是什么、为什么以及如何构建
ci/cd·单元测试·压力测试
问道飞鱼1 天前
【自动化测试】pytest 语法与核心概念
自动化测试·pytest·playwright
zUlKyyRC1 天前
基于一阶RC模型,FFRLS+EKF算法的电池SOC在线联合估计Matlab程序
pytest
卓码软件测评2 天前
软件信创测试和软件首版次认定机构【使用Postman的Pre-request Script动态处理数据】
测试工具·ci/cd·性能优化·单元测试·测试用例