derchambers
derchambers

Reputation: 954

output of fixture in params in pytest

I sat down to better learn py.test today and found the site with the documentation is down (pytest.org) so I appologize if the answer to this question is found there.

What I want to do is pass the output of two fixtures to a parametrize, like so:

import pytest

@pytest.fixture()
def make_1():
    return 1

@pytest.fixture()
def make_2():
    return 2

@pytest.mark.parametrize('arg', [make_1, make_2])
def test_main(arg):
    assert isinstance(arg, int)

but the tests fail because rather than assigning the outputs of the fixtures to the parameter "arg" the fixtures (functions) themselves are passed.

How can I parametrize the outputs of various fixtures in this way?

Upvotes: 2

Views: 1341

Answers (1)

Tom Dalton
Tom Dalton

Reputation: 6190

Would this [ugly/massive hack] do the trick? I appreciate it's far from ideal - I don't know if there's a way to create a lazy-evaluated fixture that would let you do what you're trying to do.

import pytest

@pytest.fixture
def make_1():
    return 1

@pytest.fixture
def make_2():
    return 2

@pytest.fixture
def all_makes(make_1, make_2):
    return (make_1, make_2)

def _test_thing(make):
    # Run your test
    pass

def test_main(all_makes):
    for make in all_makes:
        try:
            _test_thing(make)
        except AssertionError:
            print "Failed for make {}".format(make)
            raise

A probably better alternative might be to parameterize the fixture itself (if possible) - ref the docs: https://pytest.org/latest/fixture.html#parametrizing-a-fixture

@pytest.fixture(params=[1, 2])
def make(request):
    return request.param

def test_make(make):
    # Run your test
    pass

If your different 'make' fixtures are super-different, you could have something like:

def build_make_1():
    return 1

def build_make_2():
    return 2

@pytest.fixture(params=[build_make_1, build_make_2])
def make(request):
    return request.param()

def test_make(make):
    # Run your test
    pass

Upvotes: 1

Related Questions