OLD | NEW |
(Empty) | |
| 1 #!/usr/bin/env python |
| 2 # Copyright 2015 The LUCI Authors. All rights reserved. |
| 3 # Use of this source code is governed under the Apache License, Version 2.0 |
| 4 # that can be found in the LICENSE file. |
| 5 |
| 6 import unittest |
| 7 |
| 8 import test_env |
| 9 |
| 10 from recipe_engine import util |
| 11 |
| 12 |
| 13 class TestMultiException(unittest.TestCase): |
| 14 |
| 15 def testNoExceptionsRaisesNothing(self): |
| 16 mb = util.MultiException.Builder() |
| 17 with mb.catch(): |
| 18 pass |
| 19 mb.raise_if_any() |
| 20 |
| 21 mexc = util.MultiException() |
| 22 self.assertEqual(str(mexc), 'MultiException(No exceptions)') |
| 23 |
| 24 def testExceptionsRaised(self): |
| 25 fail_exc = Exception('fail!') |
| 26 mb = util.MultiException.Builder() |
| 27 with mb.catch(): |
| 28 raise fail_exc |
| 29 |
| 30 mexc = mb.get() |
| 31 self.assertEqual(len(mexc), 1) |
| 32 self.assertIs(mexc[0], fail_exc) |
| 33 self.assertEqual(str(mexc), 'MultiException(fail!)') |
| 34 |
| 35 def testMultipleExceptions(self): |
| 36 mb = util.MultiException.Builder() |
| 37 with mb.catch(): |
| 38 raise KeyError('One') |
| 39 with mb.catch(): |
| 40 raise ValueError('Two') |
| 41 |
| 42 mexc = mb.get() |
| 43 self.assertIsNotNone(mexc) |
| 44 self.assertEqual(len(mexc), 2) |
| 45 |
| 46 exceptions = list(mexc) |
| 47 self.assertIsInstance(exceptions[0], KeyError) |
| 48 self.assertIsInstance(exceptions[1], ValueError) |
| 49 self.assertEqual(str(mexc), "MultiException('One', and 1 more...)") |
| 50 |
| 51 def testTargetedException(self): |
| 52 mb = util.MultiException().Builder() |
| 53 def not_caught(): |
| 54 with mb.catch(ValueError): |
| 55 raise KeyError('One') |
| 56 self.assertRaises(KeyError, not_caught) |
| 57 self.assertIsNone(mb.get()) |
| 58 |
| 59 |
| 60 class TestMapDeferExceptions(unittest.TestCase): |
| 61 |
| 62 def testNoExceptionsDoesNothing(self): |
| 63 v = [] |
| 64 util.map_defer_exceptions(lambda e: v.append(e), [1, 2, 3]) |
| 65 self.assertEqual(v, [1, 2, 3]) |
| 66 |
| 67 def testCatchesExceptions(self): |
| 68 v = [] |
| 69 def fn(e): |
| 70 if e == 0: |
| 71 raise ValueError('Zero') |
| 72 v.append(e) |
| 73 |
| 74 mexc = None |
| 75 try: |
| 76 util.map_defer_exceptions(fn, [0, 1, 0, 0, 2, 0, 3, 0]) |
| 77 except util.MultiException as e: |
| 78 mexc = e |
| 79 |
| 80 self.assertEqual(v, [1, 2, 3]) |
| 81 self.assertIsNotNone(mexc) |
| 82 self.assertEqual(len(mexc), 5) |
| 83 |
| 84 def testCatchesSpecificExceptions(self): |
| 85 def fn(e): |
| 86 raise ValueError('Zero') |
| 87 self.assertRaises(ValueError, util.map_defer_exceptions, fn, [1], KeyError) |
| 88 |
| 89 |
| 90 if __name__ == '__main__': |
| 91 unittest.main() |
OLD | NEW |