Files
slic/tests/test_utils_exceptions.py
T
tligui_y fd268195cb
Run CI Tests / test (push) Successful in 57s
Update tests/test_utils_exceptions.py
2025-07-31 16:09:13 +02:00

85 lines
2.3 KiB
Python

import pytest
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