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
相关推荐
a1879272183114 小时前
Go-知识测试-工作机制
golang·单元测试·go·性能测试·go 测试·go 测试原理·示例测试
糖果店的幽灵17 小时前
基于Python的自动化测试框架-Pytest总结-第一弹基础
服务器·python·pytest
测试界吖吖1 天前
【pytest】html报告修改和汉化
自动化测试·软件测试·python·功能测试·程序人生·html·pytest
tekin1 天前
golang中空值判断函数,支持任意类型的空值判断
开发语言·golang·单元测试·go·函数·空值判断·isempty
测试19981 天前
Jmeter 进行http接口测试
自动化测试·软件测试·python·网络协议·jmeter·http·单元测试
ASOSO~1 天前
单元测试,一直转圈,既不报错也不运行结束(ssm junit4 test )
java·spring·junit·单元测试·mybatis
潇潇说测试2 天前
Python+requests+pytest+excel+allure 接口自动化测试实战
自动化测试·软件测试·python·功能测试·程序人生·excel·pytest
flysnow0102 天前
CppTest单元测试框架(更新)
单元测试·cpptest
G皮T3 天前
【单元测试】Controller、Service、Repository 层的单元测试
单元测试·service·controller·repository
a187927218313 天前
Go-知识测试-单元测试
golang·单元测试·go·单元测试原理·单元测试执行过程