[英]Writing a pytest function for checking the output on console (stdout)
此鏈接描述了如何使用 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
夾具。
示例:
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
—— 使用capfd
提供的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 工具和 Test Runner )為你做這件事。py.test 主要做三件事:
默認情況下py.test
在您的測試模塊中查找(可配置的 iirc ) test_foo.py
測試模塊和test_foo()
測試函數。
問題在於您在第一個代碼片段塊的最后顯式調用了測試函數:
test_add(sys.stdout)
你不應該這樣做; 調用您的測試函數是 pytest 的工作。 當它這樣做時,它將識別名稱capsys
(或capfd
,就此而言)並自動為您提供合適的 pytest-internal 對象作為調用參數。 ( pytest 文檔中給出的示例非常完整。)
該對象將提供所需的readouterr()
函數。 sys.stdout
沒有那個功能,這就是你的程序失敗的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.