当我的单元测试引发异常时,如何向用户显示错误消息?
也就是说,测试的断言不仅失败,而且在尝试计算断言是否应该通过时,引发了异常。
假设我有一个看起来像这样的单元测试
import unittest
class TestClass(unittest.TestCase):
def test_this(self):
... # compute `expected`, `actual`, `helpful_info`.
self.assertEqual(expected, actual, msg=f'The test failed. {helpful_info}')
其中带省略号...
的行表示一些不重要的逻辑,这些逻辑计算预期变量和实际变量,这些变量将在以下断言中进行比较,以及一些有用的关于它们所处的上下文的调试信息(这有助于了解测试失败的原因(如果成功)。
取决于expected
和actual
的值,测试可能会失败无向我显示我编写的自定义消息。例如,以下代码:
import unittest
import torch
class TestClass(unittest.TestCase):
def test_this(self):
expected = [2,3]
actual = torch.tensor([2,3])
self.assertEqual(expected, actual, msg=f'This will not show: {expected}')
(使用PyTorch library),与python -m unittest
一起运行时输出以下内容>
E ====================================================================== ERROR: test_this (test_this.TestClass) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/juliano/test/test_this.py", line 8, in test_this self.assertEqual(expected, actual, msg=f'This will not show {expected}') File "/home/juliano/miniconda3/envs/pytorch_env/lib/python3.6/unittest/case.py", line 829, in assertEqual assertion_func(first, second, msg=msg) File "/home/juliano/miniconda3/envs/pytorch_env/lib/python3.6/unittest/case.py", line 819, in _baseAssertEqual if not first == second: TypeError: eq() received an invalid combination of arguments - got (list), but expected one of: * (Tensor other) didn't match because some of the arguments have invalid types: (list) * (Number other) didn't match because some of the arguments have invalid types: (list) ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (errors=1)
这是错误消息指出的原因,因为PyTorch的
Tensor
对象无法与列表进行比较。请注意,从未打印过自定义消息。
这可能是通过先编写一个将检查要比较的对象类型的断言,或者是其他一些首先测试assertEqual
是否会引发异常的聪明逻辑来避免的。我可能对此类型的解决方案不感兴趣,因为每当我编写assertEqual
语句时,我都不想尝试预期所有可能的异常原因。
问题我的单元测试引发异常时如何向用户显示错误消息?也就是说,测试的断言不仅失败,而且在尝试计算断言...
如果您的目标只是在assertEqual中引发异常时显示失败消息,则可以这样做