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
相关推荐
l***217816 小时前
Spring Boot 整合 log4j2 日志配置教程
spring boot·单元测试·log4j
未定义.22117 小时前
第1篇:0基础入门!Python+Selenium环境搭建与第一个自动化脚本
python·功能测试·selenium·自动化·jenkins·pytest
Lucifer__hell19 小时前
【Pytest】笔记
笔记·pytest·测试
旦莫20 小时前
使用OCR加持的APP自动化测试
python·测试开发·自动化·ocr·pytest·ai测试
工会主席-阿冰1 天前
在pytest-html页面,显示测试用例日志
pytest
川石课堂软件测试2 天前
Android和iOS APP平台测试的区别
android·数据库·ios·oracle·单元测试·测试用例·cocoa
大熊猫侯佩2 天前
Swift 6.2 列传(第十七篇):钟灵的“雷电蟒”与测试附件
单元测试·swift·apple
小二·2 天前
Python Web 开发进阶实战:全链路测试体系 —— Pytest + Playwright + Vitest 构建高可靠交付流水线
前端·python·pytest
卓码软件测评2 天前
软件首版次认定测试机构:【Apifox与UMI框架结合:实现OpenAPI规范与Mock服务的自动化流水线】
测试工具·ci/cd·性能优化·单元测试·测试用例