How to use nose's assert_raises?

a 夏天 提交于 2019-11-28 23:34:32

问题


I've searched for documentation, but couldn't find any. There were a couple that didn't explain much.

Can someone explain to me Nose's

assert_raises(what should I put here?)

function and how to use it?


回答1:


The assert_raises() function tests to make sure a function call raises a specified exception when presented with certain parameters.

For example, if you had a function add that adds two numbers, it should probably raise a TypeError when you pass it, say, an integer and a string. So:

from nose.tools import assert_raises

def add(x, y):
    return x + y

assert_raises(TypeError, add, 2, "0")

The first argument is the exception type you expect. The second is the function to call. The rest of the arguments will be passed to the function (in this case, they will become x and y inside the function).

If the expected exception is raised by the function, the assertion passes.




回答2:


While the accepted answer is correct, I think there is a better use to assert_raises method.

If you simply want to assert that an exception occurs, it's probably simpler and cleaner to use @raises syntax.

@raises(HTTPError)
def test_exception_is_raised:
    call_your_method(p1, p2)

However, assume you want to do bit more with the raised exception, for example: we need to assert that raised HTTPError is of type 401: Unauthorized, instead of 500: Server Error.

In such a situation above syntax is not that helpful, we should use the assert_raises but in a different way. If we do not pass it a callable as the second parameter assert_raises will return back a context which we can use to further test the exception details.

def test_exception_is_raised:
    with assert_raises(HTTPError) as cm:
         call_your_method(p1, p2)
    ex = cm.exception # raised exception is available through exception property of context
    ok_(ex.code == 401, 'HTTPError should be Unauthorized!')


来源:https://stackoverflow.com/questions/11767938/how-to-use-noses-assert-raises

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!