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
相关推荐
许彰午11 天前
39_Java单元测试JUnit入门
java·junit·单元测试
果子耶耶11 天前
让大模型帮我写单元测试,5个模型的覆盖率和边界处理能力实测
chatgpt·单元测试
糖果店的幽灵12 天前
软件测试接口测试从入门到精通:Python接口自动化 - pytest测试框架
软件测试·python·功能测试·自动化·pytest·接口测试
川石课堂软件测试12 天前
APP自动化测试|高级手势操作&toast操作
css·功能测试·测试工具·microsoft·fiddler·单元测试·harmonyos
2601_9618752412 天前
花生十三资料1200题|题库|刷题
conda·pytest·pillow·pip·web3.py·ipython·gunicorn
某人辛木12 天前
Web自动化测试
前端·python·pycharm·pytest
Thecozzy14 天前
单元测试 vs 手工测试:以水印功能为例
单元测试
淡漠的蓝精灵14 天前
pytest-xdist:把 pytest 测试分发到多核 CPU 执行
其他·pytest
HLAIA光子15 天前
AI Coding框架,打好TDD和SDD这两拳
单元测试·ai编程·代码规范