|
| 1 | +# |
| 2 | +# Sonar Scanner Python |
| 3 | +# Copyright (C) 2011-2024 SonarSource SA. |
| 4 | +# mailto:info AT sonarsource DOT com |
| 5 | +# |
| 6 | +# This program is free software; you can redistribute it and/or |
| 7 | +# modify it under the terms of the GNU Lesser General Public |
| 8 | +# License as published by the Free Software Foundation; either |
| 9 | +# version 3 of the License, or (at your option) any later version. |
| 10 | +# This program is distributed in the hope that it will be useful, |
| 11 | +# |
| 12 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 14 | +# Lesser General Public License for more details. |
| 15 | +# |
| 16 | +# You should have received a copy of the GNU Lesser General Public License |
| 17 | +# along with this program; if not, write to the Free Software Foundation, |
| 18 | +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 19 | +# |
| 20 | +import pytest |
| 21 | +import unittest |
| 22 | +import logging |
| 23 | +from pysonar_scanner.exceptions import log_error, EXCEPTION_RETURN_CODE |
| 24 | + |
| 25 | + |
| 26 | +class TestExceptions(unittest.TestCase): |
| 27 | + @pytest.fixture(autouse=True) |
| 28 | + def set_caplog(self, caplog: pytest.LogCaptureFixture): |
| 29 | + self.caplog = caplog |
| 30 | + |
| 31 | + def test_log_error_returns_exception_return_code(self): |
| 32 | + exception = Exception("Test exception") |
| 33 | + result = log_error(exception) |
| 34 | + self.assertEqual(result, EXCEPTION_RETURN_CODE) |
| 35 | + |
| 36 | + def setUp(self) -> None: |
| 37 | + self.caplog.clear() |
| 38 | + |
| 39 | + def test_log_error_logs_message(self): |
| 40 | + # Test that log_error logs the exception message |
| 41 | + exception = Exception("Test exception") |
| 42 | + with self.caplog.at_level(logging.ERROR): |
| 43 | + log_error(exception) |
| 44 | + |
| 45 | + self.assertIn("Test exception", self.caplog.text) |
| 46 | + self.assertNotIn("Traceback", self.caplog.text) |
| 47 | + |
| 48 | + def test_log_error_includes_stack_trace_in_debug_mode(self): |
| 49 | + # raises an exception to get an Exception object with a strace trace |
| 50 | + try: |
| 51 | + raise Exception("Test exception") |
| 52 | + except Exception as exception: |
| 53 | + with self.caplog.at_level(logging.DEBUG): |
| 54 | + log_error(exception) |
| 55 | + |
| 56 | + self.assertIn("Test exception", self.caplog.text) |
| 57 | + self.assertIn("Traceback", self.caplog.text) |
0 commit comments