This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user