我在一个有很多自定义异常的项目中使用 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)
我想你要找的是:
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)
小智 9
您可以在加薪中使用匹配关键字。尝试类似的东西
with pytest.raises(
RuntimeError, match=<error string here>
):
pass
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1897 次 |
最近记录: |