更新时间:2023-11-22 15:04:28
从旁白开始,class
语句中 classname 后面的 ()
是完全正确的现代 Python —— 根本不是错误.
Starting with an aside, the ()
after the classname in a class
statement is perfectly correct in modern Python -- not an error at all.
关于问题的实质,assertRaises(MyException, foo)
是 记录传播通过调用 foo()
其类型不是 MyException
的子类——它只捕获 MyException
及其子类.当您的代码引发一种类型的异常并且您的测试期望一种不同的不相关类型时,引发的异常将传播,根据 unittest
模块的文档,这里,我引用:
On the meat of the issue, assertRaises(MyException, foo)
is documented to propagate exceptions raised by calling foo()
whose type is NOT a subclass of MyException
-- it only catches MyException
and subclasses thereof. As your code raises an exception of one type and your test expects one of a different unrelated type, the raised exception will then propagate, as per the docs of the unittest
module, here, and I quote:
如果引发异常,则测试通过,如果引发另一个异常,则测试为错误,如果未引发异常,则测试失败.
The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised.
是一个错误"意味着传播另一个异常".
And "is an error" means "propagates the other exception".
当您捕获在 try/except 块中传播的异常时,您消除了错误,并且 unittest
没有什么可诊断的了.如果你的目的是把这个错误变成失败(一个有争议的策略......),你的 except
块应该调用 self.fail
.
As you catch the exception propagating in your try/except block, you nullify the error, and there's nothing left for unittest
to diagnose. If your purpose is to turn this error into a failure (a debatable strategy...), your except
block should call self.fail
.