在夹具内的pytest中捕获stderr/stdout

2024-09-30 05:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用夹具时,为pytest捕获stderr和stdout时遇到问题。如果直接调用测试,它就可以正常工作。我之所以希望它出现在fixture中,是因为我需要根据我将要读取的文件多次调用它

下面是一个工作示例,假设此内容位于“test_something.py”:

import sys
import pytest


def printing():
    print("testing only")
    print("erroring", file=sys.stderr)
    sys.exit(1)

def test_print(capsys):
    with pytest.raises(SystemExit) as excinfo:
        printing()

    stdout, errout = capsys.readouterr()
    assert stdout == "testing only\n"
    assert errout == "erroring\n"
    assert excinfo.type == SystemExit


class TestPrint():
    @pytest.fixture(name="getResponse", scope="class", params=[0])
    def getResponse(self, request):
        with pytest.raises(SystemExit) as excinfo:
            printing()
            return excinfo

    def test_print_class(self, getResponse, capsys):
        excinfo = getResponse
        stdout, errout = capsys.readouterr()
        assert stdout == "testing only\n"
        assert errout == "erroring\n"
        assert excinfo.type == SystemExit

如果对上述内容运行“pytest-v”,则会得到:

tests/test_something.py::test_print PASSED                                                                                                                                           [ 50%]
tests/test_something.py::TestPrint::test_print_class[0] FAILED                                                                                                                       [100%]

“test\u print\u class”读取空的stdout和stderr,这是为什么?我怎样才能让它工作?谢谢你的帮助


Tags: pytestpytestdefstderrstdoutassertsomething
1条回答
网友
1楼 · 发布于 2024-09-30 05:30:31

主要问题是,您不能轻松地混合使用函数和类作用域装置。 功能范围固定装置可以工作:

class TestPrint:
    @pytest.fixture(name="getResponse")
    def getResponse(self):
        with pytest.raises(SystemExit):
            printing()

    def test_print_class(self, capsys, getResponse):
        stdout, errout = capsys.readouterr()
        assert stdout == "testing only\n"
        assert errout == "erroring\n"

类作用域fixture在调用函数作用域capsys之前运行,因此它不会从fixture捕获stdout/stderr。
如果您尝试将capsys添加到装置本身,也会显示问题。在这种情况下,pytest将投诉:

ScopeMismatch: You tried to access the 'function' scoped fixture 'capsys' with a 'class' scoped request object, involved factories

请注意,我还删除了return excinfo部分,因为这将永远不会到达-一旦发生异常,上下文管理器作用域就会离开。检查也是不必要的,因为它已经在夹具中完成了

所以答案是:以这种方式实现你想要的是不可能的。夹具用于为测试提供设置/拆卸和数据,而不是测试本身的一部分。
我不确定您的实际用例,这取决于您是否可以

  • 使用函数范围的fixture(如果您想为每个测试调用printing,这是我从您的问题中理解的)
  • printing异常处理编写一个单独的测试(就像您在第一个测试中所做的那样),并在fixture中使用它为所有其他测试设置一次,如果您需要的话

相关问题 更多 >

    热门问题