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
相关推荐
Be reborn16 小时前
用例不是孤立执行的:依赖、变量池与 storage_state 设计
python·自动化·pytest
小陈的进阶之路17 小时前
安集商城接口自动化项目架构介绍
python·自动化·pytest
QH1392923188018 小时前
思仪 Ceyear 5256C 5G 终端综合测试仪
单片机·单元测试·集成测试·嵌入式实时数据库
测试员周周18 小时前
【Appium 系列】第08节-pytest 集成 — conftest.py 中的 fixture 与 hook
开发语言·人工智能·python·功能测试·appium·测试用例·pytest
Be reborn18 小时前
从一行 CSV 到一次浏览器操作:关键字驱动执行引擎设计
python·自动化·pytest
魔都吴所谓1 天前
【开源LiteReport】告别 JDK 依赖 -- 用 LiteReport 为 pytest 项目打造轻量级测试报告
开源·pytest
汽车仪器仪表相关领域2 天前
Debron OVM 1052 光学关门速度仪:汽车门盖检测的高精度便携工具 + 生产线适配 + 耐久性监测,整车制造与质量控制的黄金标准
人工智能·功能测试·单元测试·汽车·制造·可用性测试
Sandy_Star3 天前
1.9 民法典及社会保险法制度规定
单元测试
Sandy_Star3 天前
1.7 税务行政法律救济
大数据·单元测试
旦莫3 天前
AI驱动的纯视觉自动化测试:知识库里应该积累什么知识内容
人工智能·python·测试开发·pytest·ai测试