Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log Unittest output to a text file

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

and also:

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')

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.

Thanks for any help

like image 501
chrisg Avatar asked Apr 26 '10 10:04

chrisg


1 Answers

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)
like image 116
Andrew Cox Avatar answered Nov 14 '22 00:11

Andrew Cox