Make Python unittest show AssertionError but no Traceback

后端 未结 3 2100
猫巷女王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:28

    I'm not sure if it's possible with vanilla unittest module. But you should take a look at py.test, with it you can configure the amount of information shown in a traceback with the --tb switch.

    Probably you are interested in

    py.test --tb=line    # only one line per failure
    

    See this page for a full list of options.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-04 19:51

    unittest has a mechanism for hiding the contents of the TestCase.assert* methods in the traceback, as those really don't contain any useful information for failures. It looks for __unittest in the frame's globals. You can hide an entire module from the tracebacks by putting __unittest = True at the top of the module.

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