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

How do I test exceptions and errors using pytest?

我的 Python 代码中有一些函数会引发异常以响应某些条件,我想确认它们在我的 pytest 脚本中的行为是否符合预期。

目前我有

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"

但这看起来很麻烦(并且需要针对每种情况重复)。

是否有使用 Python 或首选模式来测试异常和错误的方法?

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

不起作用(即即使我用 assert False 替换断言它也会通过)。

这样:

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

exception_raised = exc_info.value
<do asserts here>