我有一个充满数据文件的目录,可将其送入测试,并使用类似于
@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
原文地址:https://codeday.me/bug/20191108/2008185.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。