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
相关推荐
云半S一9 小时前
春招准备之测试场景面试篇
单元测试
i***132416 小时前
【SpringBoot】单元测试实战演示及心得分享
spring boot·后端·单元测试
fzm529818 小时前
嵌入软件单元测试的全面研究与实践
自动化测试·单元测试·汽车·嵌入式·白盒测试
Mr_Xuhhh18 小时前
pytest -- 测试报告allure
pytest
汽车仪器仪表相关领域18 小时前
PSB-1:安全增压与空燃比双监控仪表 - 高性能引擎的 “双重安全卫士“
java·人工智能·功能测试·单元测试·汽车·可用性测试·安全性测试
程序员威子19 小时前
最强平替Postman的工具,拒绝浏览器套壳
功能测试·selenium·测试工具·jmeter·单元测试·测试用例·postman
i***132419 小时前
Spring Boot 整合 log4j2 日志配置教程
spring boot·单元测试·log4j
卓码软件测评21 小时前
第三方CNAS软件测试评测机构:【软件测试工具Apifox中的WebSocket接口测试从入门到精通】
websocket·网络协议·测试工具·单元测试·测试用例
3***C7441 天前
Spring Boot 整合 log4j2 日志配置教程
spring boot·单元测试·log4j
IMPYLH2 天前
Lua 的 rawset 函数
开发语言·笔记·单元测试·lua