Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How do you test that a Python function throws an exception?

How do I use the unittest module to test if a function throws an exception or not?

How do I test if a function involving addition of an integer and a string throw an exception or not?


1 Answer
Manogna

We write a unittest that fails only if a function doesn't throw an expected exception.

We also test if a Python function throws an exception.

For example, see the sample code we paste into the Python shell to test Python's type-safety:

import unittest
class MyTestCase(unittest.TestCase):
        def test_1_cannot_add_int_and_str(self):
                    with self.assertRaises(TypeError):
                       1 + '1'
              def test_2_cannot_add_int_and_str(self):
              import operator
              self.assertRaises(TypeError, operator.add, 1, '1')
 unittest.main(exit=False)

Running the tests

And the terminal outputs the following:

..

----------------------------------------------------------------------

Ran 2 tests in 0.001s

OK

Test one uses assertRaises as a context manager, which ensures that the error is properly caught and cleaned up, while recorded.

We could also write it without the context manager, see test two. The first argument would be the error type you expect to raise, the second argument, the function you are testing, and the remaining args and keyword args will be passed to that function.

It's far more simple, and readable to just use the context manager.

We see that as we expect, attempting to add a 1 and a '1' result in a TypeError.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.