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
相关推荐
DJ斯特拉1 天前
Redis使用lua脚本
junit·单元测试·lua
念越1 天前
蓝桥杯单元测试模拟1期模拟题答案及代码解析
蓝桥杯·单元测试·测试
不明觉厉二十年1 天前
pytest+pywinauto+pycharm制作mobaxterm 字符串快捷发送器 Demo
ide·pycharm·pytest
AIminminHu2 天前
OpenGL渲染与几何内核那点事-项目实践理论补充(三-1-(2):当你的CAD代码变得“又大又乱”:从手动编译到CMake,从随性编码到单元测试))
c++·单元测试·cmake·cad·cad开发
DolphinDB智臾科技3 天前
DolphinDB 单元测试教程
单元测试
春日见3 天前
TEST文件夹:Pytest,集成测试,单元测试
服务器·人工智能·驱动开发·单元测试·计算机外设·集成测试·pytest
TRACER~853 天前
项目实战:pandas+pytest+allure+adb
adb·pandas·pytest
川石课堂软件测试3 天前
涨薪技术|Prometheus使用Recoding Rules优化性能
功能测试·测试工具·jmeter·mysql·面试·单元测试·prometheus
龙智DevSecOps解决方案3 天前
TESSY v5.1 新功能详解 :引入 Hyper Coverage 与基于变更的测试,大幅缩短 CI 测试时间
自动化测试·软件测试·ci/cd·单元测试·嵌入式开发·tessy