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
相关推荐
淼_@淼19 小时前
pytest-数据驱动
pytest
我的xiaodoujiao1 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 27--二次封装方法--优化断言结果
python·学习·测试工具·pytest
꧁༺℘₨风、凌๓༻꧂1 天前
C# MES .NET Framework Winform 单元测试
单元测试·c#·.net
IMPYLH2 天前
Lua 的 pairs 函数
开发语言·笔记·后端·junit·单元测试·lua
倚肆2 天前
Spring Boot 测试注解全解:从单元测试到集成测试
spring boot·单元测试·集成测试
安冬的码畜日常2 天前
【JUnit实战3_35】第二十二章:用 JUnit 5 实现测试金字塔策略
测试工具·junit·单元测试·集成测试·系统测试·bdd·测试金字塔
码农BookSea3 天前
用好PowerMock,轻松搞定那些让你头疼的单元测试
后端·单元测试
少云清3 天前
【软件测试】5_测试理论 _软件测试分类(重点)
软件测试·单元测试·uat测试·sit测试
淼_@淼4 天前
pytest简介
运维·服务器·pytest
秃了也弱了。4 天前
testng:Java界功能强大的单元测试框架
java·单元测试·log4j