assertraises behaviour

Christian Heimes lists at cheimes.de
Mon Jul 16 15:55:18 CEST 2012


Am 16.07.2012 15:38, schrieb andrea crotti:
> This small example doesn't fail, but the OSError exception is cathed
> even if not declared..
> Is this the expected behaviour (from the doc I would say it's not).
> (Running on arch-linux 64 bits and Python 2.7.3, but it doesn the same
> with Python 3.2.3)
> 
> import unittest
> 
> class TestWithRaises(unittest.TestCase):
>     def test_ass(self):
>         with self.assertRaises(AssertionError):
>             assert False, "should happen"
>             raise OSError("should give error")

The OSError isn't catched as the code never reaches the line with "raise
OSError". In other words "raise OSError" is never executed as the
exception raised by "assert False" stops the context manager.

You should avoid testing more than one line of code in a with
self.assertRaises() block.

Christian




More information about the Python-list mailing list