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
相关推荐
啊森要自信8 小时前
【GUI自动化测试】YAML 配置文件应用:从语法解析到 Python 读写
android·python·缓存·pytest·pip·dash
我的xiaodoujiao12 小时前
从 0 到 1 搭建完整 Python 语言 Web UI自动化测试学习系列 17--测试框架Pytest基础 1--介绍使用
python·学习·测试工具·pytest
lifewange13 小时前
幂等机制
功能测试·单元测试
=>>漫反射=>>1 天前
单元测试 vs Main方法调试:何时使用哪种方式?
java·spring boot·单元测试
程序员杰哥2 天前
Pytest与Unittest测试框架对比
自动化测试·软件测试·python·测试工具·测试用例·excel·pytest
软件测试小仙女2 天前
Pytest参数化实战:高效测试API接口
软件测试·测试开发·测试工具·pytest·接口测试·api·参数化
子正2 天前
Pytest单元测试一例:u16采样值格式转换的错误
单元测试·pytest
另寻沧海2 天前
测试中的 AAA 模式与 Given–When–Then 模式详解
c++·单元测试·测试覆盖率
cllsse2 天前
pytest学习
软件测试·python·pytest
寒月霜华2 天前
java-高级技术(单元测试、反射)
java·开发语言·单元测试·反射