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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With