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.

1 Answer 1

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.')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.