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
相关推荐
lierenvip17 小时前
Spring Boot 整合 log4j2 日志配置教程
spring boot·单元测试·log4j
工具人555518 小时前
pytest练习
pytest
武超杰19 小时前
SpringBoot 进阶实战:异常处理、单元测试、多环境、日志配置全解析
spring boot·单元测试·log4j
好家伙VCC20 小时前
# Pytest发散创新:从基础测试到智能断言的实战进阶指南在现代软
java·python·pytest
Samson Bruce20 小时前
【单元测试】
单元测试·log4j
小旭952720 小时前
SpringBoot 技能实战:异常处理、单元测试、多环境配置、日志
spring boot·后端·单元测试
咸鱼豆腐1 天前
Clawdbot惊艳案例:Qwen3-32B自动生成带单元测试的Python模块并执行验证
单元测试·大语言模型·ai编程·代码生成
钛态1 天前
Flutter for OpenHarmony:mockito 单元测试的替身演员,轻松模拟复杂依赖(测试驱动开发必备) 深度解析与鸿蒙适配指南
服务器·驱动开发·安全·flutter·华为·单元测试·harmonyos
小罗和阿泽2 天前
GUI 自动化测试 pywinauto测试框架
开发语言·python·功能测试·测试工具·pytest
华科易迅2 天前
Spring 单元测试
java·spring·单元测试