0

Is there a way to write (or run) a set of Python unittest tests so that there is no output except when there is a test failure?

For example, if tests/mytests.py contains some unittest tests, then running python3 test/mytests.py will only output to stdout (or stderr) if there is a test failure.

rlandster
  • 7,294
  • 14
  • 58
  • 96

1 Answers1

0

Yes there is. I was able to combine the techniques in the answers to these two questions to get it to work:

Python, unittest: Can one make the TestRunner completely quiet?

argparse and unittest python

You can uncomment the test_should_fail() test to verify what happens when a test fails.

# mymodule.py

def myfunc():
    return True

import unittest
import os

class TestMyFunc(unittest.TestCase):
    def test_myfunc(self):
        self.assertEqual(myfunc(), True)

    # def test_should_fail(self):
    #     self.assertEqual(True, False)

if __name__ == '__main__':
    alltests = unittest.TestLoader().loadTestsFromTestCase(TestMyFunc)
    runner = unittest.TextTestRunner(stream=open(os.devnull, 'w'))
    result = runner.run(alltests)
    if len(result.failures) or len(result.errors):
        print('There were failures or errors.')
Rusty Widebottom
  • 985
  • 2
  • 5
  • 14