'Filtering parameters or skipping test when parameters have certain values
I want to skip a test if a fixture parameter has a certain value. See this example:
import random
from itertools import combinations, starmap
import pytest
def save_divide(num, denom):
return divide(num, denom) if denom else UNDEFINED
UNDEFINED = None
def divide(num, denom):
return num / denom
def test_save_divide(fractions):
for num, denom in fractions:
result = save_divide(num, denom)
assert result == (num / denom if denom else UNDEFINED)
# Here I would like to skip intervals that include 0, instead of
# setting the value for `interval` manually.
# I know I can just check for `denom == 0`. This is just an artifact
# of this MWE. In my actual code such a check is not possible within
# the body of the test function.
@pytest.mark.parametrize("interval", [(1, 5)])
def test_divide(fractions):
for num, denom in fractions:
assert divide(num, denom) == num / denom
@pytest.fixture
def fractions(interval):
def stochastic_flip(a, b):
return (a, b) if random.randint(0, 1) else (b, a)
nums = range(*interval)
return set(starmap(stochastic_flip, combinations(nums, r=2)))
@pytest.fixture(params=[(-2, 2), (1, 5)])
def interval(request):
return request.param
I did not find anything in the documentation about skipping based on fixture values. Is this possible?
Solution 1:[1]
I'm still not completely sure if I understand your use case, but I assume that you want to skip tests with a parameter from fraction which is based on interval containing a zero (or meet some other condition). Provided this is what you need, you could make a separate fixture based on both interval and fraction which does that check and skips tests accordingly:
@pytest.fixture
def fractions_no_zero(interval, fractions):
if interval[0] <= 0 < interval[1]: # will skip (-2, 2)
pytest.skip("Denominator can be zero")
else:
return fractions
def test_divide(fractions_no_zero):
for num, denom in fractions_no_zero:
assert divide(num, denom) == num / denom
Note that in this case, e.g. if you base your fixture on two "base" fixtures, you will only get the matching values, e.g. the value for interval on which fractions is based upon.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MrBean Bremen |
