3

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

salce
  • 409
  • 1
  • 12
  • 28
  • 1
    Please, don't do that. Biggest strength of unit tests if a fact that output is pass/fail (and because they execute extremely fast). Stacktraces / stdout / whatever should be use only for debugging what's going wrong if tests are failing. If you force yourself to read output to know if tests have passed you will not run them as often as you should. – Łukasz Rogalski Oct 14 '14 at 19:54
  • It's for a different purpose other than debugging. – salce Oct 14 '14 at 20:23
  • Possible duplicate of [How to change the message in a Python AssertionError?](https://stackoverflow.com/questions/3807694/how-to-change-the-message-in-a-python-assertionerror) – tkruse Jun 12 '19 at 06:09

1 Answers1

4

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

tssch
  • 734
  • 8
  • 25