我有一个充满数据文件的目录,可将其送入测试,并使用类似于
@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)
有没有办法做到这一点?
编写一个读取图像文件并返回文件内容的夹具,并使用间接参数化来调用它。例:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句