在测试类中参数化测试时保持测试执行的顺序

时间:2015-08-12 06:08:26

标签: python pytest

我正在尝试对我的测试进行参数化,如下所示

@pytest.mark.parametrize("a,b", test_data)
class TestClass():
    def test_A(self,a,b):
        # Some Code ..
        pass
    def test_B(self,a,b):
        # Some Code ..
        pass
    def test_C(self,a,b):
        # Some Code ..
        pass

我希望我的测试按顺序执行,例如测试步骤,例如

test_A
test_B
test_C
test_A
test_B
test_C
....

执行它们的顺序是

test_A
test_A
...
test_B
test_B
...
test_C
test_C

我尝试过的另一个选择是将我的测试放在for循环中,如下所示

for data in test_data:
    a,b = data
    def test_A(a,b):
        # Some Code ..
        pass
    def test_B(a,b):
        # Some Code ..
        pass
    def test_C(a,b):
        # Some Code ..
        pass

这给了我所需的顺序,但测试名称在所有迭代中保持不变,因此它会在报告中产生问题。

1 个答案:

答案 0 :(得分:0)

我终于能够使用pytest_generate_tests hook来实现这一点。

def pytest_generate_tests(metafunc):
    argvalues = []
    for data in metafunc.cls.data:
        items = data.items()
        argnames = [x[0] for x in items]
        argvalues.append(([x[1] for x in items]))
    metafunc.parametrize(argnames, argvalues, scope="class"

class TestClass:
    data = [{'attr_1': 'val_1_1', 'attr_2': 'val_1_2'}, {'attr_1': 'val_2_1', 'attr_2': 'val_2_2'}]

    def test_A(self, attr_1, attr_2)
    ...

    def test_B(self, attr_1, attr_2)
    ...

    def test_B(self, attr_1, attr_2)
    ...

https://pytest.org/latest/example/parametrize.html

相关问题