问题
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