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
相关推荐
lucia_zl11 小时前
pytest并发测试,资源问题导致用例失败解决办法
pytest
鱼鱼说测试14 小时前
Selenium4+Pytest自动化测试框架实战
pytest
云动雨颤1 天前
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
python·单元测试
Suresoft China2 天前
软件测试|STATIC 代码静态验证工具 C/C++ 工具链设置指南
c++·单元测试·静态测试·测试覆盖率·static·代码覆盖率·工具链设置
itppxie3 天前
Simulink中使用Test sequence单元测试
单元测试
泛联新安3 天前
如何根据项目需求选择合适的软件测试工具?iUnit智能单元测试平台提供专业化解决方案
c++·测试工具·单元测试
EndingCoder4 天前
单元测试:Jest 与 Electron 的结合
javascript·electron·单元测试·前端框架
奔跑吧邓邓子5 天前
【Java实战㉖】深入Java单元测试:JUnit 5实战指南
java·junit·单元测试·实战·junit5
川石课堂软件测试5 天前
Oracle 数据库使用事务确保数据的安全
数据库·python·功能测试·docker·oracle·单元测试·prometheus