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
相关推荐
花酒锄作田14 小时前
[python]Flask - Tracking ID的设计
python·flask·pytest
测试秃头怪16 小时前
Python测试框架Pytest的参数化
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
IMPYLH17 小时前
Lua 的 String(字符串) 模块
开发语言·笔记·单元测试·lua
卓码软件测评1 天前
第三方软件确认测试机构【性能测试中内存泄漏的迹象:如何利用LoadRunner监控和发现 】
测试工具·ci/cd·性能优化·单元测试·测试用例
未定义.2211 天前
第7篇:跨端拓展!Playwright+Appium实现Web+移动端全覆盖
python·ui·appium·自动化·jenkins·pytest
移幻漂流1 天前
Lua关键字全解析:从基础到精通的语义指南
junit·单元测试·lua
未定义.2212 天前
第5篇:进阶优化:数据驱动+日志体系+失败重试实战
python·ui·自动化·jenkins·集成测试·pytest
未定义.2212 天前
第4篇:企业级框架搭建,Pytest+PO模式从0到1实战
python·ui·自动化·jenkins·集成测试·pytest
文人sec2 天前
pytest2-Allure自动化测试报告
python·功能测试·自动化·pytest