Python unittest: how can I check an argument in Exceptions?

I am testing Exceptions using unittest, for example:

self.assertRaises(UnrecognizedAirportError, func, arg1, arg2) 

and my code raises:

 raise UnrecognizedAirportError('From') 

Which works well.

How to verify that an argument in an exception is what I expect?

I want to somehow claim that capturedException.argument == 'From' .

I hope this is clear enough - thanks in advance!

Tal.

+5
python unit-testing
May 19, '09 at 15:10
source share
2 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 are just a subclass of Exception .

See http://docs.python.org/library/exceptions.html#module-exceptions

If the exception class is derived from the standard BaseException root class, the associated value is present as an attribute attribute of the instance instances.




Edit Higher 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" ) 
+11
May 19, '09 at 15:19
source share

assertRaises little simplified and does not allow you to check the details of the above exception outside of it belonging to the specified class. For finer testing of exceptions, you need to "collapse your own" using the try/except/else block (you can do this once and for all in the def assertDetailedRaises method, which you add to your own common unittest test-case subclass, then your test cases inherit your subclass instead of unittest's).

+1
May 19, '09 at 15:23
source share



All Articles