pytest 核心功能-在测试中使用临时目录和文件
tmp_path fixture
您可以使用tmp_path fixture,它将为测试调用提供一个在基本临时目录中创建的惟一临时目录。
Tmp_path是一个pathlib.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运行它会导致测试通过,除了我们用来查看值的最后一个 assert 0 行:
$ pytest test_tmp_path.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item
test_tmp_path.py F [100%]
================================= FAILURES =================================
_____________________________ test_create_file _____________________________
tmp_path = PosixPath('PYTEST_TMPDIR/test_create_file0')
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
E assert 0
test_tmp_path.py:11: AssertionError
========================= short test summary info ==========================
FAILED test_tmp_path.py::test_create_file - assert 0
============================ 1 failed in 0.12s =============================tmp_path_factory fixture
tmp_path_factory是一个会话范围的fixture,可用于从任何其他fixture或测试创建任意临时目录。
假设您的测试套件需要在磁盘上生成一个大的映像,这个映像是程序生成的。为每个测试计算相同的图像,并将其使用到自己的tmp_path中,您可以每次生成一个图像,以节省时间:
# 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 histogramtmpdir和tmpdir_factory fixture
tmpdir 和 tmpdir_factory fixtures类似于 tmp_path 和 tmp_path_factory,但使用/返回旧版 py.path.local 对象而不是标准 pathlib.Path 对象。现在,更喜欢使用 tmp_path 和 tmp_path_factory。
默认的基本临时目录
默认情况下,临时目录作为系统临时目录的子目录创建。基本名称将是pytest-NUM,其中NUM将随着每次测试运行而递增。此外,超过3个临时目录的条目将被删除。
当前不能更改条目的数量,但是使用--basetemp选项将在每次运行之前删除目录,这意味着只有最近运行的临时目录将被保留。
你可以像这样覆盖默认的临时目录设置:
pytest --basetemp=mydirmydir的内容将被完全删除,因此请确保仅将目录用于此目的。
使用 pytest-xdist 在本地机器上分发测试时,注意为子进程自动配置一个 basetemp目录,以便所有临时数据都位于单个每次测试运行的 basetemp 目录下。