Is it possible to conditionally skip parametrized tests?
Here's an example:
@pytest.mark.parametrize("a_date", a_list_of_dates)
@pytest.mark.skipif(a_date > date.today())
def test_something_using_a_date(self, a_date):
assert <some assertion>
Of course I can do this inside the test method, but I'm looking for a structured way to do this with pytest
.
If you create your own method you check the values in test collection time and run the relevant tests only
a_list_of_dates = [date.today(), date(2024, 1, 1), date(2022, 1, 1)]
def get_dates():
for d in a_list_of_dates:
if d <= date.today():
yield d
class TestSomething:
@pytest.mark.parametrize("a_date", get_dates())
def test_something_using_a_date(self, a_date):
print(a_date)
Output
TestSomething::test_something_using_a_date[a_date0] PASSED [ 50%] 2022-08-24
TestSomething::test_something_using_a_date[a_date1] PASSED [100%] 2022-01-01
If you still want to see the skipped tests you can add the skip
marker to the relevant tests
def get_dates():
for d in a_list_of_dates:
markers = []
if d > date.today():
markers.append(pytest.mark.skip(reason=f'{d} is after today'))
yield pytest.param(d, marks=markers)
Output
TestSomething::test_something_using_a_date[a_date0] PASSED [ 33%] 2022-08-24
TestSomething::test_something_using_a_date[a_date1] SKIPPED (2024-01-01 is after today) [ 66%]
Skipped: 2024-01-01 is after today
TestSomething::test_something_using_a_date[a_date2] PASSED [100%] 2022-01-01