From f38458fe56bf8850da72a924bd2e8ff59c6adf06 Mon Sep 17 00:00:00 2001 From: Pratyush Mittal Date: Thu, 28 Oct 2021 23:45:01 +0530 Subject: [PATCH] Fixed #33236 -- Fixed assertHTMLEqual() error messages for escaped HTML. --- django/test/html.py | 12 +++++++++--- tests/test_utils/tests.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/django/test/html.py b/django/test/html.py index f1cbadfc54..07e986439b 100644 --- a/django/test/html.py +++ b/django/test/html.py @@ -1,5 +1,5 @@ """Compare two HTML documents.""" - +import html from html.parser import HTMLParser from django.utils.regex_helper import _lazy_re_compile @@ -150,7 +150,10 @@ class Element: output += ' %s' % key if self.children: output += '>\n' - output += ''.join(str(c) for c in self.children) + output += ''.join([ + html.escape(c) if isinstance(c, str) else str(c) + for c in self.children + ]) output += '\n' % self.name else: output += '>' @@ -165,7 +168,10 @@ class RootElement(Element): super().__init__(None, ()) def __str__(self): - return ''.join(str(c) for c in self.children) + return ''.join([ + html.escape(c) if isinstance(c, str) else str(c) + for c in self.children + ]) class HTMLParseError(Exception): diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py index ce328cd90a..9c003e5a6f 100644 --- a/tests/test_utils/tests.py +++ b/tests/test_utils/tests.py @@ -868,6 +868,11 @@ class HTMLEqualTests(SimpleTestCase): dom2 = parse_html('') self.assertEqual(dom2.count(dom1), 2) + def test_root_element_escaped_html(self): + html = '<br>' + parsed = parse_html(html) + self.assertEqual(str(parsed), html) + def test_parsing_errors(self): with self.assertRaises(AssertionError): self.assertHTMLEqual('

', '') @@ -882,6 +887,17 @@ class HTMLEqualTests(SimpleTestCase): with self.assertRaises(HTMLParseError): parse_html('

') + def test_escaped_html_errors(self): + msg = ( + '

\n\n

' + ' != ' + '

\n<foo>\n

\n' + ) + with self.assertRaisesMessage(AssertionError, msg): + self.assertHTMLEqual('

', '

<foo>

') + with self.assertRaisesMessage(AssertionError, msg): + self.assertHTMLEqual('

', '

<foo>

') + def test_contains_html(self): response = HttpResponse(''' This is a form: