Tal Weiss
Tal Weiss

Reputation: 8999

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.

Upvotes: 6

Views: 2685

Answers (2)

S.Lott
S.Lott

Reputation: 391854

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" )

Upvotes: 11

Alex Martelli
Alex Martelli

Reputation: 881635

assertRaises is a bit simplistic, and doesn't let you test the details of the raised exception beyond it belonging to a specified class. For finer-grained testing of exceptions, you need to "roll your own" with a try/except/else block (you can do it once and for all in a def assertDetailedRaises method you add to your own generic subclass of unittest's test-case, then have your test cases all inherit your subclass instead of unittest's).

Upvotes: 1

Related Questions