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

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically