Here is my code:
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)
When I run this, the contents of demo_test.stdout.log
is only:
test one
test two
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)
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.)
Alternatively, you can use set sys. stdout to os. devnull, which is the file path of the null device. The file path of the null device is /dev/null on Unix and nul on Windows.
unittest.skipUnless(condition, reason) Skip the decorated test unless condition is true.
using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.
pytest supports running Python unittest -based tests out of the box. It's meant for leveraging existing unittest -based test suites to use pytest as a test runner and also allow to incrementally adapt the test suite to take full advantage of pytest's features.
redirect stderr, e.g.:
python my_unit_test_launcher.py 2> log.txt
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