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
相关推荐
程序员二黑9 小时前
Web UI自动化王者:Selenium WebDriver 核心原理与API详解
单元测试·测试·ab测试
5:001 天前
pytest框架-详解
pytest
健康平安的活着1 天前
java之 junit4单元测试Mockito的使用
java·开发语言·单元测试
程序员二黑1 天前
Pytest为何成为Python测试王者?Fixtures/Parametrize/Plugins三神器揭秘
单元测试·测试·ab测试
zru_96022 天前
Spring Boot 单元测试:@SpyBean 使用教程
spring boot·单元测试·log4j
程序员二黑3 天前
单元测试三大神器:unittest vs JUnit vs Jest 终极对决
单元测试·测试·ab测试
丿罗小黑3 天前
Pytest项目_day15(yaml)
pytest
丿罗小黑3 天前
Pytest项目_day16(yaml和parametrize结合)
pytest
用户84913717547164 天前
JustAuth实战系列(第11期):测试驱动开发 - 质量保证与重构实践
java·设计模式·单元测试
代码小念4 天前
Pytest+selenium UI自动化测试实战实例(超详细)
selenium·ui·pytest