diff --git a/telebot/formatting.py b/telebot/formatting.py index 871c293b4..73f737fd4 100644 --- a/telebot/formatting.py +++ b/telebot/formatting.py @@ -312,7 +312,7 @@ def hpre(content: str, escape: Optional[bool]=True, language: str="") -> str: :return: The formatted string. :rtype: :obj:`str` """ - return '
{}
'.format(language, escape_html(content) if escape else content) + return '
{}
'.format(escape_html(language), escape_html(content) if escape else content) def hide_link(url: str) -> str: diff --git a/tests/test_formatting.py b/tests/test_formatting.py new file mode 100644 index 000000000..eb0eabdfb --- /dev/null +++ b/tests/test_formatting.py @@ -0,0 +1,37 @@ +import sys + +sys.path.append('../') + +from html.parser import HTMLParser + +from telebot.formatting import hpre + + +class AttributeCollector(HTMLParser): + def __init__(self): + super().__init__() + self.tags = [] + + def handle_starttag(self, tag, attrs): + self.tags.append((tag, attrs)) + + +def test_hpre_keeps_plain_language(): + assert hpre("x", language="python") == '
x
' + + +def test_hpre_escapes_quotes_in_language(): + assert hpre("x", language='a"b') == '
x
' + + +def test_hpre_language_cannot_add_attributes(): + parser = AttributeCollector() + parser.feed(hpre("x", language='a" onmouseover="alert(1)')) + assert parser.tags == [ + ("pre", []), + ("code", [("class", 'a" onmouseover="alert(1)')]), + ] + + +def test_hpre_still_escapes_content(): + assert hpre("", language="python") == '
<b>
'