在测试中访问Pytest Fixture参数

时间:2017-11-18 16:02:18

标签: python pytest

是否有可能从测试功能中访问request.param

使用参数设置灯具

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

测试

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

编辑:添加了collections.namedtuple解决方案

到目前为止我的工作

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

然后在测试中访问

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

我仍然希望有更好的解决方案!

1 个答案:

答案 0 :(得分:0)

这个重复的问题的好答案:In pytest, how can I access the parameters passed to a test?

您可以使用request.node.callspec.params来访问它:

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

或者您可以稍微重构灯具:

@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