Python | Testing Exceptional Conditions in Unit Tests

File handling | Python Methods and Functions | Regular Expressions

Code # 1: Check that the function raised a ValueError

import unittest

  
# Simple function for illustration

def parse_int (s):

return int (s)

 

class TestConversion (unittest.TestCase ):

def test_bad_int ( self ):

self . assertRaises (ValueError, parse_int, 'N / A' )

Code # 2 : need to check the value of the exception with a different approach

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 check for an exception. A common mistake is writing tests that manually try to do something 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's easy to forget about corner cases, such as the case where no exceptions are thrown. To do this, you need to add an extra check for this situation 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 just takes care of these details, so it's preferred to use it. The only limitation of assertRaises () is that it does not provide a means to validate the value of the generated exception object. 
To do this, it must be manually checked. Somewhere in between these two extremes, you can use the assertRaisesRegex () method which allows you to check for an exception while matching the regular expression against the string representation of the exception.

Code # 5:

class TestConversion (unittest.TestCase):

def test_bad_int ( self ):

self . assertRaisesRegex (

ValueError, 'invalid literal. *'

parse_int, 'N / 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 a test has multiple steps (such as customization) besides just executing the called one.





Get Solution for free from DataCamp guru