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
相关推荐
oliveira-time19 小时前
java单元测试代码
java·windows·单元测试
尽-欢1 天前
以太坊智能合约开发框架:Hardhat v2 核心功能从入门到基础教程
单元测试·区块链·智能合约
Allen Bright2 天前
【Java JUnit单元测试框架-60】深入理解JUnit:Java单元测试的艺术与实践
java·junit·单元测试
张张张3122 天前
4.29-4.30 Maven+单元测试
java·单元测试·maven
川石教育2 天前
Pytest中的fixture装饰器详解
python自动化测试·pytest·pytest自动化测试框架·pytest测试框架·pytest单元测试框架
春风又。3 天前
接口自动化——参数化
python·测试工具·自动化·pytest
川石课堂软件测试5 天前
涨薪技术|0到1学会性能测试第44课-apachetop模块监控
服务器·数据库·python·功能测试·性能优化·单元测试
XTY005 天前
mac电脑pytest生成测试报告
pytest
程序员的世界你不懂5 天前
pytest-前后置及fixture运用
pytest
song_ly0016 天前
软件测试52讲学习分享:深入理解单元测试
单元测试