summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--cmd2/utils.py4
-rw-r--r--tests/test_utils.py39
2 files changed, 40 insertions, 3 deletions
diff --git a/cmd2/utils.py b/cmd2/utils.py
index cb8922f6..32781e28 100644
--- a/cmd2/utils.py
+++ b/cmd2/utils.py
@@ -667,7 +667,7 @@ def align_text(text: str, alignment: TextAlignment, *, fill_char: str = ' ',
if width is None:
width = shutil.get_terminal_size().columns
- if width <= 1:
+ if width < 1:
raise ValueError("width must be at least 1")
# Handle tabs
@@ -822,7 +822,7 @@ def truncate_string(text: str, max_width: int, *, tab_width: int = 4) -> str:
if ansi.style_aware_wcswidth(text) == -1:
raise (ValueError("text contains an unprintable character"))
- if max_width <= 1:
+ if max_width < 1:
raise ValueError("max_width must be at least 1")
if ansi.style_aware_wcswidth(text) > max_width:
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 9b2279ae..08b282b7 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -293,6 +293,36 @@ def test_context_flag_exit_err(context_flag):
context_flag.__exit__()
+def test_truncate_string():
+ text = 'long'
+ max_width = 3
+ truncated = cu.truncate_string(text, max_width)
+ assert truncated == 'lo\N{HORIZONTAL ELLIPSIS}'
+
+def test_truncate_string_newline_in_text():
+ text = 'fo\no'
+ max_width = 2
+ with pytest.raises(ValueError):
+ cu.truncate_string(text, max_width)
+
+def test_truncate_string_width_is_too_small():
+ text = 'foo'
+ max_width = 0
+ with pytest.raises(ValueError):
+ cu.truncate_string(text, max_width)
+
+def test_truncate_string_wide_text():
+ text = '苹苹other'
+ max_width = 6
+ truncated = cu.truncate_string(text, max_width)
+ assert truncated == '苹苹o\N{HORIZONTAL ELLIPSIS}'
+
+def test_truncate_string_tabs():
+ text = 'has\ttab'
+ max_width = 9
+ truncated = cu.truncate_string(text, max_width)
+ assert truncated == 'has t\N{HORIZONTAL ELLIPSIS}'
+
def test_align_text_fill_char_is_tab():
text = 'foo'
fill_char = '\t'
@@ -300,6 +330,13 @@ def test_align_text_fill_char_is_tab():
aligned = cu.align_text(text, cu.TextAlignment.LEFT, fill_char=fill_char, width=width)
assert aligned == text + ' '
+def test_align_text_width_is_too_small():
+ text = 'foo'
+ fill_char = '-'
+ width = 0
+ with pytest.raises(ValueError):
+ cu.align_text(text, cu.TextAlignment.LEFT, fill_char=fill_char, width=width)
+
def test_align_text_fill_char_is_too_long():
text = 'foo'
fill_char = 'fill'
@@ -340,7 +377,7 @@ def test_align_text_wider_than_width_truncate():
fill_char = '-'
width = 8
aligned = cu.align_text(text, cu.TextAlignment.LEFT, fill_char=fill_char, width=width, truncate=True)
- assert aligned == 'long te' + "\N{HORIZONTAL ELLIPSIS}"
+ assert aligned == 'long te\N{HORIZONTAL ELLIPSIS}'
def test_align_text_has_unprintable():
text = 'foo\x02'