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
相关推荐
一个处女座的测试2 小时前
Python语言+pytest框架+allure报告+log日志+yaml文件+mysql断言实现接口自动化框架
python·mysql·pytest
新world2 天前
mybatis-plus从入门到入土(二):单元测试
单元测试·log4j·mybatis
仰望星空@脚踏实地3 天前
Spring Boot Web 服务单元测试设计指南
spring boot·后端·单元测试
思则变3 天前
[Pytest][Part 1]Pytest 自动化测试框架
pytest
思则变5 天前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
啃火龙果的兔子5 天前
前端单元测试覆盖率工具有哪些,分别有什么优缺点
前端·单元测试
思则变5 天前
[Pytest][Part 3]检测python package状态
pytest
编程乐学(Arfan开发工程师)15 天前
75、单元测试-嵌套测试
前端·javascript·redis·python·单元测试·bootstrap
编程乐学(Arfan开发工程师)15 天前
73、单元测试-断言机制
服务器·数据库·servlet·单元测试·sqlite·log4j·mybatis
编程乐学(Arfan开发工程师)15 天前
74、单元测试-前置条件
redis·python·阿里云·单元测试·云计算·bootstrap