使用fixture时pytest capsys未捕获stdout

Dan*_*age 6 python fixtures pytest

我正在使用 pytest 固定装置来模拟用于测试脚本的命令行参数。这样每个测试函数共享的参数只需要在一个地方声明。我也在尝试使用 pytest 的 capsys 来捕获脚本打印的输出。考虑下面这个愚蠢的例子。

from __future__ import print_function
import pytest
import othermod
from sys import stdout


@pytest.fixture
def shared_args():
    args = type('', (), {})()
    args.out = stdout
    args.prefix = 'dude:'
    return args


def otherfunction(message, prefix, stream):
    print(prefix, message, file=stream)


def test_dudesweet(shared_args, capsys):
    otherfunction('sweet', shared_args.prefix, shared_args.out)
    out, err = capsys.readouterr()
    assert out == 'dude: sweet\n'
Run Code Online (Sandbox Code Playgroud)

在这里,capsys 无法sys.stderr正确捕获。如果我移动from sys import stdout,并args.out = stdout直接进入测试功能,一切按预期工作。但这让事情变得更加混乱,因为我必须为每个测试重新声明这些语句。难道我做错了什么?我可以将 capsys 与夹具一起使用吗?

Sil*_*Guy -1

在运行测试之前调用夹具。在您的示例中,shared_args 固定装置正在读取标准输出,然后其他函数可以将任何内容写入标准输出。

解决问题的一种方法是让你的装置返回一个可以执行你想要它执行的操作的函数。您可以根据您的用例确定夹具的范围。

from __future__ import print_function
import pytest
from sys import stdout
import os


@pytest.fixture(scope='function')
def shared_args():
    def args_func():
        args = type('', (), {})()
        args.out = stdout
        args.prefix = 'dude:'
        return args
    return args_func


def otherfunction(message, prefix, stream):
    print(prefix, message, file=stream)


def test_dudesweet(shared_args, capsys):
    prefix, out = shared_args().prefix, shared_args().out
    otherfunction('sweet', prefix, out)
    out, err = capsys.readouterr()
    assert out == 'dude: sweet\n'
Run Code Online (Sandbox Code Playgroud)

您没有正确使用 capsys.readouterr() 。请参阅此处 capsys 的正确用法:https ://stackoverflow.com/a/26618230/2312300