From 70f39e46f86b946c273340d52109824c776ffb4c Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 6 Feb 2024 20:52:52 +0100 Subject: [PATCH] Refs #30686 -- Fixed text truncation for negative or zero lengths. --- django/utils/text.py | 4 ++++ .../template_tests/filter_tests/test_truncatechars_html.py | 2 +- tests/utils_tests/test_text.py | 6 +++++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/django/utils/text.py b/django/utils/text.py index 295f919b51..374fd78f92 100644 --- a/django/utils/text.py +++ b/django/utils/text.py @@ -104,6 +104,8 @@ class Truncator(SimpleLazyObject): """ self._setup() length = int(num) + if length <= 0: + return "" text = unicodedata.normalize("NFC", self._wrapped) # Calculate the length to truncate to (max length - end_text length) @@ -144,6 +146,8 @@ class Truncator(SimpleLazyObject): """ self._setup() length = int(num) + if length <= 0: + return "" if html: return self._truncate_html(length, truncate, self._wrapped, length, True) return self._text_words(length, truncate) diff --git a/tests/template_tests/filter_tests/test_truncatechars_html.py b/tests/template_tests/filter_tests/test_truncatechars_html.py index 6c5fc3c883..881290d47d 100644 --- a/tests/template_tests/filter_tests/test_truncatechars_html.py +++ b/tests/template_tests/filter_tests/test_truncatechars_html.py @@ -8,7 +8,7 @@ class FunctionTests(SimpleTestCase): truncatechars_html( '

one two - three
four
five

', 0 ), - "…", + "", ) def test_truncate(self): diff --git a/tests/utils_tests/test_text.py b/tests/utils_tests/test_text.py index a7f25c7936..6004712bf2 100644 --- a/tests/utils_tests/test_text.py +++ b/tests/utils_tests/test_text.py @@ -89,7 +89,7 @@ class TestUtilsText(SimpleTestCase): # Make a best effort to shorten to the desired length, but requesting # a length shorter than the ellipsis shouldn't break - self.assertEqual("…", text.Truncator("asdf").chars(0)) + self.assertEqual("...", text.Truncator("asdf").chars(1, truncate="...")) # lazy strings are handled correctly self.assertEqual( text.Truncator(lazystr("The quick brown fox")).chars(10), "The quick…" @@ -123,6 +123,8 @@ class TestUtilsText(SimpleTestCase): "…", truncator.chars(1, html=True), ) + self.assertEqual("", truncator.chars(0, html=True)) + self.assertEqual("", truncator.chars(-1, html=True)) self.assertEqual( '

The qu....

', truncator.chars(10, "....", html=True), @@ -206,6 +208,8 @@ class TestUtilsText(SimpleTestCase): lazystr("The quick brown fox jumped over the lazy dog.") ) self.assertEqual("The quick brown fox…", truncator.words(4)) + self.assertEqual("", truncator.words(0)) + self.assertEqual("", truncator.words(-1)) def test_truncate_html_words(self): truncator = text.Truncator(