assertRaises in unittest not catching Exception properly
<p>I have a file testtest.py that i contains the code</p>

<pre><code>import unittest

def add(self, a, b):
    return a + b

class Test(unittest.TestCase):

    def test_additon(self):
        self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed")
        #self.assertRaises(TypeError, lambda: add(1 + '1'), msg="Addition failed")

if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>The problem is that <code>assertRaises</code> doesn't catch the exception properly and all my tests keep failing as errors not based on the condition, this is the output that I'm getting:</p>

<pre><code>E
======================================================================
ERROR: test_additon (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "testtest.py", line 9, in test_additon
    self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
</code></pre>

<p>I know i can get around it by using lambda (i commented it out in the code) to make my tests properly catch the exceptions, but according to the docs, passing a callable and the arguments to <code>assertRaises</code> should work, as it will call the function internally by itself and be able to trap any exception that was raised.</p>

<pre><code>assertRaises(*callable*, *args*, *kwargs*)
</code></pre>

<p>but it doesn't</p>

<p>if i run it with lambda which is a callable that would be evaluated later by <code>assertRaises</code>, it works as expected and i get this</p>

<pre><code>----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
</code></pre>

<p><code>I'm running python 3.5</code></p>

<pre><code>Python 3.5.2 (default, Jun 28 2016, 08:46:01) 
[GCC 6.1.1 20160602] on linux
</code></pre>

<p>but i also get the same behaviour with <code>python2.7</code></p>

<p>Try</p>

<pre><code>def test_additon(self):
    with self.assertRaises(TypeError):
        add(1 + '1')
</code></pre>

<p>The problem is that the exception is raised during argument evaluation before self.assertRaises can kick in.</p>

python unit-testing lambda python-3.5 python-unittest