From 2cbaed320d9abea9a7db5339898843f64a0d4271 Mon Sep 17 00:00:00 2001 From: Bernhard Kaindl Date: Fri, 22 Mar 2024 12:00:00 +0100 Subject: [PATCH] CA-390129: Add test for the exception handler xen-bugtool.log_exceptions() Signed-off-by: Bernhard Kaindl --- .pre-commit-config.yaml | 5 +++++ tests/unit/test_dump_xapi_rrds.py | 34 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index cda5dc7..51110d1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -119,6 +119,11 @@ repos: files: '(^xen-bugtool|\.py)$' +# If you are working on a PR and the branch shall not be up-to-date with the base +# branch, export SKIP=check-branch-needs-rebase or use these commands to skip the check: +# SKIP=check-branch-needs-rebase time pre-commit run --hook-stage push --all-files -v +# SKIP=check-branch-needs-rebase git commit -s -m "your message" +# or to skip all checks because you ran them before: git push --no-verify - repo: local hooks: - id: check-branch-needs-rebase diff --git a/tests/unit/test_dump_xapi_rrds.py b/tests/unit/test_dump_xapi_rrds.py index 2fe0e46..0d2ad69 100644 --- a/tests/unit/test_dump_xapi_rrds.py +++ b/tests/unit/test_dump_xapi_rrds.py @@ -158,3 +158,37 @@ def test_dump_xapi_rrds_master(mocker, isolated_bugtool, mock_session1, mock_url run_dump_xapi_rrds(mocker, isolated_bugtool, mock_session1, mock_urlopen) assert_mock_session1(isolated_bugtool, mock_urlopen) + + +def test_log_exceptions(isolated_bugtool, capsys): + """Test log_exceptions() to log the exception message and return the exception type.""" + + try: + with isolated_bugtool.log_exceptions(): + raise IOError("message") + except BaseException: # pragma: no cover # NOSONAR + assert False, "log_exceptions() is expected to catch all Exceptions" + finally: + with capsys.disabled(): + # Assert that the exception message is logged to stdout + assert_log_contents(capsys.readouterr().out.splitlines()) + + # Assert that the exception message is logged to the log file + with open(isolated_bugtool.XEN_BUGTOOL_LOG, "r") as f: + log = f.read().splitlines() + assert_log_contents(log) + + # Clear the log file to indicate that we checked the log file contents + with open(isolated_bugtool.XEN_BUGTOOL_LOG, "w") as f: + f.write("") + + +def assert_log_contents(log): + """Assert the contents of the log""" + + # Check the log file contents + assert log[0] == "message, Traceback (most recent call last):" + assert ", in log_exceptions" in log[1] + assert log[2] == " yield" + assert ", in test_log_exceptions" in log[3] + assert log[4] == ' raise IOError("message")'