0

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,])

  • yes, sort of. The problem is if when I need to test with a non-fixture object and check if it raise error, like (123, TypeError), then that solution will lead up to creating another function```def int_obj(): return 123``` and decorate it with fixture. I was wondering if there're other workaround though. – Mathew_Dong Mar 14 '22 at 00:37
  • Have you check the `[lazy-fixture](https://github.com/tvorog/pytest-lazy-fixture) plugin mentioned in one of the answers? – MrBean Bremen Mar 14 '22 at 06:23
  • yes, thanks for helping me. Though I've edit my problem to be more specific. – Mathew_Dong Mar 15 '22 at 16:29

0 Answers0