Make Python unittest show AssertionError but no Traceback

后端 未结 3 2116
猫巷女王i
猫巷女王i 2021-01-04 18:56

I have looked at the other related questions here but have not found my answer. I would like to simplify the output of my Python (2.7) unittests. Trying sys.tracebackl

3条回答
  •  情书的邮戳
    2021-01-04 19:43

    The trick is to catch the exception, strip out the bits that aren't needed and throw it again...

    Based on this answer - the following code works...

    #!/usr/bin/python -E
    import unittest
    import os
    import sys
    
    class TestSequense(unittest.TestCase):
        pass
    
    def test_dir_exists(dir):
        def test(self):
           try:
               self.assertTrue(os.path.isdir(dir),"ERROR: " + dir + " is not a directory")
           except:
               # Remove traceback info as we don't need it
               unittest_exception = sys.exc_info()
               raise unittest_exception[0], unittest_exception[1], unittest_exception[2].tb_next
        return test
    
    if __name__ == '__main__':
        test = test_dir_exists("/something/not/set/correctly")
        setattr(TestSequense, "test_path",  test)
        unittest.main()
    

    And generates the following...

    ./simple_unittest.py
    F
    ======================================================================
    FAIL: test_path (__main__.TestSequense)
    ----------------------------------------------------------------------
    AssertionError: ERROR: /something/not/set/correctly is not a directory
    
    ----------------------------------------------------------------------
    Ran 1 test in 0.000s
    

提交回复
热议问题