blob: 50132679e2dcd4d3dcce34d4d4928935d50a9993 [file] [log] [blame]
Adrià Vilanova Martínezf19ea432024-01-23 20:20:52 +01001# Copyright 2020 The Chromium Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
Copybara854996b2021-09-07 19:36:02 +00004"""Unittest for the exceptions module."""
5
6from __future__ import print_function
7from __future__ import division
8from __future__ import absolute_import
9
10import unittest
11
12from framework import exceptions
13from framework import permissions
14
15
16class ErrorsManagerTest(unittest.TestCase):
17
18 def testRaiseIfErrors_Errors(self):
19 """We raise the given exception if there are errors."""
20 err_aggregator = exceptions.ErrorAggregator(exceptions.InputException)
21
22 err_aggregator.AddErrorMessage('The chickens are missing.')
23 err_aggregator.AddErrorMessage('The foxes are free.')
Adrià Vilanova Martínezf19ea432024-01-23 20:20:52 +010024 with self.assertRaisesRegex(
Copybara854996b2021-09-07 19:36:02 +000025 exceptions.InputException,
26 'The chickens are missing.\nThe foxes are free.'):
27 err_aggregator.RaiseIfErrors()
28
29 def testErrorsManager_NoErrors(self):
30 """ We don't raise exceptions if there are not errors. """
31 err_aggregator = exceptions.ErrorAggregator(exceptions.InputException)
32 err_aggregator.RaiseIfErrors()
33
34 def testWithinContext_ExceptionPassedIn(self):
35 """We do not suppress exceptions raised within wrapped code."""
36
Adrià Vilanova Martínezf19ea432024-01-23 20:20:52 +010037 with self.assertRaisesRegex(exceptions.InputException,
38 'We should raise this'):
Copybara854996b2021-09-07 19:36:02 +000039 with exceptions.ErrorAggregator(exceptions.InputException) as errors:
40 errors.AddErrorMessage('We should ignore this error.')
41 raise exceptions.InputException('We should raise this')
42
43 def testWithinContext_NoExceptionPassedIn(self):
44 """We raise an exception for any errors if no exceptions are passed in."""
Adrià Vilanova Martínezf19ea432024-01-23 20:20:52 +010045 with self.assertRaisesRegex(exceptions.InputException,
46 'We can raise this now.'):
Copybara854996b2021-09-07 19:36:02 +000047 with exceptions.ErrorAggregator(exceptions.InputException) as errors:
48 errors.AddErrorMessage('We can raise this now.')
49 return True
50
51 def testAddErrorMessage(self):
52 """We properly handle string formatting when needed."""
53 err_aggregator = exceptions.ErrorAggregator(exceptions.InputException)
54 err_aggregator.AddErrorMessage('No args')
55 err_aggregator.AddErrorMessage('No args2', 'unused', unused2=1)
56 err_aggregator.AddErrorMessage('{}', 'One arg')
57 err_aggregator.AddErrorMessage('{}, {two}', '1', two='2')
58
59 # Verify exceptions formatting a message don't clear the earlier messages.
60 with self.assertRaises(IndexError):
61 err_aggregator.AddErrorMessage('{}')
62
63 expected = ['No args', 'No args2', 'One arg', '1, 2']
64 self.assertEqual(err_aggregator.error_messages, expected)