assertraises behaviour

Peter Otten __peter__ at web.de
Mon Jul 16 11:10:49 EDT 2012


andrea crotti wrote:

> 2012/7/16 Christian Heimes <lists at cheimes.de>:
>>
>> 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
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
> 
> Ok now it's more clear, and normally I only test one thing in the block.
> But I find this quite counter-intuitive, because in the block I want
> to be able to run something that raises the exception I catch (and
> which I'm aware of), but if another exception is raised it *should*
> show it and fail in my opinion..

That doesn't sound like "it's clearer". Perhaps it helps if you translate 
your code into a standard try...except:

>>> class A(Exception): pass
... 
>>> class B(Exception): pass
... 
>>> try:
...     raise A
...     raise B
... except A as e:
...     print "caught %r" % e
... 
caught A()

The try block is left at the "raise A' statement" -- Python doesn't have an 
equivalent of Basic's "resume next". Therefore B (or OSError) is never 
raised.

PS: Strictly speaking your "assert False" is equivalent to 

if __debug__ and False: raise AssertionError

Therefore you *can* trigger the OSError by invoking the interpreter with the
"-O" option:

$ python -c 'assert False; raise OSError'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AssertionError
$ python -O -c 'assert False; raise OSError'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
OSError





More information about the Python-list mailing list