Home > database >  Python unittest that at least one exception is raised
Python unittest that at least one exception is raised

Time:02-06

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:

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()

CodePudding user response:

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.

  • Related