如何重定向unittest的输出?明显的解决方案不起作用 [英] How can I redirect the output of unittest? Obvious solution doesn't work

查看:26
本文介绍了如何重定向unittest的输出?明显的解决方案不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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 的内容只有:

When I run this, the contents of demo_test.stdout.log is only:

test one
test two

在屏幕上我仍然看到 unittest 的输出:

on the screen I still see the output from 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 都会导致发送电子邮件,因此我希望能够准确指定发生这种情况的时间,这意味着我需要能够在此控制单元测试考虑.)

I want there to be no output on the screen and everything to be logged. (I am running the test as a cron job, so any output to stdout or stderr causes an email to be sent, so I want to be able to specify exactly when this happens, which means I need to be able to control unittest in this regard.)

推荐答案

重定向标准错误,例如:

redirect stderr, e.g.:

python my_unit_test_launcher.py 2> log.txt

这篇关于如何重定向unittest的输出?明显的解决方案不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆