[英]Why exception isn't printed in except block
我正在尝试从一个 except 块中断言一条消息,如下所示:
assert exceptions.main() == f"Join into Exception: {exceptions.CustomException}"
我正在使用这些文件:
# main file
class CustomException(Exception):
"""
This is a custom exception
"""
def return_an_exception():
pass
def another_func():
pass
def main():
try:
return_an_exception()
another_func()
except CustomException as e:
return f"Join into Exception: {str(e)}"
return "Not join into Exception"
# test file
import exceptions
def test_exceptions(
mocker,
):
mocker.patch("exceptions.return_an_exception").side_effect = exceptions.CustomException
mocker.patch("exceptions.another_func")
assert exceptions.main() == f"Join into Exception: {exceptions.CustomException}"
我收到此错误:
========================================================================================== FAILURES ==========================================================================================
______________________________________________________________________________________ test_exceptions _______________________________________________________________________________________
mocker = <pytest_mock.plugin.MockerFixture object at 0x102413f40>
def test_exceptions(
mocker,
):
mocker.patch("exceptions.return_an_exception").side_effect = exceptions.CustomException
mocker.patch("exceptions.another_func")
> assert exceptions.main() == f"Join into Exception: {exceptions.CustomException}"
E assert 'Join into Exception: ' == "Join into Ex...omException'>"
E - Join into Exception: <class 'exceptions.CustomException'>
E + Join into Exception:
test_exceptions.py:9: AssertionError
================================================================================== short test summary info ===================================================================================
FAILED test_exceptions.py::test_exceptions - assert 'Join on Exception: ' == "Join on Exce...omException'>"
===================================================================================== 1 failed in 0.06s ======================================================================================
你能帮我理解为什么不打印e
那是因为Exception
的__str__
方法的默认实现是返回其消息:
print(Exception()) # Prints nothing
print(Exception("An error occured")) # Prints "An error occured"
您可以通过打印e.__class__.__name__
来解决此问题:
class CustomException(Exception):
pass
def return_an_exception():
raise CustomException
def another_func():
pass
def main():
try:
return_an_exception()
another_func()
except CustomException as e:
return f"Join into Exception: {e.__class__.__name__}"
return "Not join into Exception"
print(main()) # Now prints "Join into Exception: CustomException"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.