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
相关推荐
汽车仪器仪表相关领域8 小时前
GT-NHVR-20-A1工业及商业用途点型可燃气体探测器:精准感知隐患,筑牢工商业安全防线
运维·网络·人工智能·功能测试·单元测试·汽车·压力测试
Lightning-py1 天前
pytest 软断言的几种方式
pytest
Lightning-py1 天前
pytest后置处理方式
pytest
weixin_433179331 天前
Python -- 单元测试 unittest
python·单元测试
方安乐2 天前
单元测试之helper函数
前端·javascript·单元测试
测试老哥2 天前
白盒测试用例的设计
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
爆更小哇2 天前
Python自动化测试:pytest新手快速入门指南
python·测试工具·自动化·pytest
qq_452396232 天前
第一篇:基座选型 —— 为什么 Pytest 是自动化的终点?
自动化·pytest
好大哥呀2 天前
单元测试自动化的流程
运维·单元测试·自动化
时光不写代码3 天前
修复 pytest-asyncio 事件循环冲突:完整解决方案
python·pytest·fastapi