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
相关推荐
nvd1139 分钟前
Pytest 异步数据库测试实战:基于 AsyncMock 的无副作用打桩方案
数据库·pytest
移幻漂流44 分钟前
Lua的现状与机遇:技术生态全景及高潜力领域分析
junit·单元测试·lua
开五档的蒙奇10 小时前
【单元测试】Junit5 + Mockito
单元测试
nvd1114 小时前
深入分析:Pytest异步测试中的数据库会话事件循环问题
数据库·pytest
程序员雷叔21 小时前
在postman设置请求里带动态token,看看这两种方法!
selenium·测试工具·单元测试·测试用例·pytest·lua·postman
花酒锄作田2 天前
[python]Flask - Tracking ID的设计
python·flask·pytest
测试秃头怪2 天前
Python测试框架Pytest的参数化
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
IMPYLH2 天前
Lua 的 String(字符串) 模块
开发语言·笔记·单元测试·lua
卓码软件测评2 天前
第三方软件确认测试机构【性能测试中内存泄漏的迹象:如何利用LoadRunner监控和发现 】
测试工具·ci/cd·性能优化·单元测试·测试用例
未定义.2212 天前
第7篇:跨端拓展!Playwright+Appium实现Web+移动端全覆盖
python·ui·appium·自动化·jenkins·pytest