Run Python unittest so that nothing is printed if successful, only AssertionError() if fails

前端 未结 1 1615
我在风中等你
我在风中等你 2021-02-05 18:48

I have a test module in the standard unittest format

class my_test(unittest.TestCase):

    def test_1(self):
        [tests]

    def test_2(self):
        [tes         


        
1条回答
  •  情深已故
    2021-02-05 19:15

    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
    

    0 讨论(0)
提交回复
热议问题