How do you show an error message when a test does not throw an expected exception?
<p>I am new to python. I wanted to test if my code throws an exception. I got the code from here: <a href="http://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception">How do you test that a Python function throws an exception?</a></p>

<pre><code>import mymod
import unittest

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc, compulsory_argument)
</code></pre>

<p>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.</p>

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

<pre><code>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)
</code></pre>

<p><strong>Error:</strong></p>

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

<p>As of python 3.3, <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises" rel="nofollow">assertRaises</a> can be used as a context manager with a message:</p>

<pre><code>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()
</code></pre>

<p>Results in</p>

<pre><code>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)
</code></pre>

python unit-testing exception