salce
salce

Reputation: 407

Custom error messages in Python

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

Upvotes: 3

Views: 5953

Answers (1)

tssch
tssch

Reputation: 764

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.)

Upvotes: 4

Related Questions