Python 从参数化测试访问夹具(如capsys)
在本例中,我无法从参数化测试中访问设备capsys。目前,我正在使用虚拟夹具来实现此功能:Python 从参数化测试访问夹具(如capsys),python,pytest,Python,Pytest,在本例中,我无法从参数化测试中访问设备capsys。目前,我正在使用虚拟夹具来实现此功能: import pytest @pytest.fixture def params(request): from collections import namedtuple return namedtuple('Params', 'input output')(*request.param) @pytest.mark.parametrize('params', [ ('a', '
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
有没有办法在不使用params fixture的情况下重写此代码?您只需删除间接参数:
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
但更好的方法是让参数化直接通过名称传递参数:
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
那太尴尬了。。。当我试图让它工作时,我确信我看到了错误,关于传递给测试的参数数量不正确,但显然这个例子工作得很好。谢谢