py.test参数化夹具功能和测试功能

时间:2018-12-20 13:02:02

标签: python pytest

类似于这个问题:enter image description here,但是,我们也希望将测试的输入参数化。

例如(这是我想要做的简化版本):

import pytest


def person_says(name, age):
    return f"{name} is {age}"


@pytest.fixture
def add_surname(request):
    surname = request.param
    return f'Mike {surname}'


NAME1 = "Johnson"
AGE1 = "13"
OUTPUT1 = "Mike Johnson is 13"
NAME2 = "Liam"
AGE2 = "21"
OUTPUT2 = "Mike Liam is 21"

我想通过这样的事情:

@pytest.mark.parametrize('add_surname,age,expected',
                         [[NAME1, AGE1, OUTPUT1], 
                          [NAME2, AGE2, OUTPUT2]],
                         indirect=True)
def test_person_says(add_surname, age, expected):
    name = add_surname
    output = person_says(name, age)
    assert expected == output

但是,这不起作用,因为它查找的夹具age不存在。


使用多个装饰器可以完成所有4种组合。

@pytest.mark.parametrize('age,expected', [[AGE1, OUTPUT1], [AGE2, OUTPUT2]])
@pytest.mark.parametrize('add_surname', [NAME1, NAME2], indirect=True)
def test_person_says(add_surname, age, expected):
    name = add_surname
    output = person_says(name, age)
    assert expected == output

结果:

Expected :Mike Liam is 21        Actual   :Mike Johnson is 21  # FAIL
Expected :Mike Johnson is 13     Actual   :Mike Johnson is 13  # Pass
Expected :Mike Johnson is 13     Actual   :Mike Liam is 13     # FAIL
Expected :Mike Liam is 21        Actual   :Mike Liam is 21     # Pass

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

除了布尔值之外,indirect可以获取输入名称列表,因此通过固定装置进行的间接参数化仅适用于这些输入。示例:

@pytest.mark.parametrize('x, y, z', [('spam', 'eggs', 'bacon')], indirect=['x', 'y'])

xy是间接参数化的,因此spameggs将通过xy固定装置传递,但是{{ 1}}是直接参数化的,因此z将用作普通输入。就您而言:

bacon

可以解决问题。