这是我的代码:
import unittest
import sys
import os
class DemoTest(unittest.TestCase):
def test_one(self):
print "test one"
self.assertTrue(True)
def test_two(self):
print "test two"
self.assertTrue(False)
if __name__ == '__main__':
dirpath = os.path.dirname(os.path.abspath(__file__))
sys.stdout = open(dirpath+'/test_logs/demo_test.stdout.log', 'w')
sys.stderr = open(dirpath+'/test_logs/demo_test.stderr.log', 'w')
test_program = unittest.main(verbosity=0, exit=False)
当我运行它时,内容demo_test.stdout.log
仅为:
test one
test two
在屏幕上,我仍然可以看到 unittest 的输出:
======================================================================
FAIL: test_two (__main__.DemoTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "demotest.py", line 12, in test_two
self.assertTrue(False)
AssertionError: False is not true
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=1)
我希望屏幕上没有输出并且要记录所有内容。(我将测试作为 cron 作业运行,因此到 stdout 或 stderr 的任何输出都会导致发送电子邮件,因此我希望能够准确指定何时发生这种情况,这意味着我需要能够在此控制 unittest看待。)