Python | Exceptional Conditions Testing in Unit Tests

12 Jun, 2019
This article aims to write a unit test that cleanly tests if an exception is raised. To test for exceptions, the assertRaises() method is used.
Code #1 : Testing that a function raised a ValueError exception
import unittest  # A simple function to illustratedef parse_int(s):    return int(s)  class TestConversion(unittest.TestCase):    def test_bad_int(self):        self.assertRaises(ValueError, parse_int, 'N/A')
Code #2 : Test the exception’s value with a different approach is needed
import errno  class TestIO(unittest.TestCase):    def test_file_not_found(self):        try:            f = open('/file/not/found')        except IOError as e:            self.assertEqual(e.errno, errno.ENOENT)        else:            self.fail('IOError not raised')
The assertRaises() method provides a convenient way to test for the presence of an exception. A common pitfall is to write tests that manually try to do things with exceptions on their own.
Code #3 : Example
class TestConversion(unittest.TestCase):    def test_bad_int(self):        try:            r = parse_int('N/A')        except ValueError as e:            self.assertEqual(type(e), ValueError)
The problem with such approaches is that it is easy to forget about corner cases, such as that when no exception is raised at all. To do that, an extra check for that situation needs to be added, as shown in the code below.
Code #4 :
class TestConversion(unittest.TestCase):    def test_bad_int(self):        try:            r = parse_int('N/A')        except ValueError as e:            self.assertEqual(type(e), ValueError)        else:            self.fail('ValueError not raised')
The assertRaises() method simply takes care of these details, so it is preferred to be used. The one limitation of assertRaises() is that it doesn’t provide a means for testing the value of the exception object that’s created.To do that, it has to be manually tested. Somewhere in between these two extremes, the assertRaisesRegex() method can be used and it allows to test for an exception and perform a regular expression match against the exception’s string representation at the same time.
Code #5 :
class TestConversion(unittest.TestCase):    def test_bad_int(self):        self.assertRaisesRegex(                ValueError, 'invalid literal .*',                 parse_int, 'N/A')
A little-known fact about assertRaises() and assertRaisesRegex() is that they can also be used as context managers.
Code #6 :
class TestConversion(unittest.TestCase):    def test_bad_int(self):        with self.assertRaisesRegex(ValueError, 'invalid literal .*'):            r = parse_int('N/A')
This form can be useful if the test involves multiple steps (e.g., setup) besides that of simply executing a callable.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts