Search code examples
pythonpython-3.xpytest

pytest nested parameterization


Code

@pytest.mark.parametrize("arg1", [1,2])
@pytest.mark.parametrize("arg2", [["A1", "A2"], ["B1", "B2", "B3"]])
def test_stackoverflow(arg1, arg2):
    print(arg1, arg2)

Current output

1 [A1, A2]
2 [A1, A2]
1 [B1, B2, B3]
2 [B1, B2, B3]

But I am expecting something like below. Is this even possible, if so how?

1 A1
1 A2
2 B1
2 B2
2 B3

Solution

  • You can build a function to handle the combinations

    def parametrize():
        for lst1, lst2 in zip([1, 2], [["A1", "A2"], ["B1", "B2", "B3"]]):
            for val in lst2:
                yield lst1, val
    
    
    @pytest.mark.parametrize(("arg1", "arg2"), parametrize())
    def test_stackoverflow(arg1, arg2):
        print(arg1, arg2)
    

    Output

    test_stackoverflow[1-A1] PASSED                        [ 20%]1 A1
    test_stackoverflow[1-A2] PASSED                        [ 40%]1 A2
    test_stackoverflow[2-B1] PASSED                        [ 60%]2 B1
    test_stackoverflow[2-B2] PASSED                        [ 80%]2 B2
    test_stackoverflow[2-B3] PASSED                        [100%]2 B3