Change language

Python | Testing Exceptional Conditions in Unit Tests

| |

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.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method