Custom error messages in Python

左心房为你撑大大i 提交于 2019-12-24 03:15:17

问题


So I'm practicing some unit test and I have a question about error messages. I'm trying to create a custom error message that will display when the test fails. Here is a basic Hello World program. The test runs fine and everything, but here is the error message I get.

F ====================================================================== FAIL: test_StringContains
 (__main__.TestSuite) ----------------------------------------------------------------------   
Traceback    (most recent call last): File "Testsuite.py", line 8, in test_StringContains 
self.assertEqual("Hello,    World", hello_world,"This is a custom error") AssertionError: 'Hello,   
World' != 'Hello World' - Hello,    World ? - + Hello World : This is a custom error ---------------  
------------------------------------------------------- 
Ran 1 test in 0.000s FAILED (failures=1)

So this is expected. Here is my test suite

from  HelloWorld import*
import unittest

class TestSuite(unittest.TestCase):

    def test_StringContains(self):
            self.assertEqual("Hello World", hello_world,"This is a custom")


if __name__ == "__main__":
    unittest.main()

and here is my run code

hello_world = "Hello World"
print (hello_world)

Super basic, just want to understand how to throw a custom error message. The only thing I want to see if the test fails is This is a custom error, I tried following the Python documentation on Errors & Exceptions here https://docs.python.org/2/tutorial/errors.html , but not sure how to implement it.

I don't know if this is doable or not. Any help is greatly appreciated. Thank you


回答1:


What you could do is to catch the AssertionError by wrapping the assertEqual in a try except statement and then print the error:

        try:
            self.assertEqual("Hello World", hello_world,"This is a custom error")
        except AssertionError as e:
            print(e)

There is however a downside when catching the AssertionError: the unittest module can no longer count the errors. (Stacktraces are not beautiful but they server the purpose of exactly pointing you to the point in the stack where the error occured.)



来源:https://stackoverflow.com/questions/26368064/custom-error-messages-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!