我有這樣的示例代碼(test_it.py
):丟棄標準輸出下測試程序/標準錯誤,但保留單元測試輸出
import sys
def give_me_5():
print >>sys.stdout, "STDOUT"
print >>sys.stderr, "STDERR"
return 6
import unittest
class TestMe(unittest.TestCase):
def setUp(self):
pass
def test_give_me_5(self):
self.assertEqual(give_me_5(), 5)
if __name__ == '__main__':
unittest.main()
這給了我下面的輸出:
» python -m unittest test_it
A long annoying output message
A long annoying error message
F
======================================================================
FAIL: test_give_me_5 (__main__.TestMe)
----------------------------------------------------------------------
Traceback (most recent call last):
File "xx.py", line 17, in test_give_me_5
self.assertEqual(give_me_5(), 5)
AssertionError: 6 != 5
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
但由於由測試程序(真正的程序產生LOTS輸出)產生的長,煩人的消息,我無法看到unittest的輸出。我想擺脫正在測試的函數(give_me_5
)的stdout/stderr,但我仍然希望看到stdout/stderr的unittest
。我想得到這樣的結果:
» python -m unittest test_it
F
======================================================================
FAIL: test_give_me_5 (__main__.TestMe)
----------------------------------------------------------------------
Traceback (most recent call last):
File "xx.py", line 17, in test_give_me_5
self.assertEqual(give_me_5(), 5)
AssertionError: 6 != 5
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
因此,根據試驗(標準輸出和標準錯誤)由程序產生的輸出由單元測試,過濾掉,但輸出產生的單元測試本身保持。我不想修改正在測試的代碼(代碼本身沒有重定向)。我只想告訴unittest,所有輸出到stdout/stderr被測試的代碼應該被丟棄。
這可能嗎?
可能的[python-如何重定向unittest的輸出?明顯的解決方案不起作用](http://stackoverflow.com/questions/14246119/python-how-can-i-redirect-the-output-of-unittest-obvious-solution-doesnt-wor) –
@DougR。另一個問題是關於相反的問題:這個人得到了程序的輸出,單元測試的輸出被分解了,這正是我想要實現的。 – dangonfast