Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unittest: how do I test the argument in an Exceptions?

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.

like image 915
Tal Weiss Avatar asked May 19 '09 15:05

Tal Weiss


People also ask

How do you assert Exceptions in Unittest Python?

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.


1 Answers

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" )
like image 184
S.Lott Avatar answered Oct 12 '22 01:10

S.Lott