Parameterize fixture depending on other fixture? #14140
-
|
Hello, I want to know if there is a way to parameterize a fixture not depending on some known value, but depending on another fixture. I know that I can parameterize fixtures like this: @pytest.fixture(params=[[1, 2, 3], [7, 8, 9]])
def numbers(request):
return request.param
# This test will run twice, once per numbers list
def test_list_not_empty(numbers):
assert len(numbers) > 0I also know that fixtures can depend on parameterized fixtures: @pytest.fixture(params=[[1, 2, 3], [7, 8, 9]])
def numbers(request):
return request.param
# This fixture will be requested twice because `numbers` has two parameters
@pytest.fixture
def first_number(numbers):
return numbers[0]
def test_first_in_list(first_number, numbers)
assert first_number in numbersWhat I want to do is combine both: @pytest.fixture(params=[[1, 2, 3], [7, 8, 9]])
def numbers(request):
return request.param
@pytest.fixture
def number(numbers):
for n in numbers:
yield n # <-- this is wrong, yield is for fixtures that need cleanup
def test_contains(number, numbers)
assert number in numbersThe above code is of course wrong because fixtures are only supposed to yield once and yielding is used for cleanup, but I hope it illustrates the idea that I want to call This is of course a silly toy example, but I do have real use cases where one fixture drives other fixtures and some of those other fixtures branch out to provide even more values. For example, let's say I have a number of XML Schema files and modules of classes. For each class I want to verify that it matches the definition from the schema. I have the following fixtures:
Then the test can look something like this: def test_class_defined(klass, schema):
assert ...Without being able to parameterize def test_classes_defined(module, schema):
for klass in get_classes(module):
assert ...This is bad because the test will fail on the very first failure, so I won't know if there is only one broken class or a hundred broken classes. Is there a way to achieve what I'm looking for? I don't mind if I have to do it in a roundabout way, all I want is to run the test once per class per schema. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
|
As currently fixture values happen after collecting there's no direct mechanism to do so A crude workaround would be to collect the data at collection time and using the generate tests hook to create fitting test items |
Beta Was this translation helpful? Give feedback.
Its been asked before
Making it worknis the tricky thing