From ac116d5a5f4d7e041738e3daaff67d14e6d978e0 Mon Sep 17 00:00:00 2001 From: tligui_y Date: Thu, 31 Jul 2025 15:57:46 +0200 Subject: [PATCH] Add tests/test_utils_exceptions.py --- tests/test_utils_exceptions.py | 83 ++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 tests/test_utils_exceptions.py diff --git a/tests/test_utils_exceptions.py b/tests/test_utils_exceptions.py new file mode 100644 index 000000000..320442a06 --- /dev/null +++ b/tests/test_utils_exceptions.py @@ -0,0 +1,83 @@ +import sys +import os +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) +from slic.utils.exceptions import * + +# Custom ChainedException +class MyChainedError(ChainedException): + def __init__(self): + super().__init__("High-level task failed") + +# Functions that each raise a different low-level error +def cause_key_error(): + return {}["missing"] + +def cause_index_error(): + return [][1] + +def cause_zero_division(): + return 1 / 0 + +def cause_value_error(): + int("not_a_number") + +def cause_type_error(): + return "hello" + 5 + +# Test ChainedException and indirecty printable_exception +@pytest.mark.parametrize("func, expected_output", [ + ( + cause_key_error, + "High-level task failed\ncaused by KeyError: 'missing'" + ), + ( + cause_index_error, + "High-level task failed\ncaused by IndexError: list index out of range" + ), + ( + cause_zero_division, + "High-level task failed\ncaused by ZeroDivisionError: division by zero" + ), + ( + cause_value_error, + "High-level task failed\ncaused by ValueError: invalid literal for int() with base 10: 'not_a_number'" + ), + ( + cause_type_error, + "High-level task failed\ncaused by TypeError: can only concatenate str (not \"int\") to str" + ), +]) +def test_chained_exception_various(func, expected_output): + try: + try: + func() + except Exception as e: + raise MyChainedError() from e + except MyChainedError as exc: + assert str(exc) == expected_output + +# Test printed exception +@pytest.mark.parametrize( + "func, expected_output", + [ + (cause_key_error, "KeyError: 'missing'"), + (cause_index_error, "IndexError: list index out of range"), + (cause_zero_division,"ZeroDivisionError: division by zero"), + (cause_value_error, "ValueError: invalid literal for int() with base 10: 'not_a_number'"), + (cause_type_error, 'TypeError: can only concatenate str (not "int") to str'), + ], +) + +def test_printed_exception(func, expected_output, capfd): + + with printed_exception(): + func() + print("Code continuing...") + + out, err = capfd.readouterr() + + # Check if the error is printed in stdout + assert expected_output in out + + # Check if the code didn't exit 1 + assert "Code continuing..." in out