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
相关推荐
QH139292318806 小时前
KEYSIGHT E5071C 端网络分析仪
网络·功能测试·嵌入式硬件·物联网·单元测试·集成测试·模块测试
marsh020611 小时前
36 openclaw单元测试框架:编写可维护的测试代码
ai·单元测试·log4j·编程·技术
我的xiaodoujiao2 天前
API 接口自动化测试详细图文教程学习系列11--Requests模块3--测试练习
开发语言·python·学习·测试工具·pytest
川石课堂软件测试2 天前
requests接口自动化测试
数据库·python·功能测试·测试工具·单元测试·grafana·prometheus
我的xiaodoujiao2 天前
API 接口自动化测试详细图文教程学习系列12--Requests模块4--测试实践操作
python·学习·测试工具·pytest
汽车仪器仪表相关领域3 天前
GT-NHVR-20-A1工业及商业用途点型可燃气体探测器:精准感知隐患,筑牢工商业安全防线
运维·网络·人工智能·功能测试·单元测试·汽车·压力测试
Lightning-py4 天前
pytest 软断言的几种方式
pytest
Lightning-py4 天前
pytest后置处理方式
pytest
weixin_433179335 天前
Python -- 单元测试 unittest
python·单元测试