【问题标题】:Programmatically create pytest fixtures以编程方式创建 pytest 固定装置
【发布时间】:2018-10-24 22:05:23
【问题描述】:

我有一个充满数据文件的目录来输入测试,我使用类似的东西加载它们

@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 的夹具,也许先进行一些格式化?
  • 你想完成什么?您是否想要为每个图像执行测试并将读取的文件移动到固定装置?测试或夹具参数化很可能是您需要的。
  • 是的,我有一个文件夹,里面装满了触发不同输出的图像,所以我对每个图像进行了测试。我想读取文件数据以将它们作为输入传递给正在测试的函数

标签: python pytest


【解决方案1】:

编写一个读取图像文件并返回文件内容的夹具,并使用间接参数化来调用它。示例:

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

【讨论】:

    【解决方案2】:

    类似这样的:

    @pytest.mark.parametrize('pic', ['f1', 'f2', 'f3'])
    def test_pics(pic):
        load_image(pic)
    

    查看文档了解详情 https://docs.pytest.org/en/latest/parametrize.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      相关资源
      最近更新 更多