2.6 如何在测试中使用临时目录和文件
2.6. 固定装置:tmp_path
您可以使用tmp_path固定装置,它将提供一个在基本临时目录中创建的测试调用唯一的临时目录。
# content of 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
assert 0
2.6.2 固定装置:tmp_path_factory
tmp_path_factory 是一个会话范围的夹具,夹具可从任何其他固定装置或测试中创建任意的临时目录
# contents of conftest.py
import pytest
@pytest.fixture(scope="session")
def image_file(tmp_path_factory):
img = compute_expensive_image()
fn = tmp_path_factory.mktemp("data") / "img.png"
img.save(fn)
return fn
# contents of test_image.py
def test_histogram(image_file):
img = load_image(image_file)
# compute and test histogram
2.6.3 固定装置:tmpdir、tmpdir_factory
tmpdir、tmpdir_factory 与 tmp_path_factory 类似,但是要使用/返回的 py.path.local 对象,而不是标准的 pathlib.Path 对象
2.6.4 默认的基本临时目录
默认情况下,临时目录被创建为系统临时目录的子目录。基本名称将是pytest-NUM,其中NUM将随着每次测试运行而递增,此外,超过3个临时目录的条目将被删除。
当前不能更改条目数量,但是使用-基温度选项将在每次运行之前删除目录,这意味着只保留最近运行的临时目录。可以覆盖默认临时目录设置:
pytest --basetemp=mydir
警告:mydir的内容将被完全删除,所以请确保仅为此目的使用一个目录。
当使用pytest-xdist在本地机器上分发测试时,自动为子进程配置一个基项目录,以便所有临时数据都位于每个测试运行的基项目录之下.