我有一个充满数据文件的目录,可以送入测试,并且使用类似的方式加载它们
@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)
有没有办法做到这一点?
答案 0 :(得分:2)
写一个夹具来读取图像文件并返回文件内容,并使用间接参数化来调用它。示例:
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 :(得分:1)
类似这样的东西:
@pytest.mark.parametrize('pic', ['f1', 'f2', 'f3'])
def test_pics(pic):
load_image(pic)
有关详细信息,请参阅文档 https://docs.pytest.org/en/latest/parametrize.html