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
相关推荐
回眸&啤酒鸭21 小时前
【回眸】搞钱灵感——智能体 汽车软件单元测试与集成测试
单元测试·汽车·集成测试
小龙飞刀3 天前
Chrome插件自动化测试:单元测试、集成测试
chrome·单元测试·集成测试
LayZhangStrive4 天前
claude code使用命令技巧(四)(开发沉淀的提示词模板)
ai·单元测试·prompt·ai编程·提示词·claude code
久久学姐6 天前
Python+Playwright+Pytest+BDD,用FSM打造高效测试框架
python·pytest·bdd·playwright·fsm
小白上线*^_^*6 天前
Pytest 自动化测试框架速通指南(二)
软件测试·pytest·python测试框架·ai测试基础
栈溢出的浪漫6 天前
Python单元测试框架覆盖率-Coverage
python·单元测试·工具·覆盖率·coverage
Logintern097 天前
pytest的AST 断言重写
pytest
名字还没想好☜7 天前
Go 表驱动测试实战:用 t.Run 子测试组织可维护的单元测试
golang·单元测试·log4j·go·testing
Dr.kangder7 天前
嵌入式软件单元测试:从理论到实践
架构·单元测试·嵌入式·测试覆盖率
Tinyfacture8 天前
接口自动化之添加商品(pytest)
python·测试工具·自动化·pytest