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.
This commit is contained in:
(GalaxyMaster) 2021-09-08 23:43:44 +10:00
commit aa3d39fcd4
2 changed files with 31 additions and 0 deletions

View file

@ -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('<!-- comment -->' + 'word ' * 100, 20),
'<!-- comment -->' + 'word ' * 20 + '')
# Words enclosed or intervaled by HTML tags with a custom end
# marker containing HTML tags.
self.assertEqual(
utils.truncate_html_words('<p>' + 'word ' * 100 + '</p>', 20,
'<span>marker</span>'),
'<p>' + 'word ' * 20 + '<span>marker</span></p>')
self.assertEqual(
utils.truncate_html_words(
'<span\nstyle="\n\n">' + 'word ' * 100 + '</span>', 20,
'<span>marker</span>'),
'<span\nstyle="\n\n">' + 'word ' * 20 + '<span>marker</span></span>')
self.assertEqual(
utils.truncate_html_words('<br>' + 'word ' * 100, 20,
'<span>marker</span>'),
'<br>' + 'word ' * 20 + '<span>marker</span>')
self.assertEqual(
utils.truncate_html_words('<!-- comment -->' + 'word ' * 100, 20,
'<span>marker</span>'),
'<!-- comment -->' + 'word ' * 20 + '<span>marker</span>')
# Words with HTML tags and a Jinja2 generated end marker (Markup)
self.assertEqual(
utils.truncate_html_words('<p>' + 'word ' * 100 + '</p>', 20,
Markup('<span>marker</span>')),
'<p>' + 'word ' * 20 + '<span>marker</span></p>')
# Words with hypens and apostrophes.
self.assertEqual(
utils.truncate_html_words("a-b " * 100, 20),

View file

@ -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: