简体   繁体   English

如何使用pytest测试异常和错误?

[英]How do I test exceptions and errors using pytest?

I have functions in my Python code that raise exceptions in response to certain conditions, and would like to confirm that they behave as expected in my pytest scripts. 我的Python代码中有函数可以响应某些条件引发异常,并且想确认它们在我的pytest脚本中的行为与预期一致

Currently I have 目前我有

def test_something():
    try:
        my_func(good_args)
        assert True
    except MyError as e:
        assert False
    try:
        my_func(bad_args)
        assert False
    except MyError as e:
        assert e.message == "My expected message for bad args"

but this seems cumbersome (and needs to be repeated for each case). 但这看起来很麻烦(需要对每个案例重复)。

Is there way to test exceptions and errors using Python, or a preferred pattern for doing so? 有没有办法使用Python测试异常和错误,或者这样做的首选模式?

def test_something():
    with pytest.raises(TypeError) as e:
        my_func(bad_args)
        assert e.message == "My expected message for bad args"

does not work (ie it passes even if I replace the assertion with assert False ). 不起作用(即使用assert False替换断言,它也会通过)。

This way: 这条路:

with pytest.raises(<YourException>) as exc_info:
    <your code that should raise YourException>

exception_raised = exc_info.value
<do asserts here>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM