Update: my question was actually about understanding that assertRaises needs to make the call to the function, rather than the function itself. This question is similar to this post: How do you test that a Python function throws an exception? But is specifically asking about why my code, which was calling the function directly, wouldn't work.
I have checked several other posts here on the topic but can't figure out what is going wrong. I am trying to assert that a given exception will occur. I reduced this down to a very basic function that raises an exception type for simplicity. I have tried BaseException and that doesn't work either. I'm hoping I'm missing something basic. Thanks for your help!
I am running python 3.9.1. Code copied is from a jupyter notebook, but I get the same error using pure python and calling from a command line.
def raise_exception():
raise ValueError
class Test_exceptions(unittest.TestCase):
def test_exception(self):
self.assertRaises(ValueError, raise_exception())
unittest.main(argv=[''],verbosity=2, exit=False)
Output:
test_exception (__main__.Test_exceptions) ... ERROR
======================================================================
ERROR: test_exception (__main__.Test_exceptions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<ipython-input-8-f1c9cab8fc2b>", line 6, in test_exception
self.assertRaises(ValueError, raise_exception())
File "<ipython-input-8-f1c9cab8fc2b>", line 2, in raise_exception
raise ValueError
ValueError
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (errors=1)
<unittest.main.TestProgram at 0x22a27396550>