Skip to content

Commit 13ddf69

Browse files
committed
Updated stylize() unit test.
1 parent fca3b95 commit 13ddf69

File tree

2 files changed

+13
-14
lines changed

2 files changed

+13
-14
lines changed

cmd2/string_utils.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,22 +82,23 @@ def align_right(
8282

8383

8484
def stylize(val: str, style: StyleType) -> str:
85-
"""Apply ANSI style to a string.
85+
"""Apply an ANSI style to a string, preserving any existing styles.
8686
8787
:param val: string to be styled
8888
:param style: style instance or style definition to apply.
8989
:return: the stylized string
9090
"""
91+
# Convert to a Rich Text object to parse and preserve existing ANSI styles.
9192
text = ru.string_to_rich_text(val)
9293
text.stylize(style)
9394
return ru.rich_text_to_string(text)
9495

9596

9697
def strip_style(val: str) -> str:
97-
"""Strip ANSI style sequences from a string.
98+
"""Strip all ANSI styles from a string.
9899
99-
:param val: string which may contain ANSI style sequences
100-
:return: the same string with any ANSI style sequences removed
100+
:param val: string to be stripped
101+
:return: the stripped string
101102
"""
102103
text = ru.string_to_rich_text(val)
103104
return text.plain

tests/test_string_utils.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -115,18 +115,16 @@ def test_align_right_with_style() -> None:
115115

116116

117117
def test_stylize() -> None:
118-
styled_str = su.stylize(
119-
HELLO_WORLD,
120-
style=Style(
121-
color=Color.GREEN,
122-
bgcolor=Color.BLUE,
123-
bold=True,
124-
underline=True,
125-
),
126-
)
127-
118+
# Test string with no existing style
119+
style = Style(color=Color.GREEN, bgcolor=Color.BLUE, bold=True, underline=True)
120+
styled_str = su.stylize(HELLO_WORLD, style=style)
128121
assert styled_str == "\x1b[1;4;32;44mHello, world!\x1b[0m"
129122

123+
# Add style to already-styled string
124+
updated_style = Style.combine([style, Style(strike=True)])
125+
restyled_string = su.stylize(styled_str, style=updated_style)
126+
assert restyled_string == "\x1b[1;4;9;32;44mHello, world!\x1b[0m"
127+
130128

131129
def test_strip_style() -> None:
132130
base_str = HELLO_WORLD

0 commit comments

Comments
 (0)