Accessing fixtures (e.g., capsys) from a parametrized test

我与影子孤独终老i 提交于 2020-05-30 09:39:37

问题


I'm having trouble accessing fixtures (in this case, capsys) from within a parametrized test. Currently I'm using a dummy fixture to make this work:

import pytest

@pytest.fixture
def params(request):
    from collections import namedtuple
    return namedtuple('Params', 'input output')(*request.param)

@pytest.mark.parametrize('params', [
    ('a', '1a\n'),
    ('b', '1b\n'),
], indirect=True)
def test_output(capsys, params):
    print('1' + params.input)
    out, err = capsys.readouterr()
    assert out == params.output

Is there a way to rewrite this code without the params fixture?


回答1:


You can simply remove the indirect parameter:

import pytest

@pytest.mark.parametrize('params', [
    ('a', '1a\n'),
    ('b', '1b\n'),
])
def test_output(capsys, params):
    inp, expected = params
    print('1' + inp)
    out, err = capsys.readouterr()
    assert out == expected

But better approach would be to make parametrize pass arguments directly by names:

import pytest

@pytest.mark.parametrize('inp, expected', [
    ('a', '1a\n'),
    ('b', '1b\n'),
])
def test_output(capsys, inp, expected):
    print('1' + inp)
    out, err = capsys.readouterr()
    assert out == expected


来源:https://stackoverflow.com/questions/42391770/accessing-fixtures-e-g-capsys-from-a-parametrized-test

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!