断言异常消息?

sna*_*che 5 python pytest

我在一个有很多自定义异常的项目中使用 pytest。

pytest 提供了一种方便的语法来检查是否已引发异常,但是,我不知道有人断言已引发正确的异常消息。

假设我有一个CustomException打印“boo!”的东西,我怎么能断言“boo!” 确实已打印,而不是说“<unprintable CustomException object>”?

#errors.py
class CustomException(Exception):
    def __str__(self): return "ouch!"
Run Code Online (Sandbox Code Playgroud)
#test.py
import pytest, myModule

def test_custom_error(): # SHOULD FAIL
    with pytest.raises(myModule.CustomException):
        raise myModule.CustomException == "boo!"
Run Code Online (Sandbox Code Playgroud)

Tom*_*ton 9

我想你要找的是:

def failer():
    raise myModule.CustomException()

def test_failer():
    with pytest.raises(myModule.CustomException) as excinfo:
        failer()

    assert str(excinfo.value) == "boo!"
Run Code Online (Sandbox Code Playgroud)

  • 注意:您必须在“with”块之外访问它,如本答案所示。在 `failer()` 之后您将无法访问它 (4认同)

小智 9

您可以在加薪中使用匹配关键字。尝试类似的东西

with pytest.raises(
        RuntimeError, match=<error string here>
    ):
     pass
Run Code Online (Sandbox Code Playgroud)