Bubaya
Bubaya

Reputation: 823

Parametrize tests for similar types

I have an interface A that's implemented by two types B1 and B2. I want to write a test suite that checks that both B1 and B2 implement A correctly. Say is of the form

class A:
    def __init__(self, from_object): pass
    def do_something(self): pass

and B1, B2 inherit fro A. My test looks something like

class TestA:
    @pytest.fixture(params=[input1, input2])
    def some_data(request):
        return T(request.param)
    @pytest.mark.parametrize("with_object", [pytest.lazy_fixture("some_data")])
    def test_do_something(with_object):
        assert with_object.do_something() == expectation

I'd like to have that T attains B1 and B2, but I am not sure how to achieve that nicely. Do you have hints on that?

Upvotes: 0

Views: 31

Answers (1)

tmt
tmt

Reputation: 8654

Generally I'd achieve this but using indirect=True to pass parameters (in your case 2 different classes) to some_data fixture which could then access it from request.param and return an initialized object:

class TestA:
    @pytest.fixture()
    def some_data(self, request):
        return request.param()

    @pytest.mark.parametrize("some_data", (B1, B2), indirect=True)
    def test_do_something(self, some_data):
        assert some_data.do_something() == expectation

This assumes that some_data() would do a more complex intialization of B1/B2 than in my example because you actually wouldn't need the fixture otherwise. If the fixture needs some additional parametrized data, you could make the input params more complex:

class TestA:
    @pytest.fixture()
    def some_data(self, request):
        return request.param[0](request.param[1])

    @pytest.mark.parametrize(
        "some_data",
        ((B1, {'abc': 'xyz'}), (B2, {'abc': 'xyz'})),
        indirect=True
    )
    def test_do_something(self, some_data):
        assert some_data.do_something() == expectation

Upvotes: 1

Related Questions