-->

maintaining order of test execution when parametri

2020-07-27 23:25发布

问题:

I am trying to parametrize my tests like below

@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

I want my test to be executed in Sequential order like test steps, e.g

test_A
test_B
test_C
test_A
test_B
test_C
....

The order in which they are getting executed is

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

The other option I have tried is by putting my tests in for loop like below

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

This give me the desired order but test names remains same in all the iteration so it creates problem in reporting.

回答1:

I was finally able to acheive this using 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



标签: python pytest