当我使用夹具时,为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,这是为什么?我怎样才能让它工作?谢谢你的帮助
主要问题是,您不能轻松地混合使用函数和类作用域装置。 功能范围固定装置可以工作:
类作用域fixture在调用函数作用域
capsys
之前运行,因此它不会从fixture捕获stdout/stderr。如果您尝试将
capsys
添加到装置本身,也会显示问题。在这种情况下,pytest将投诉:请注意,我还删除了
return excinfo
部分,因为这将永远不会到达-一旦发生异常,上下文管理器作用域就会离开。检查也是不必要的,因为它已经在夹具中完成了所以答案是:以这种方式实现你想要的是不可能的。夹具用于为测试提供设置/拆卸和数据,而不是测试本身的一部分。
我不确定您的实际用例,这取决于您是否可以
printing
,这是我从您的问题中理解的)printing
异常处理编写一个单独的测试(就像您在第一个测试中所做的那样),并在fixture中使用它为所有其他测试设置一次,如果您需要的话相关问题 更多 >
编程相关推荐