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>

<blockquote>
  <p>Now, I also want to display a message if the exception is not thrown. How do I do that ?</p>
</blockquote>

<p>The general philosophy of <em>unittest</em> is for the tests to be silent when they succeed and only become verbose when they fail.  Accordingly, the API provides a "msg" keyword argument for the unsuccessful case but does not offer an alternative for the successful case.</p>

<p>That said, another part of the philosophy works in your favor.  In general, test cases internally raise an exception when a testcase fails.  That means that if you want to display a message when there is a success, you just add another statement <em>after</em> the test:</p>

<pre><code>with self.assertRaises(TypeError, msg='Oh no, I did not get a TypeError')
     somecode()
logging.info('Yippee, we got a TypeError!')  # Runs after a successful test
</code></pre>

python unit-testing exception