本文介绍了从参数化测试访问夹具(例如,capsys)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在参数化测试中访问装置(在本例中为 capsys)时遇到问题.目前我正在使用一个虚拟夹具来完成这项工作:

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

有没有办法在没有 params 固定装置的情况下重写这段代码?

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

推荐答案

您可以简单地删除 indirect 参数:

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

但更好的方法是让 parametrize 直接通过名称传递参数:

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

这篇关于从参数化测试访问夹具(例如,capsys)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 12:50