Skip to content

Commit

Permalink
Added type checks to ansi.style()
Browse files Browse the repository at this point in the history
  • Loading branch information
kmvanbrunt committed Oct 27, 2021
1 parent 0d60017 commit d2c9733
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
6 changes: 6 additions & 0 deletions cmd2/ansi.py
Original file line number Diff line number Diff line change
Expand Up @@ -970,6 +970,8 @@ def style(
:param overline: apply the overline style if True. Defaults to False.
:param strikethrough: apply the strikethrough style if True. Defaults to False.
:param underline: apply the underline style if True. Defaults to False.
:raises: TypeError if fg isn't None or a subclass of FgColor
:raises: TypeError if bg isn't None or a subclass of BgColor
:return: the stylized string
"""
# List of strings that add style
Expand All @@ -980,10 +982,14 @@ def style(

# Process the style settings
if fg is not None:
if not isinstance(fg, FgColor):
raise TypeError("fg must be a subclass of FgColor")
additions.append(fg)
removals.append(Fg.RESET)

if bg is not None:
if not isinstance(bg, BgColor):
raise TypeError("bg must a subclass of BgColor")
additions.append(bg)
removals.append(Bg.RESET)

Expand Down
12 changes: 11 additions & 1 deletion tests/test_ansi.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ def test_style_bg(bg_color):
assert ansi.style(base_str, bg=bg_color) == ansi_str


# noinspection PyTypeChecker
def test_style_invalid_types():
# Use a BgColor with fg
with pytest.raises(TypeError):
ansi.style('test', fg=ansi.Bg.BLUE)

# Use a FgColor with bg
with pytest.raises(TypeError):
ansi.style('test', bg=ansi.Fg.BLUE)


def test_style_bold():
base_str = HELLO_WORLD
ansi_str = ansi.TextStyle.INTENSITY_BOLD + base_str + ansi.TextStyle.INTENSITY_NORMAL
Expand Down Expand Up @@ -236,7 +247,6 @@ def test_sequence_str_building(ansi_sequence):
],
)
def test_rgb_bounds(r, g, b, valid):

if valid:
ansi.RgbFg(r, g, b)
ansi.RgbBg(r, g, b)
Expand Down

0 comments on commit d2c9733

Please sign in to comment.