I am testing for Exceptions using unittest, for example:
self.assertRaises(UnrecognizedAirportError, func, arg1, arg2)
and my code raises:
raise UnrecognizedAirportError('From')
Which works well.
How do I test that the argument in the exception is what I expect it to be?
I wish to somehow assert that capturedException.argument == 'From'
.
I hope this is clear enough - thanks in advance!
Tal.
There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.
Like this.
>>> try:
... raise UnrecognizedAirportError("func","arg1","arg2")
... except UnrecognizedAirportError, e:
... print e.args
...
('func', 'arg1', 'arg2')
>>>
Your arguments are in args
, if you simply subclass Exception
.
See http://docs.python.org/library/exceptions.html#module-exceptions
If the exception class is derived from the standard root class BaseException, the associated value is present as the exception instance’s args attribute.
Edit Bigger Example.
class TestSomeException( unittest.TestCase ):
def testRaiseWithArgs( self ):
try:
... Something that raises the exception ...
self.fail( "Didn't raise the exception" )
except UnrecognizedAirportError, e:
self.assertEquals( "func", e.args[0] )
self.assertEquals( "arg1", e.args[1] )
except Exception, e:
self.fail( "Raised the wrong exception" )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With