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 =

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

446

被折叠的 条评论
为什么被折叠?



