Access Pytest Fixture Params In Test

Viewed 473

Is there a possibility to access the request.param from the test function?

Setup Fixture with params

@pytest.fixture(params=[0,10,20,30])
def wallet(request):
    return Wallet(request.param)

Test

def test_init_balance(wallet):
    assert wallet.balance == 10

EDIT: Added a collections.namedtuple solution

What I got working until now

@pytest.fixture(params=[20,30,40])
def wallet(request):
    FixtureHelper = collections.namedtuple('fixtureHelper', ['wallet', 'request'])
    fh = FixtureHelper(Wallet(request.param), request)
    return fh

Then accessing it in the test

def test_spend_cash(wallet):
    wallet.wallet.spend_cash(wallet.request.param)

I would still appreciate a better solution!

1 Answers

Good answers in this duplicate question: In pytest, how can I access the parameters passed to a test?

You can access it with request.node.callspec.params:

def test_init_balance(request, wallet):
    assert wallet.balance == request.node.callspec.params.get("wallet")

Or you can refactor the fixtures slightly:

@pytest.fixture(params=[0, 10, 20, 30])
def balance(request):
    return request.param


@pytest.fixture
def wallet(balance):
    return Wallet(balance)


def test_init_balance(wallet, balance):
    assert wallet.balance == balance
Related