Reputation: 161
I'm trying to nest parametrized tests. The code below does it, but I only want to execute the code on param1 when it changes ("print param1" is time-consuming)
@pytest.mark.parametrize("param3", ["p31", "p32"])
@pytest.mark.parametrize("param2", ["p21", "p22"])
@pytest.mark.parametrize("param1", ["p11", "p12"])
def test_one(param1, param2, param3):
print param1 # goal is to run this only when param1 changes
print param2, param3
I tried this, but it does not seem to work:
@pytest.mark.parametrize("param1", ["p11", "p12"])
def test_one(param1, param2, param3):
print param1 # goal is to run this only when param1 changes
@pytest.mark.parametrize("param3", ["p31", "p32"])
@pytest.mark.parametrize("param2", ["p21", "p22"])
def test_two(param2, param3):
print param2, param3
Does anybody have an idea?
Upvotes: 9
Views: 12542
Reputation: 5156
To complement egabro's answer you can use the "module"
(or "session"
) scope in order to reach the same target without having to nest your tests in a class:
import pytest
@pytest.fixture(scope="module", params=["B1","B2"])
def two(request):
print("\n SETUP", request.param)
return request.param
#print "\n UNDO", request.param
@pytest.fixture(scope="module", params=["A1", "A2"])
def one(request):
print("\n SETUP", request.param)
return request.param
#print "\n UNDO", request.param
@pytest.mark.parametrize("param4", ["D1", "D2"])
@pytest.mark.parametrize("param3", ["C1", "C2"])
def test_three(one, two, param3, param4):
print("\n ({0} {1}) RUN ".format(one, two))
See pytest documentation on fixtures.
Upvotes: 3
Reputation: 161
A colleague gave me a solution:
@pytest.fixture(scope="class", params=["B1","B2"])
def two(request):
print "\n SETUP", request.param
yield request.param
#print "\n UNDO", request.param
@pytest.fixture(scope="class", params=["A1", "A2"])
def one(request):
print "\n SETUP", request.param
yield request.param
#print "\n UNDO", request.param
class Test_myclass():
@pytest.mark.parametrize("param4", ["D1", "D2"])
@pytest.mark.parametrize("param3", ["C1", "C2"])
def test_three(self, one, two, param3, param4):
print "\n ({0} {1}) RUN ".format(one, two), param3, param4,
Upvotes: 7