showard | 756d82e | 2009-04-29 21:35:48 +0000 | [diff] [blame^] | 1 | #!/usr/bin/python2.4 |
| 2 | |
| 3 | import cStringIO, logging, os, sys, unittest |
| 4 | |
| 5 | # direct imports; autotest_lib has not been setup while testing this. |
| 6 | from common_lib.test_utils import mock |
| 7 | import setup_modules |
| 8 | |
| 9 | |
| 10 | class LoggingErrorStderrTests(unittest.TestCase): |
| 11 | def setUp(self): |
| 12 | autotest_dir = os.path.abspath(os.path.join(setup_modules.dirname, |
| 13 | '..')) |
| 14 | setup_modules.setup(autotest_dir, root_module_name='autotest_lib') |
| 15 | self.god = mock.mock_god() |
| 16 | self.test_stderr = cStringIO.StringIO() |
| 17 | self.god.stub_with(sys, 'stderr', self.test_stderr) |
| 18 | self.old_root_logging_level = logging.root.level |
| 19 | logging.basicConfig(level=logging.ERROR) |
| 20 | |
| 21 | |
| 22 | def tearDown(self): |
| 23 | self.god.unstub_all() |
| 24 | # Undo the setUp logging.basicConfig call. |
| 25 | logging.basicConfig(level=self.old_root_logging_level) |
| 26 | |
| 27 | |
| 28 | def assert_autotest_logging_handle_error_called(self): |
| 29 | self.stderr_str = self.test_stderr.getvalue() |
| 30 | self.assertTrue('Exception occurred formatting' in self.stderr_str, |
| 31 | repr(self.stderr_str)) |
| 32 | |
| 33 | |
| 34 | def test_autotest_logging_handle_error(self): |
| 35 | record = logging.LogRecord( |
| 36 | 'test', logging.DEBUG, __file__, 0, 'MESSAGE', 'ARGS', None) |
| 37 | try: |
| 38 | raise RuntimeError('Exception context needed for the test.') |
| 39 | except RuntimeError: |
| 40 | setup_modules._autotest_logging_handle_error(logging.Handler(), |
| 41 | record) |
| 42 | else: |
| 43 | self.fail() |
| 44 | self.assert_autotest_logging_handle_error_called() |
| 45 | self.assertTrue(('MESSAGE' in self.stderr_str), repr(self.stderr_str)) |
| 46 | self.assertTrue(('ARGS' in self.stderr_str), repr(self.stderr_str)) |
| 47 | self.assertTrue(('Exception' in self.stderr_str), repr(self.stderr_str)) |
| 48 | self.assertTrue(('setup_modules_unittest.py' in self.stderr_str), |
| 49 | repr(self.stderr_str)) |
| 50 | |
| 51 | |
| 52 | def test_logging_monkey_patch_wrong_number_of_args(self): |
| 53 | logging.error('logging unittest %d %s', 32) |
| 54 | self.assert_autotest_logging_handle_error_called() |
| 55 | self.assertTrue('logging unittest' in self.stderr_str, |
| 56 | repr(self.stderr_str)) |
| 57 | |
| 58 | |
| 59 | def test_logging_monkey_patch_wrong_type_of_arg(self): |
| 60 | logging.error('logging unittest %d', 'eighteen') |
| 61 | self.assert_autotest_logging_handle_error_called() |
| 62 | self.assertTrue('logging unittest' in self.stderr_str, |
| 63 | repr(self.stderr_str)) |
| 64 | |
| 65 | |
| 66 | def test_logging_no_error(self): |
| 67 | logging.error('logging unittest. %s %s', 'meep', 'meep!') |
| 68 | self.assertEqual('', self.test_stderr.getvalue()) |
| 69 | |
| 70 | |
| 71 | if __name__ == "__main__": |
| 72 | unittest.main() |