title: Python assertRaises on user-defined exceptions
body: <p>The following question was triggered by the discussion in <a href="https://stackoverflow.com/questions/35484182/passing-exceptions-across-classes-while-unit-testing-in-python">this post</a>.</p>
  
  <p>Assume two files (<em>foobar.py</em> and <em>foobar_unittest.py</em>). File <em>foobar.py</em> contains a class (<em>FooBar</em>) with two functions (<em>foo</em> and <em>bar</em>). Function <em>bar</em> raises a built-in exception, function <em>foo</em> a user-defined exception.</p>
  
  <pre><code># foobar.py
  class MyException(Exception):
      pass
  class FooBar:
      def __init__(self):
          pass
      def bar(self):
          raise ValueError('Hello World.')
      def foo(self):
          raise MyException('Hello World.')
  </code></pre>
  
  <p>.</p>
  
  <pre><code># foobar_unittest.py
  import unittest
  import foobar as fb
  class MyException(Exception):
      pass
  class FooBarTestCases(unittest.TestCase):
      def test_bar(self):
          with self.assertRaises(ValueError):
              fb.FooBar().bar()
      def test_foo(self):
          with self.assertRaises(MyException):
              fb.FooBar().foo()
  if __name__ == '__main__':
      unittest.main()
  </code></pre>
  
  <p>When running unit-test on <em>foobar.py</em>, why does the function raising the user-defined exception (<em>foo</em>) fail to pass the test?</p>
  
  <pre><code>&gt;&gt;&gt; python2.7 foobar_unittest.py 
  .E
  ======================================================================
  ERROR: test_foo (__main__.FooBarTestCases)
  ----------------------------------------------------------------------
  Traceback (most recent call last):
    File "foobar_unittest.py", line 11, in test_foo
      fb.FooBar().foo()
    File "/a_path/foobar.py", line 9, in foo
      raise MyException('Hello World.')
  MyException: Hello World.
  
  ----------------------------------------------------------------------
  Ran 2 tests in 0.000s
  
  FAILED (errors=1)
  </code></pre>