问题描述
此链接 描述了如何使用 pytest 捕获控制台输出.我尝试了以下简单代码,但出现错误
This link gives a description how to use pytest for capturing console outputs.I tried on this following simple code, but I get error
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'
出了什么问题,需要什么修复?谢谢
what is wrong and what fix needed? thank you
根据评论,我更改了 capfd
,但仍然出现相同的错误
As per the comment, I changed capfd
, but I still get the same error
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
固定装置.
示例:
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
以获取内置设备列表.
And see: py.test --fixtures
for a list of builtin fixtures.
您的示例存在一些问题.这是一个更正的版本:
Your example has a few problems. Here is a corrected version:
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
- Do not use
sys.stdout
-- Use thecapfd
fixture as-is as provided by pytest. - Run the test with:
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 工具和测试运行程序)为您完成这项工作.
- You do not need to run your Test Function(s) in your test modules.
py.test
(The CLI tool and Test Runner) does this for you.
py.test 主要做三件事:
py.test does mainly three things:
- 收集您的测试
- 运行测试
- 显示统计信息和可能的错误
默认py.test
寻找(可配置的iirc)test_foo.py
测试模块和test_foo()
在您的测试模块中测试功能.
By default py.test
looks for (configurable iirc) test_foo.py
test modules and test_foo()
test functions in your test modules.
这篇关于编写一个 pytest 函数来检查控制台上的输出 (stdout)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!