Skip to content

Commit d2c9733

Browse files
committed
Added type checks to ansi.style()
1 parent 0d60017 commit d2c9733

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

cmd2/ansi.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -970,6 +970,8 @@ def style(
970970
:param overline: apply the overline style if True. Defaults to False.
971971
:param strikethrough: apply the strikethrough style if True. Defaults to False.
972972
:param underline: apply the underline style if True. Defaults to False.
973+
:raises: TypeError if fg isn't None or a subclass of FgColor
974+
:raises: TypeError if bg isn't None or a subclass of BgColor
973975
:return: the stylized string
974976
"""
975977
# List of strings that add style
@@ -980,10 +982,14 @@ def style(
980982

981983
# Process the style settings
982984
if fg is not None:
985+
if not isinstance(fg, FgColor):
986+
raise TypeError("fg must be a subclass of FgColor")
983987
additions.append(fg)
984988
removals.append(Fg.RESET)
985989

986990
if bg is not None:
991+
if not isinstance(bg, BgColor):
992+
raise TypeError("bg must a subclass of BgColor")
987993
additions.append(bg)
988994
removals.append(Bg.RESET)
989995

tests/test_ansi.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,17 @@ def test_style_bg(bg_color):
5858
assert ansi.style(base_str, bg=bg_color) == ansi_str
5959

6060

61+
# noinspection PyTypeChecker
62+
def test_style_invalid_types():
63+
# Use a BgColor with fg
64+
with pytest.raises(TypeError):
65+
ansi.style('test', fg=ansi.Bg.BLUE)
66+
67+
# Use a FgColor with bg
68+
with pytest.raises(TypeError):
69+
ansi.style('test', bg=ansi.Fg.BLUE)
70+
71+
6172
def test_style_bold():
6273
base_str = HELLO_WORLD
6374
ansi_str = ansi.TextStyle.INTENSITY_BOLD + base_str + ansi.TextStyle.INTENSITY_NORMAL
@@ -236,7 +247,6 @@ def test_sequence_str_building(ansi_sequence):
236247
],
237248
)
238249
def test_rgb_bounds(r, g, b, valid):
239-
240250
if valid:
241251
ansi.RgbFg(r, g, b)
242252
ansi.RgbBg(r, g, b)

0 commit comments

Comments
 (0)