为什么python unittest assertRaises方法不注册抛出的异常?



我有一个类似于这篇文章的问题,但是解决方案对我没有帮助,因为我只传递一个参数给函数。

我有以下代码:

def outer():
def tuple_unpacker( mytuple ):
try:
a,b,c = mytuple
return a+b+c
except ValueError:
print('pass tuple with exactly 3 elements')
except TypeError:
print('pass only integers in tuple')
return tuple_unpacker

,我使用python unittest模块进行测试。然而,即使我的异常,断言失败。

class TestInner(unittest.TestCase):
def test_tuple_unpacker(self):
func = outer()
self.assertRaises(TypeError, func, (1,'a',1))
self.assertRaises(ValueError, func, (1,1,1,1))

当我运行这个时,回溯是:

pass only integers in tuple
F
======================================================================
FAIL: test_tuple_unpacker (__main__.TestInner)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/malte/TDDE23_git/lab5/test_test.py", line 21, in test_tuple_unpacker
self.assertRaises(TypeError, func, (1,'a',1))
AssertionError: TypeError not raised by tuple_unpacker
----------------------------------------------------------------------
Ran 1 test in 0.000s

可以看到,它打印了pass only integers in tuple,因此抛出了异常。

如果我调换位置,首先测试ValueError并失败,问题也是一样的。

奇怪的是,如果我将断言更改为:

class TestInner(unittest.TestCase):
def test_tuple_unpacker(self):
func = outer()
self.assertRaises(TypeError, func((1,'a',1)))
self.assertRaises(ValueError, func((1,1,1,1)))

它适用于TypeError,但不适用于ValueError。

这是回溯:

pass only integers in tuple
pass tuple with exactly 3 elements
E
======================================================================
ERROR: test_tuple_unpacker (__main__.TestInner)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/malte/TDDE23_git/lab5/test_test.py", line 22, in test_tuple_unpacker
self.assertRaises(ValueError, func((1,1,1,1)))
File "/usr/local/Cellar/python@3.9/3.9.7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/case.py", line 731, in assertRaises
return context.handle('assertRaises', args, kwargs)
File "/usr/local/Cellar/python@3.9/3.9.7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/case.py", line 201, in handle
callable_obj(*args, **kwargs)
TypeError: 'NoneType' object is not callable
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)

感谢所有的指导。

tuple_unpacker打印,然后抑制TypeErrorValueError异常。您的测试检查这些异常,但由于异常没有被修正,因此测试失败。函数或测试有bug,需要修改

最新更新