Python unittest:如何在Exceptions中测试参数?

Tal*_*iss 5 python unit-testing

我正在使用unittest测试异常,例如:

self.assertRaises(UnrecognizedAirportError, func, arg1, arg2)
Run Code Online (Sandbox Code Playgroud)

我的代码提出:

raise UnrecognizedAirportError('From')
Run Code Online (Sandbox Code Playgroud)

哪个效果很好.

我如何测试异常中的参数是否符合我的预期?

我希望以某种方式断言capturedException.argument == 'From'.

我希望这很清楚 - 提前感谢!

塔尔.

S.L*_*ott 11

像这样.

>>> try:
...     raise UnrecognizedAirportError("func","arg1","arg2")
... except UnrecognizedAirportError, e:
...     print e.args
...
('func', 'arg1', 'arg2')
>>>
Run Code Online (Sandbox Code Playgroud)

args如果您只是子类,那么您的参数就在Exception.

请参阅http://docs.python.org/library/exceptions.html#module-exceptions

如果异常类是从标准根类BaseException派生的,则关联的值将作为异常实例的args属性出现.


编辑更大的示例.

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" )
Run Code Online (Sandbox Code Playgroud)