1

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>
Gigi
  • 347
  • 4
  • 11
  • Does this answer your question? [How do you test that a Python function throws an exception?](https://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception) – KurtMica Feb 11 '21 at 19:11
  • No - as far as I can see I have written pretty much what is in that answer and I am recieving and error – Gigi Feb 11 '21 at 19:15

1 Answers1

2

The problem in your code is you are executing the function with this line.

self.assertRaises(ValueError, raise_exception())

whereas it should be unittest module doing the same.

Just remove the parentheses from function name.

self.assertRaises(ValueError, raise_exception)
gsb22
  • 2,112
  • 2
  • 10
  • 25
  • Thank you that was the exact problem. – Gigi Feb 11 '21 at 19:20
  • Apparently, all other answers regarding this problem seem to assume that you already know that you need to omit the brackets from the function call. Thank you for pointing out this pitfall explicitly! – M463 Jun 17 '21 at 13:18