Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

python - How to use nose's assert_raises?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...