From aa3d39fcd4b7a1fb210897301f14cfd446f6c0c2 Mon Sep 17 00:00:00 2001 From: "(GalaxyMaster)" Date: Wed, 8 Sep 2021 23:43:44 +1000 Subject: [PATCH] Added missing tests for the custom end marker for truncate_html_words() Added support for Jinja2 generated end marker when the passed variable is an instance of Markup. This makes the function compatible with Jinja2's environments where autoescape is enabled. --- pelican/tests/test_utils.py | 28 ++++++++++++++++++++++++++++ pelican/utils.py | 3 +++ 2 files changed, 31 insertions(+) diff --git a/pelican/tests/test_utils.py b/pelican/tests/test_utils.py index 5fbd066d..bca783cb 100644 --- a/pelican/tests/test_utils.py +++ b/pelican/tests/test_utils.py @@ -8,6 +8,8 @@ from tempfile import mkdtemp import pytz +from markupsafe import Markup + from pelican import utils from pelican.generators import TemplatePagesGenerator from pelican.readers import Readers @@ -233,6 +235,32 @@ class TestUtils(LoggedTestCase): utils.truncate_html_words('' + 'word ' * 100, 20), '' + 'word ' * 20 + '…') + # Words enclosed or intervaled by HTML tags with a custom end + # marker containing HTML tags. + self.assertEqual( + utils.truncate_html_words('

' + 'word ' * 100 + '

', 20, + 'marker'), + '

' + 'word ' * 20 + 'marker

') + self.assertEqual( + utils.truncate_html_words( + '' + 'word ' * 100 + '', 20, + 'marker'), + '' + 'word ' * 20 + 'marker') + self.assertEqual( + utils.truncate_html_words('
' + 'word ' * 100, 20, + 'marker'), + '
' + 'word ' * 20 + 'marker') + self.assertEqual( + utils.truncate_html_words('' + 'word ' * 100, 20, + 'marker'), + '' + 'word ' * 20 + 'marker') + + # Words with HTML tags and a Jinja2 generated end marker (Markup) + self.assertEqual( + utils.truncate_html_words('

' + 'word ' * 100 + '

', 20, + Markup('marker')), + '

' + 'word ' * 20 + 'marker

') + # Words with hypens and apostrophes. self.assertEqual( utils.truncate_html_words("a-b " * 100, 20), diff --git a/pelican/utils.py b/pelican/utils.py index b69cbf95..a3f9a9e1 100644 --- a/pelican/utils.py +++ b/pelican/utils.py @@ -580,6 +580,9 @@ def truncate_html_words(s, num, end_text='…'): return s out = s[:truncator.truncate_at] if end_text: + # check if the passed terminator was Jinja2 generated (i.e. Markup) + if isinstance(end_text, Markup): + end_text = end_text.unescape() out += ' ' + end_text # Close any tags still open for tag in truncator.open_tags: