如何在pytest中进行依赖参数化?

Igo*_*lev 1 python testing pytest

例如我有这样的测试数据:

PARAMS = {'pic1': [1, 2, 3], 'pic2': [14, 15], 'pic3': [100, 200, 300]}
Run Code Online (Sandbox Code Playgroud)

我需要从中下载每个关键图片PARAMS并生成[1, 2, 3]将使用该图片的单独测试。之后,当每对测试'pic1': [1, 2, 3]结束时,删除图片,然后下载下一张,依此类推......粗略地说,生成的测试应该如下所示:

test_pic[pic1-1]
test_pic[pic1-2]
test_pic[pic1-3]
test_pic[pic2-14]
test_pic[pic2-15]
test_pic[pic3-100]
test_pic[pic3-200]
test_pic[pic3-300]
Run Code Online (Sandbox Code Playgroud)

但里面会有一个下载图像的逻辑。

我没有找到如何在 pytest 中做到这一点的方法。

请帮忙。

hoe*_*ing 6

对我来说,这似乎是一项间接参数化的任务。

准备参数

首先要做的事情:pytest.mark.parametrize期望参数作为元组列表传递,数据按参数名称排序,例如:

@pytest.mark.parametrize('spam,eggs', [(1, 2), (3, 4), (5, 6)])
Run Code Online (Sandbox Code Playgroud)

将生成三个测试:

  • spam=1, eggs=2,
  • spam=3, eggs=4,
  • spam=5, eggs=6

因此,您必须将PARAMS字典转换为元组列表,每个字典键有一个数字。有很多方法可以做到这一点,其中一种解决方案是:

PARAMS = {'pic1': [1, 2, 3],
          'pic2': [14, 15],
          'pic3': [100, 200, 300]}

test_pic_params = [(key, el) for key, nums in PARAMS.items()
                   for el in nums]


@pytest.mark.parametrize('file,num', test_pic_params)
def test_pic(file, num):
    assert True
Run Code Online (Sandbox Code Playgroud)

检查测试是否正确生成:

@pytest.mark.parametrize('spam,eggs', [(1, 2), (3, 4), (5, 6)])
Run Code Online (Sandbox Code Playgroud)

间接参数化

file现在您想在测试之前处理参数,因此测试会获取下载的文件pic1而不是pic1. 这可以通过间接参数化来完成。你需要做的是:

  • 实现一个名为的装置file(重要的是该装置与测试参数具有相同的名称,否则pytest将无法识别和应用它);
  • 添加indirect=['file']到参数化标记。

这样,pic1首先传递到file()夹具,然后将夹具的结果传递给测试。扩展示例:

import pathlib
import pytest


PARAMS = {'pic1': [1, 2, 3], 
          'pic2': [14, 15],
          'pic3': [100, 200, 300]}

test_pic_params = [(key, el) for key, nums in PARAMS.items()
                   for el in nums]


@pytest.fixture
def file(request):
    pic = request.param
    # this will just create an empty file named 'pic1' etc;
    # replace it with file download logic
    filename = pathlib.Path(pic)
    filename.touch()
    # pass filename instead of pic to test
    yield filename
    # after test finishes, we remove downloaded file
    filename.unlink()


@pytest.mark.parametrize('file,num', test_pic_params, indirect=['file'])
def test_pic(file, num):
    assert file.is_file()
Run Code Online (Sandbox Code Playgroud)

编辑:

我需要的是'pic1'在测试后删除文件test_pic[pic1-1] , test_pic[pic1-2], test_pic[pic1-3]。然后下载新文件pic2

虽然这肯定是可能的,但请记住,这将违反单个测试运行的原子性,因此,例如,您将失去并行运行测试的能力。

如果您想跟踪测试运行的当前状态,只需在夹具中执行即可。当编号为对应列表中的第一个时,下载文件;删除最后一个号码上的文件:

@pytest.fixture
def file(request):
    pic = request.param
    num = request.node.callspec.params['num']
    filename = pathlib.Path(pic)
    if num == PARAMS[pic][0]:  # download here
        filename.touch()
    yield filename
    if num == PARAMS[pic][-1]:  # remove here
        filename.unlink()
Run Code Online (Sandbox Code Playgroud)

IMO 更好的方法是使用磁盘缓存,在第一次下载时缓存文件;这将使测试再次原子化。