以编程方式创建pytest fixtures

9

我有一个充满数据文件的目录,用于测试,并且我使用以下代码来加载它们:

@pytest.fixture(scope="function")
def test_image_one():
     return load_image("test_image_one.png")

随着测试套件的增长,这变得难以维护。是否有一种可以编程创建固定装置的方法?理想情况下,它应该像这样:
for fname in ["test_image_one", "test_image_two", ...]:
    def pytest_fixutre_function():
        return load_image("{}.png".format(fname))
    pytest.magic_create_fixture_function(fname, pytest_fixutre_function)

有没有一种方法可以实现这个?

为什么你不能只是创建一个夹具,调用load_image函数,或许先进行一些格式化处理呢? - SuperStormer
你想要实现什么目标?你想要为每个图像执行一个测试,并将文件读取移至 fixture 吗?测试或 fixture 参数化很可能是你需要的。 - hoefling
是的,我有一个装满不同输出触发图像的文件夹,所以我为每个图像都有一个测试。我想读取文件数据,将它们作为输入传递给正在测试的函数。 - Charles L.
2个回答

9
编写一个装置,读取图像文件并返回文件内容,并使用间接参数化来调用它。示例:
import pathlib
import pytest


files = [p for p in pathlib.Path('images').iterdir() if p.is_file()]


@pytest.fixture
def image(request):
    path = request.param
    with path.open('rb') as fileobj:
        yield fileobj.read()


@pytest.mark.parametrize('image', files, indirect=True, ids=str)
def test_with_file_contents(image):
    assert image is not None

测试运行将产生以下结果:
test_spam.py::test_with_file_contents[images/spam.png] PASSED
test_spam.py::test_with_file_contents[images/eggs.png] PASSED
test_spam.py::test_with_file_contents[images/bacon.png] PASSED

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接