Borat Sagdiyev Borat Sagdiyev - 2 months ago 9
Python Question

How do you show an error message when a test does not throw an expected exception?

I am new to python. I wanted to test if my code throws an exception. I got the code from here: How do you test that a Python function throws an exception?

import mymod
import unittest

class MyTestCase(unittest.TestCase):
def test1(self):
self.assertRaises(SomeCoolException, mymod.myfunc, compulsory_argument)


Now, I also want to display a message if the exception is not thrown. How do I do that ? The python docs do not mention it clearly. I added the message after "compulsory_argument" and it failed.

EDIT: I tried the first answer with modifications and got an exception. What is my mistake here ?

import unittest

def sayHelloTo(name):
print("Hello " + name)

class MyTestCase(unittest.TestCase):
def test1(self):
person = "John"
with self.assertRaises(Exception, "My insightful message"):
sayHelloTo(person)


Error:

Error
Traceback (most recent call last):
File "C:\tests\tester.py", line 9, in test1
with self.assertRaises(Exception, "My insightful message"):
AttributeError: __exit__

Answer

As of python 3.3, assertRaises can be used as a context manager with a message:

import unittest

def sayHelloTo(name):
    print("Hello " + name)

class MyTestCase(unittest.TestCase):
    def test1(self):
        person = "John"
        with self.assertRaises(Exception, msg="My insightful message"):
            sayHelloTo(person)

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

Results in

Hello John
F
======================================================================
FAIL: test1 (__main__.MyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "r.py", line 10, in test1
    sayHelloTo(person)
AssertionError: Exception not raised : My insightful message

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)