这是我的代码:
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)
Run Code Online (Sandbox Code Playgroud)
当我运行它时,内容demo_test.stdout.log仅为:
test one
test two
Run Code Online (Sandbox Code Playgroud)
在屏幕上我仍然看到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)
Run Code Online (Sandbox Code Playgroud)
我希望屏幕上没有输出以及要记录的所有内容.(我作为一个cron作业运行测试,所以输出到stdout或stderr导致发送一封电子邮件,所以我希望能够确切地指定何时发生这种情况,这意味着我需要能够在此控制unittest看待.)