Skip to content Skip to sidebar Skip to footer

Run Python Unittest So That Nothing Is Printed If Successful, Only Assertionerror() If Fails

I have a test module in the standard unittest format class my_test(unittest.TestCase): def test_1(self): [tests] def test_2(self): [tests] etc.... My c

Solution 1:

I came up with this. If you are able to change the command line you might remove the internal io redirection.

import sys, inspect, traceback

# redirect stdout,
# can be replaced by testharness.py > /dev/null at console
class devnull():
    def write(self, data):
        pass

f = devnull()
orig_stdout = sys.stdout
sys.stdout = f

class TestCase():
    def test_1(self):
        print 'test_1'

    def test_2(self):
        raise AssertionError, 'test_2'

    def test_3(self):
        print 'test_3'


if __name__ == "__main__":
    testcase = TestCase()
    testnames =  [ t[0] for t in inspect.getmembers(TestCase)
                        if t[0].startswith('test_') ]

    for testname in testnames:
        try:
            getattr(testcase, testname)()
        except AssertionError, e:
            print >> sys.stderr, traceback.format_exc()

# restore
sys.stdout = orig_stdout

Post a Comment for "Run Python Unittest So That Nothing Is Printed If Successful, Only Assertionerror() If Fails"