How to pass testCase value to next one with Pytest

import pytest


def add(x):
    return x + 1

def sub(x):
    return x - 1


testData1 = [1, 2]
testData2 = [3]


class Test_math(object):
    @pytest.mark.parametrize('n', testData1)
    def test_add(self, n):
        result = add(n)
        testData2.append(result) <-------- Modify testData here
        assert result == 5

    @pytest.mark.parametrize('n', testData2)
    def test_sub(self, n):
        result = sub(n)
        assert result == 3


if __name__ == '__main__':
    pytest.main()

there are only 3 tests :Test_math.test_add[1],Test_math.test_add[2],Test_math.test_sub[3] executed in this scenario.

Test_math.test_sub only executes with predefined data [3] which is not my expectation [2,3,3]. How to fix it?

update [1,2,3]-> [2,3,3]


Solution 1:

Not exactly sure why it didn't work, but doing it like that it's a bad idea since the order of tests is not guaranteed (unless you implement ad-hoc code to order the execution of tests).

Besides this and other issues of test design, the way you can somewhat achieve what you want would be by joining testData1 and testData2 in the pytest.mark.parametrize decorator.

@pytest.mark.parametrize('n', testData1 + testData2)
def test_sub(self, n):
    result = sub(n)
    assert result == 3

Now, keep in mind that with your test definition, this will always fail because the result of sub(n) with testData1 + testData2 will never be 3.