Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python unittest that at least one exception is raised

Is there a way to get unittest standard library to check for multiple exceptions?

Obviously assertRaises works for a single exception: How do you test that a Python function throws an exception?

But I want to test whether at least one error is raised. This feels right, but is not correct:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

with self.assertRaises(StatisticsError, ZeroDivisionError):    # Test one or the other?
  my_list_mean([])

Full MRE: a "mean" function may raise a ZeroDivisionError or a StatisticsError depending on the implementation. I want to assert that this raises one or the other:

from statistics import mean, StatisticsError
import unittest

def my_list_mean(lof):
    # return sum(lof) / len(lof)    # ZeroDivisionError
    return mean(lof)                # StatisticsError

class TestMultipleWaysToComputeMean(unittest.TestCase):
    def test_zero_division_or_statistics_error(self):
        with self.assertRaises(ZeroDivisionError):
            _ = my_list_mean([])

if __name__ == "__main__":  unittest.main()

>Solution :

Pass an actual tuple. Right now, you are passing StatisticsError as an exception and ZeroDivisionError as a callable that might produce a StatisticsError.

with self.assertRaises((StatisticsError, ZeroDivisionError)):
    my_list_mean([])

From the documentation:

Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading