test_errors.py (3144B)
1 # This Source Code Form is subject to the terms of the Mozilla Public 2 # License, v. 2.0. If a copy of the MPL was not distributed with this 3 # file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 5 import sys 6 import unittest 7 from io import StringIO 8 9 import mozunit 10 11 from mozpack.errors import AccumulatedErrors, ErrorMessage, errors 12 13 14 class TestErrors: 15 def setUp(self): 16 errors.out = StringIO() 17 errors.ignore_errors(False) 18 19 def tearDown(self): 20 errors.out = sys.stderr 21 22 def get_output(self): 23 return [l.strip() for l in errors.out.getvalue().splitlines()] 24 25 26 class TestErrorsImpl(TestErrors, unittest.TestCase): 27 def test_plain_error(self): 28 errors.warn("foo") 29 self.assertRaises(ErrorMessage, errors.error, "foo") 30 self.assertRaises(ErrorMessage, errors.fatal, "foo") 31 self.assertEqual(self.get_output(), ["warning: foo"]) 32 33 def test_ignore_errors(self): 34 errors.ignore_errors() 35 errors.warn("foo") 36 errors.error("bar") 37 self.assertRaises(ErrorMessage, errors.fatal, "foo") 38 self.assertEqual(self.get_output(), ["warning: foo", "warning: bar"]) 39 40 def test_no_error(self): 41 with errors.accumulate(): 42 errors.warn("1") 43 44 def test_simple_error(self): 45 with self.assertRaises(AccumulatedErrors): 46 with errors.accumulate(): 47 errors.error("1") 48 self.assertEqual(self.get_output(), ["error: 1"]) 49 50 def test_error_loop(self): 51 with self.assertRaises(AccumulatedErrors): 52 with errors.accumulate(): 53 for i in range(3): 54 errors.error("%d" % i) 55 self.assertEqual(self.get_output(), ["error: 0", "error: 1", "error: 2"]) 56 57 def test_multiple_errors(self): 58 with self.assertRaises(AccumulatedErrors): 59 with errors.accumulate(): 60 errors.error("foo") 61 for i in range(3): 62 if i == 2: 63 errors.warn("%d" % i) 64 else: 65 errors.error("%d" % i) 66 errors.error("bar") 67 self.assertEqual( 68 self.get_output(), 69 ["error: foo", "error: 0", "error: 1", "warning: 2", "error: bar"], 70 ) 71 72 def test_errors_context(self): 73 with self.assertRaises(AccumulatedErrors): 74 with errors.accumulate(): 75 self.assertEqual(errors.get_context(), None) 76 with errors.context("foo", 1): 77 self.assertEqual(errors.get_context(), ("foo", 1)) 78 errors.error("a") 79 with errors.context("bar", 2): 80 self.assertEqual(errors.get_context(), ("bar", 2)) 81 errors.error("b") 82 self.assertEqual(errors.get_context(), ("foo", 1)) 83 errors.error("c") 84 self.assertEqual( 85 self.get_output(), 86 [ 87 "error: foo:1: a", 88 "error: bar:2: b", 89 "error: foo:1: c", 90 ], 91 ) 92 93 94 if __name__ == "__main__": 95 mozunit.main()