将Unittest的输出记录到文本文件中 [英] Log Unittest output to a text file

查看:395
本文介绍了将Unittest的输出记录到文本文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将测试的输出记录到文本文件中.我正在使用unittest模块,并希望将结果记录到文本文件而不是屏幕中.我这里有一些脚本来解释到目前为止已经尝试过的内容.这是测试脚本.

I am trying to log the output of tests to a text file. I am using the unittest module and want to log results into a text file instead of the screen. I have some script here to explain what has been tryied so far. This is the test script.

import unittest, sys

class TestOne(unittest.TestCase):

    def setUp(self):
        self.var = 'Tuesday'
    def tearDown(self):
        self.var = None 



class BasicTestOne(TestOne):

    def runTest(self):

        TestOne.setUp(self)
        self.assertEqual(self.var, 'Tuesday')



class AbsoluteMoveTestSuite(unittest.TestSuite):

    # Tests to be tested by test suite
    def makeAbsoluteMoveTestSuite():
        suite = unittest.TestSuite()
        suite.addTest(TestOne("BasicTestOne"))

        return suite 

    def suite():
        return unittest.makeSuite(TestOne)


if __name__ == '__main__':
    unittest.main()

我已将其添加到文件中,但似乎无法正常工作.

I have added this to the file but it doesn't seem to work.

log_file = 'log_file.txt'
sys.stout = sys.sterr = open(log_file, 'w')

return suite >> sys.stout

还有:

log_file = 'log_file.txt'
return suite >> open(log_file, 'w')

我已经尝试了此命令的几种不同版本.

I have tried several different versions of this command.

if __name__ == '__main__':
    unittest.main() >> open(log_file, 'w')

我已经尝试过了.我希望在python脚本中存储和创建日志文件.我不想打电话给python tests.py >> log_file.txt.

I have tried this. I want the log file to be stored and created inside the python script. I do not want to have to call python tests.py >> log_file.txt.

感谢您的帮助

推荐答案

您可以将文本运行器传递到main方法中.必须将文本运行程序设置为写入文件,而不是将std.err写入文件,因为它将文本流包装在装饰器中.以下内容在python 2.6中为我工作

You can pass the text runner into the main method. The text runner must be set up to write to a file rather than the std.err as it wraps the stream in a decorator. The following worked for me in python 2.6

if __name__ == '__main__':
   log_file = 'log_file.txt'
   with open(log_file, "w") as f:
       runner = unittest.TextTestRunner(f)
       unittest.main(testRunner=runner)

这篇关于将Unittest的输出记录到文本文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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