gpt4 book ai didi

python - 编写一个 pytest 函数来检查控制台上的输出(stdout)

转载 作者:IT老高 更新时间:2023-10-28 21:01:10 25 4
gpt4 key购买 nike

This link描述了如何使用 pytest 来捕获控制台输出。我尝试了以下简单代码,但出现错误

import sys
import pytest
def f(name):
print "hello "+ name

def test_add(capsys):
f("Tom")
out,err=capsys.readouterr()
assert out=="hello Tom"


test_add(sys.stdout)

输出:

python test_pytest.py 
hello Tom
Traceback (most recent call last):
File "test_pytest.py", line 12, in <module>
test_add(sys.stdout)
File "test_pytest.py", line 8, in test_add
out,err=capsys.readouterr()
AttributeError: 'file' object has no attribute 'readouterr'

出了什么问题,需要什么修复?谢谢

编辑:根据评论,我更改了 capfd,但仍然收到相同的错误

import sys
import pytest
def f(name):
print "hello "+ name

def test_add(capfd):
f("Tom")
out,err=capfd.readouterr()
assert out=="hello Tom"


test_add(sys.stdout)

最佳答案

使用 capfd fixture 。

示例:

def test_foo(capfd):
foo() # Writes "Hello World!" to stdout
out, err = capfd.readouterr()
assert out == "Hello World!"

见:http://pytest.org/en/latest/fixture.html了解更多

并查看:py.test --fixtures 以获取内置固定装置的列表。

您的示例存在一些问题。这是一个更正的版本:

def f(name):
print "hello {}".format(name)


def test_f(capfd):
f("Tom")

out, err = capfd.readouterr()
assert out == "hello Tom\n"

注意:

  • 不要使用 sys.stdout -- 使用 pytest 提供的 capfd 固定装置。
  • 使用以下命令运行测试:py.test foo.py

测试运行输出:

$ py.test foo.py
====================================================================== test session starts ======================================================================
platform linux2 -- Python 2.7.5 -- pytest-2.4.2
plugins: flakes, cache, pep8, cov
collected 1 items

foo.py .

=================================================================== 1 passed in 0.01 seconds ====================================================================

另请注意:

  • 您不需要在您的测试模块中运行您的测试函数py.test(CLI 工具和测试运行器)为您完成这项工作。

py.test 主要做了三件事:

  1. 收集您的测试
  2. 运行您的测试
  3. 显示统计信息和可能的错误

默认情况下 py.test 寻找 (configurable iirc) test_foo.py 测试模块和 test_foo() 在您的测试模块中测试函数。

关于python - 编写一个 pytest 函数来检查控制台上的输出(stdout),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20507601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com