pytest.parametrize get pytest.fixture function instead of the actual object

63 Views Asked by At

Let's just say I have an object(XList) that will check it's input data type, like the following

class B(A):
    pass

class C(A):
    pass

class XList:
    def __init__(self, x: List):
        self.data = []
        for _x in x:
            if not isinstance(_x, A):
                raise TypeError
            self.data.append(_x)

and inside the test file, I used fixture to decorate my b and c function, and parametrize them to test my B and C object can be accepted inside my XList. The problem is, instead of receiving an instance of A, XList actually get an function of b and c, which raise TypError. Is there any way to receive the actual object instead of the fixture function without using lazyfixture or getfixturevalue?

Current Solution


@contextlib.contextmanager
def not_raise():
    yield

@pytest.fixture
def b():
    b = B()
    yield b

@pytest.fixture
def c():
    c = C()
    yield c

@pytest.fixture
def not_a_object():
    yield 123

@pytest.fixture
def get_a(request):
    yield request.getfixturevalue(request.param)

@pytest.mark.parametrize('get_a, raise_error', {
    ('b', not_raise()),
    ('c', not_raise()),
    ('not_a_object', pytest.raise(TypeError)),
}, indirect=['get_a'])
def test_xlist_append(get_a, raise_error)
    with raise_error:
        XList([obj,])

Desire Solution

@pytest.mark.parametrize('obj, raise_error', {
    (b, not_raise()),
    (c, not_raise()),
    (123, pytest.raise(TypeError)),
})
def test_xlist_append(obj, raise_error)
    with raise_error:
        XList([obj,])

0

There are 0 best solutions below