Log Unittest output to a text file

18,943

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)
Share:
18,943
chrisg
Author by

chrisg

All things serverless at the minute. Enjoy travelling and getting my hands on any piece of technology that is of course going to make my life amazing :)

Updated on June 15, 2022

Comments

  • chrisg
    chrisg almost 2 years

    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

  • Man Wa kileleshwa
    Man Wa kileleshwa over 4 years
    where is the log_file.tx created? is it in the folder that the test is running?
  • Andrew Cox
    Andrew Cox over 4 years
    Its been a while but the open(log_file, "w") will be relative to the current working directory see docs.python.org/3/library/functions.html#open
  • Tom Smith
    Tom Smith over 2 years
    Hi, this doesn't work for me. The code runs fine but no file is created. Is this an outdated answer? I'm running python 3.9.7.