6、pytest -- 临时目录和文件

本文介绍了在 pytest 框架中如何使用 `tmp_path` 和 `tmp_path_factory` 创建临时目录,分别阐述了它们在用例级别和会话级别的应用,并详细对比了两者的区别。内容包括 `pathlib.Path` 的使用、临时目录的默认位置以及如何自定义基本临时目录。

1. 相关的fixture

1.1. tmp_path

tmp_path是一个用例级别的fixture,其作用是返回一个唯一的临时目录对象(pathlib.Path);

我们看下面的例子:

# src/chapter-6/test_tmp_path.py

CONTENT = "content"


def test_create_file(tmp_path):
    d = tmp_path / "sub"  
    d.mkdir()  # 创建一个子目录
    p = d / "hello.txt"
    p.write_text(CONTENT)
    assert p.read_text() == CONTENT
    assert len(list(tmp_path.iterdir())) == 1  # iterdir() 迭代目录,返回迭代器
    assert 0  # 为了展示,强制置为失败

执行:

λ pipenv run pytest -q -s src/chapter-6/test_tmp_path.py
F
==================================== FAILURES =====================================
________________________________ test_create_file _________________________________

tmp_path = WindowsPath('C:/Users/luyao/AppData/Local/Temp/pytest-of-luyao/pytest-4/test_create_file0')

    def test_create_file(tmp_path):
        d = tmp_path / "sub"
        d.mkdir()  # 创建一个子目录
        p =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值