I have a problem similar to this post, however the solution doesn't help me as I only pass one argument to the function.
I have the following code:
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
which I test using the python unittest module. However, even when my exceptions are raised, the assertions fail.
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))
When I run this, the traceback is:
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
As you can see, it printed pass only integers in tuple
so the exception was thrown.
The problem is the same if i switch places so the ValueError is tested first and fails.
Weirdly enough, if i change the assertions to:
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)))
It works for the TypeError, but not the ValueError.
Here is the traceback:
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)
Thankful for all guidance.
tuple_unpacker
prints and then suppresses TypeError
and ValueError
exceptions. Your test checks for these exceptions but since the exceptions aren't reraised, the test fails. Either the function or the test has a bug and needs to change.