在测试 class 中参数化测试时维护测试执行顺序

maintaining order of test execution when parametrizing tests in test class

我正尝试像下面那样参数化我的测试

@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

这给了我想要的顺序,但测试名称在所有迭代中保持不变,因此在报告中造成问题。

我终于能够使用 pytest_generate_tests 钩子实现这一点。

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