Skip to content

Commit e01abb9

Browse files
committed
Added type checking to rich_text_to_string().
1 parent a94cc75 commit e01abb9

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

cmd2/rich_utils.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,13 @@ def rich_text_to_string(text: Text) -> str:
426426
427427
:param text: the text object to convert
428428
:return: the resulting string with ANSI styles preserved.
429+
:raises TypeError: if text is not a rich.text.Text object
429430
"""
431+
# Strictly enforce Text type. While console.print() can render any object,
432+
# this function is specifically tailored to convert Text instances to strings.
433+
if not isinstance(text, Text):
434+
raise TypeError(f"rich_text_to_string() expected a rich.text.Text object, but got {type(text).__name__}")
435+
430436
console = Console(
431437
force_terminal=True,
432438
soft_wrap=True,

tests/test_rich_utils.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,12 @@ def test_rich_text_to_string(rich_text: Text, string: str) -> None:
8181
assert ru.rich_text_to_string(rich_text) == string
8282

8383

84+
def test_rich_text_to_string_type_error() -> None:
85+
with pytest.raises(TypeError) as excinfo:
86+
ru.rich_text_to_string("not a Text object") # type: ignore[arg-type]
87+
assert "rich_text_to_string() expected a rich.text.Text object, but got str" in str(excinfo.value)
88+
89+
8490
def test_set_theme() -> None:
8591
# Save a cmd2, rich-argparse, and rich-specific style.
8692
cmd2_style_key = Cmd2Style.ERROR

0 commit comments

Comments
 (0)