# BSD 2-Clause License
#
# Apprise - Push Notification Library.
# Copyright (c) 2026, Chris Caron
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from inspect import cleandoc
# Disable logging for a cleaner testing output
import logging
from timeit import default_timer
import pytest
from apprise import NotifyFormat
from apprise.conversion import (
BLOCKQUOTE_DEPTH_MAX,
LIST_DEPTH_MAX,
MAX_FRAME_DEPTH,
HTMLMarkdownConverter,
build_backtick_run_index,
convert_between,
find_unescaped_run,
)
logging.disable(logging.CRITICAL)
def test_conversion_html_to_text():
"""conversion: Test HTML to plain text"""
def to_html(body):
"""A function to simply html conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.TEXT, body)
assert to_html("No HTML code here.") == "No HTML code here."
clist = to_html("")
assert "Lots and lots" in clist
assert "of lists." in clist
assert "To be or not to be." in to_html(
"To be or not to be.
"
)
cspace = to_html(
"Fancy heading
And a paragraph too.
Plus line break.
"
)
assert "Fancy heading" in cspace
assert "And a paragraph too.\nPlus line break." in cspace
assert (
to_html(
""
"Some obnoxious text here.
"
)
== "Some obnoxious text here."
)
assert (
to_html("line 1
line 2
line 3
")
== "line 1\nline 2\nline 3"
)
# Case sensitivity
assert (
to_html("line 1
line 2
line 3
")
== "line 1\nline 2\nline 3"
)
# double new lines (testing
and )
assert (
to_html("some information
and more information")
== "some information\n\nand more information"
)
#
# Test bad tags
#
# first 2 entries are okay, but last will do as best as it can
assert (
to_html("line 1>
line 2
line 3>")
== "line 1\nline 2\nline 3>"
)
# Make sure we ignore fields that aren't important to us
assert (
to_html(
""
"
line 1
"
"Another line without being enclosed"
)
== "line 1\nAnother line without being enclosed"
)
# Test cases when there are no new lines (we're dealing with just inline
# entries); an empty entry as well
assert (
to_html("test my link")
== "test my link"
)
#
missing
assert (
to_html(
"
Hi!
How are you?
red font
link you wanted.
""")
== "---\nFROM: apprise-test@mydomain.yyy\n---\nHi!\n How are you?\n"
" red font link you wanted."
)
assert (
to_html("""
TEST
Hi!
How are you?
red font
link you wanted.
""")
== "---\nTEST\n---\nHi!\n How are you?\n red font link you wanted."
)
with pytest.raises(TypeError):
# Invalid input
assert to_html(None)
with pytest.raises(TypeError):
# Invalid input
assert to_html(42)
with pytest.raises(TypeError):
# Invalid input
assert to_html(object)
def test_conversion_html_to_markdown():
"""Test basic HTML-to-Markdown conversion."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Plain text with no HTML passes through unchanged
assert to_md("No HTML code here.") == "No HTML code here."
# Empty string in, empty string out
assert to_md("") == ""
# Paragraphs need a full blank line between them.
assert (
to_md("line 1
line 2
line 3
")
== "line 1\n\nline 2\n\nline 3"
)
# Case sensitivity -- tag names are case-insensitive in HTML
assert (
to_md("line 1
line 2
line 3
")
== "line 1\n\nline 2\n\nline 3"
)
# HTMLParser lowercases ALL tag names -- inline tags included
assert to_md("bold text") == "**bold text**"
assert to_md("italic") == "*italic*"
# Uppercase self-closing
tags also produce CommonMark hard breaks.
assert (
to_md("line one
line two
line three")
== "line one \nline two \nline three"
)
#
and self-closing
both emit a hard break
assert (
to_md("some information
and more information")
== "some information \n \nand more information"
)
# Each heading level maps to the correct number of # characters
assert to_md("Heading 1
") == "# Heading 1"
assert to_md("Heading 2
") == "## Heading 2"
assert to_md("Heading 3
") == "### Heading 3"
assert to_md("Heading 4
") == "#### Heading 4"
assert to_md("Heading 5
") == "##### Heading 5"
assert to_md("Heading 6
") == "###### Heading 6"
# Multiple headings and paragraphs together
assert to_md(
"Heading 1
"
"Heading 2
"
"Heading 3
"
"Heading 4
"
"Heading 5
"
"Heading 6
"
"line 1>"
"
line 2"
"
line 3>"
) == (
"# Heading 1\n## Heading 2\n### Heading 3\n"
"#### Heading 4\n##### Heading 5\n###### Heading 6\n\n"
"line 1\n\n*line 2*\n\nline 3\\>"
)
# and both produce bold markers
assert to_md("bold text") == "**bold text**"
assert to_md("bold text") == "**bold text**"
# and both produce italic markers
assert to_md("italic") == "*italic*"
assert to_md("italic") == "*italic*"
# Angle destinations prevent parentheses in an href from ending links.
assert (
to_md(
"line 1 bold
"
" my link"
"3rd line"
)
== "line 1 **bold**\n\n[my link]()\n\n3rd line"
)
# produces Markdown link syntax
assert (
to_md("test my link")
== "test [my link](<#>)"
)
# with nested inline markup -- the href must survive the child tags
assert to_md("hello world") == (
"[**hello** world]()"
)
assert to_md("label") == (
"[**label**]()"
)
assert (
to_md("italic and plain")
== "[*italic* and plain]()"
)
# Nested -- inner href wins for its own span; outer wraps the rest
assert (
to_md("text link")
== "[text [link]()]()"
)
# with no href attribute -- content rendered as plain text
assert to_md("test no link") == "test no link"
# Bare anchor (no href) -- text passes through unchanged
assert to_md("jump target") == "jump target"
# is inline -- it passes text through without a newline; is
# block-level and paragraph-like, so it adds a blank line.
assert to_md("
block
inline") == "block\n\ninline"
# HTML comments are stripped entirely; surrounding text is preserved
assert to_md(" text") == "text"
assert to_md("abc") == "abc"
# sections are gracefully ignored (content is dropped, text
# outside the CDATA boundary is kept)
assert to_md("text here") == "text here"
assert to_md("text") == "text"
# Inline
wraps in backticks without a block boundary
assert to_md("func()") == "`func()`"
# Markdown special characters inside are NOT escaped -- backtick
# delimiters already make content literal
assert to_md("x*2 and #tag") == "`x*2 and #tag`"
# produces a fenced code block
assert to_md("line a\nline b
") == "```\nline a\nline b\n```"
# is treated the same as (fenced block)
assert to_md("output\nhere") == "```\noutput\nhere\n```"
# Inline code followed immediately by a pre block
assert to_md(
"multi-line 1\nmulti-line 2more content"
"multi-line 1\nmulti-line 2
more content"
) == (
"`multi-line 1\nmulti-line 2`more content"
"\n```\nmulti-line 1\nmulti-line 2\n```\nmore content"
)
# Unordered lists produce "- " prefixed items
result = to_md("")
assert "- Lots and lots" in result
assert "- of lists." in result
assert (
to_md("To be or not to be.
")
== "> To be or not to be."
)
# Standalone
produces just "---"
assert to_md("
") == "---"
assert to_md("
") == "---"
# "
"Some obnoxious text here.
"
)
== "Some obnoxious text here."
)
# "
"line 1
"
"Another line without being enclosed"
)
== "line 1\n\nAnother line without being enclosed"
)
# '*' outside code is escaped so it does not trigger emphasis
assert to_md("price: 5 * 3
") == r"price: 5 \* 3"
# '#' outside code is escaped so it does not trigger a heading
assert to_md("Tag #1
") == r"Tag \#1"
# Backtick outside code is escaped
assert to_md("Use `func`
") == r"Use \`func\`"
assert (
to_md(
"""
ignore this entry
Let's handle special html encoding
"""
)
== "Let's handle special html encoding\n\n---"
)
# Missing is handled gracefully
assert (
to_md(
"Heading
And a paragraph too.
Plus line break.
"
)
== "## Heading\n\nAnd a paragraph too. \nPlus line break."
)
with pytest.raises(TypeError):
to_md(None)
with pytest.raises(TypeError):
to_md(42)
with pytest.raises(TypeError):
to_md(object)
def test_conversion_html_to_markdown_lists():
"""Test list nesting and numbering."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Flat unordered list
assert (
to_md("")
== "- alpha\n- beta\n- gamma"
)
# Flat ordered list with auto-incrementing counter
assert (
to_md("- first
- second
- third
")
== "1. first\n2. second\n3. third"
)
# shifts where the auto-incrementing counter begins
assert to_md('- a
- b
') == "4. a\n5. b"
assert to_md('- a
') == "0. a"
# CommonMark list markers cannot represent negative starting values.
assert to_md('- a
- b
') == "0. a\n1. b"
# A non-numeric start is ignored, same as no attribute at all
assert to_md('- a
') == "1. a"
# - resets the counter for that item and every sibling after it
assert to_md('
- a
- b
') == "5. a\n6. b"
assert (
to_md('- a
- b
- c
')
== "1. a\n10. b\n11. c"
)
assert to_md('- a
- b
') == "0. a\n1. b"
# A non-numeric value is ignored too -- the counter just keeps incrementing
# normally, same as if the attribute weren't there
assert to_md('- a
- b
') == "1. a\n2. b"
# Nested unordered lists (2 levels)
assert (
to_md(
""
)
== "- top A\n - nested A\n- top B"
)
# Nested unordered lists (3 levels)
assert (
to_md("")
== "- L1\n - L2\n - L3"
)
# Mixed nesting: ol inside ul
assert (
to_md(
""
"- intro
"
"- step one
"
"- step two
"
"
"
"
"
)
== "- intro\n 1. step one\n 2. step two"
)
# Mixed nesting: ul inside ol
assert (
to_md(
""
"- first
"
"- second
"
"
"
)
== "1. first\n - sub A\n - sub B\n2. second"
)
# Malformed HTML: missing in a HTMLParser does not synthesize
# implicit close events; each missing is simply absent, but the next.
assert (
to_md("")
== "- item A\n- item B\n- item C"
)
# Without , ordered-list counters cannot advance.
assert (
to_md("- one
- two
- three
") == "1. one\n1. two\n1. three"
)
# Malformed HTML: missing closing
assert to_md("- item A
- item B
") == "- item A\n- item B"
# Malformed HTML: missing AND missing
assert to_md("- item A
- item B") == "- item A\n- item B"
# Malformed HTML: bare text inside
text") == "text"
assert to_md("text") == "text"
# Markdown/HTML injection via plain text content
assert (
to_md("Click [here](https://evil.example.com) now
")
== r"Click \[here\]\(https://evil.example.com\) now"
)
assert (
to_md("An image  too
")
== r"An image \!\[x\]\(https://evil.example.com/x.png\) too"
)
# A literal backslash must itself be escaped
assert to_md("back\\*slash
") == r"back\\\*slash"
# '_' (CommonMark's other emphasis delimiter) and '~' (GFM/chat- dialect
# strikethrough) are escaped unconditionally, the same as '*'.
assert to_md("_literal_
") == r"\_literal\_"
assert to_md("my_variable_name
") == r"my\_variable\_name"
assert to_md("~strikethrough~
") == r"\~strikethrough\~"
# Entity-encoded HTML (decoded to literal "<"/">" text by the parser) must
# not survive into the Markdown output unescaped
assert (
to_md("previously <script>alert(1)</script>
")
== r"previously \"
)
# href cannot break out of the link destination
assert to_md(
''
"legit link"
) == (
"[legit link]"
"()"
)
# A '<' or '>' inside the href itself must be escaped, since both are
# meaningful within the angle-bracket destination form.
assert to_md('y') == (
r"[y](>)"
)
# Strip line endings before placing a URL in an angle-bracket destination.
assert (
to_md('click')
== "[click]()"
)
# Neutralize schemes that can execute content or expose local files.
assert to_md('click me') == (
"[click me](<#>)"
)
assert to_md('click') == "[click](<#>)"
assert to_md('click') == "[click](<#>)"
assert to_md('click') == "[click](<#>)"
assert to_md('click') == "[click](<#>)"
# Leading/trailing whitespace must not defeat scheme detection\
assert to_md('click') == (
"[click](<#>)"
)
assert to_md('click') == (
"[click](<#>)"
)
assert to_md('click') == (
"[click](<#>)"
)
# BiDi override/embedding characters must not defeat scheme detection.
assert to_md('click') == ("[click](<#>)")
assert to_md('click') == ("[click](<#>)")
# U+2066 (LEFT-TO-RIGHT ISOLATE) must also be stripped.
assert to_md('click') == ("[click](<#>)")
# Keep legitimate app-specific schemes that are not explicitly unsafe.
assert to_md('x') == (
"[x]()"
)
assert to_md('x') == (
"[x]()"
)
assert to_md('x') == (
"[x]()"
)
assert to_md('x') == (
"[x]()"
)
assert to_md('x') == (
"[x]()"
)
assert to_md('x') == (
"[x]()"
)
assert to_md('x') == (
"[x]()"
)
assert to_md('x') == ("[x]()")
assert to_md('x') == "[x](<#anchor>)"
def test_conversion_html_to_markdown_line_start_escaping():
"""Test block syntax escaping."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Escape ordered-list-shaped text only at the start of a line.
assert to_md("1. Apples
2. Oranges
") == (
"1\\. Apples\n\n2\\. Oranges"
)
assert to_md("23. done
") == "23\\. done"
# Match bullet markers at the start of a line.
assert to_md("- not a bullet, just a dash
") == (
"\\- not a bullet, just a dash"
)
assert to_md("+ plus sign list?
") == "\\+ plus sign list?"
# Escape repeated dashes that could become a thematic break.
assert to_md("Some text
---
more text
") == (
"Some text\n\n\\---\n\nmore text"
)
# Escaping the first dash is enough to prevent a thematic break.
rendered = convert_between(
NotifyFormat.MARKDOWN,
NotifyFormat.HTML,
to_md("Some text
---
more text
"),
)
assert "
***") == "\\*\\*\\*"
assert to_md("___
") == "\\_\\_\\_"
assert to_md("- - -
") == "\\- - -"
assert to_md("Hello world
===
") == "Hello world \n\\==="
assert to_md("Heading
---
") == "Heading \n\\---"
# None of this is ambiguous -- and so isn't escaped -- anywhere other than
# a true line start
assert to_md("well-known v1.2 it is not - really
") == (
"well-known v1.2 it is not - really"
)
assert to_md("price is $5.00
") == "price is $5.00"
assert to_md("a-b-c
") == "a-b-c"
assert to_md("5 - 3 = 2
") == "5 - 3 = 2"
def test_conversion_html_to_markdown_hardening():
"""Test malformed stack input."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Stray close tags before any matching open tag
# and take the early-return path in handle_endtag
assert to_md("text") == "text"
assert to_md("text") == "text"
# finds no open anywhere on the stack and is a no-op -- the
# text that follows is unindented and stored normally
assert to_md("text") == "text"
# Multiple stray close tags in a row must not crash or corrupt state
assert to_md("preamble") == "preamble"
# A valid list after a stray close must still render correctly
assert to_md("") == "- A\n- B"
# A stray close tag with content on BOTH sides must be a complete no-op,
# not just absorbed because nothing preceded it.
assert to_md("ab") == "ab"
assert to_md("ab") == "ab"
assert to_md("ab") == "ab"
assert to_md("ab") == "ab"
assert to_md("ab") == "ab"
assert to_md("ab") == "ab"
# A stray / | close still falls through cleanly when content follows.
assert to_md(" ab ") == "ab"
# _make_frame() empty-stack guard
conv = HTMLMarkdownConverter()
# Force the stack empty -- this can only happen via direct attribute
# manipulation, never through the public parsing API
conv._stack = []
frame = conv._make_frame("div")
# The fallback defaults must match the root sentinel values
assert frame["tag"] == "div"
assert frame["do_store"] is True
assert frame["preserve_cr"] is False
assert frame["list_type"] is None
assert frame["depth"] == 0
assert frame["counter"] is None
assert frame["list_do_store"] is True
# A stale open-tag count must not corrupt the stack.
conv = HTMLMarkdownConverter()
conv._tag_open_counts["nonexistent"] = 1
conv._pop_to("nonexistent") # must not raise or corrupt state
assert len(conv._stack) == 1 # only the root sentinel remains
# ignore content found in head
assert (
to_md(
""
+ "" * 50
+ "text"
)
== "text"
)
# deep nesting still resolve correctly.
assert (
to_md("" * 50) == "- visible"
)
# List indentation is capped at LIST_DEPTH_MAX ---
assert LIST_DEPTH_MAX == 4
one_per_level = "" * 10
out = to_md(one_per_level)
lines = out.split("\n")
assert len(lines) == 10
# Indent grows for the first LIST_DEPTH_MAX levels...
assert lines[0] == "- x"
assert lines[1] == " - x"
assert lines[2] == " - x"
assert lines[3] == " - x"
# ...then holds steady for every level beyond the cap
for line in lines[4:]:
assert line == " - x"
# Performance: same shape, large enough that the old O(N^2)
n = 20000
deep = "" * n
start = default_timer()
out = to_md(deep)
elapsed = default_timer() - start
assert len(out) < 20 * n
# Generous bound: this must catch a real return to quadratic
# behavior, not just run fast on a quiet dev machine -- shared or
# emulated build infrastructure (e.g. a busy Koji builder) can be
# many times slower.
assert elapsed < 15.0
# Performance: many UNCLOSED - tags nested directly inside one another.
n = 20000
html = "
- x" * n
start = default_timer()
out = to_md(html)
elapsed = default_timer() - start
assert len(out) < 10 * n # output itself is linear, not quadratic
# Generous bound -- see the note on the equivalent check above.
assert elapsed < 30.0
# Performance: many open
tags followed by many closing tags of
# a *different* kind that's never actually open ("").
n = 20000
html = "" * n + "" * n
start = default_timer()
out = to_md(html)
elapsed = default_timer() - start
assert len(out) < 20 * n
# Generous bound: this must catch a real return to quadratic
# behavior, not just run fast on a quiet dev machine -- shared or
# emulated build infrastructure (e.g. a busy Koji builder) can be
# many times slower.
assert elapsed < 15.0
# Blockquote depth is capped at BLOCKQUOTE_DEPTH_MAX
assert BLOCKQUOTE_DEPTH_MAX == 4
# Each level is its own , so every line of real content is followed by a
# blank (but still "> "-prefixed) separator line.
one_per_level = " x " * 10 + " " * 10
out = to_md(one_per_level)
lines = out.split("\n")
assert len(lines) == 19
content_lines = lines[0::2]
separator_lines = lines[1::2]
assert len(content_lines) == 10
assert content_lines[0] == "> x"
assert content_lines[1] == "> > x"
assert content_lines[2] == "> > > x"
assert content_lines[3] == "> > > > x"
for line in content_lines[4:]:
assert line == "> > > > x"
# Each separator matches its preceding content line, minus the "x"
for content, separator in zip(content_lines, separator_lines):
assert separator == content[: -len("x")].rstrip()
n = 20000
deep = "x " * n + " " * n
start = default_timer()
out = to_md(deep)
elapsed = default_timer() - start
assert len(out) < 20 * n
# Generous bound: this must catch a real return to quadratic
# behavior, not just run fast on a quiet dev machine -- shared or
# emulated build infrastructure (e.g. a busy Koji builder) can be
# many times slower.
assert elapsed < 15.0
# When emphasis or anchor tags are nested past MAX_FRAME_DEPTH, _push_frame
# returns False and the opening delimiter must NOT be emitted.
depth = MAX_FRAME_DEPTH + 1
em_open = "" * depth
em_close = "" * depth
out_em = to_md(f"{em_open}text{em_close}")
# The text must appear; no unmatched bare asterisk may leak through.
assert "text" in out_em
assert out_em.replace("*", "").strip() == "text"
# Same guard for -- no unmatched "[" in the output.
a_open = '' * depth
a_close = "" * depth
out_a = to_md(f"{a_open}text{a_close}")
assert "text" in out_a
# Count "[" and "](" -- every "[" must have a matching "](".
assert out_a.count("[") == out_a.count("](")
# At MAX_FRAME_DEPTH the frame is discarded and _push_frame
# returns False.
bq_open = "" * depth
bq_close = " " * depth
out_bq = to_md(f"{bq_open}text{bq_close}")
assert "text" in out_bq
# Every ">" line-prefix must correspond to a real nested blockquote level.
first_line = out_bq.splitlines()[0] if out_bq else ""
gt_count = len(first_line) - len(first_line.lstrip("> "))
assert gt_count <= BLOCKQUOTE_DEPTH_MAX * 2 # ">" + " " per level
# At MAX_FRAME_DEPTH the - frame is discarded and _push_frame returns
# False. No _ListMarker must be appended without a backing frame.
li_open = "
" + "- " * depth
li_close = "
" * depth + " "
out_li = to_md(f"{li_open}text{li_close}")
assert "text" in out_li
def test_conversion_html_to_markdown_blockquotes():
"""Test blockquote conversion."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Single paragraph -- marker and content share the first line
assert to_md("line1 ") == "> line1"
# Multiple paragraphs
assert (
to_md("line1 line2 ")
== "> line1\n>\n> line2"
)
assert (
to_md("a b c ")
== "> a\n>\n> b\n>\n> c"
)
# A heading doesn't need that same blank-line treatment.
assert (
to_md("Titlebody ")
== "> ## Title\n> body"
)
# Inline-only content needs no internal prefixing -- it never hits a
# boundary inside the quote in the first place
assert (
to_md("To be or not to be. ")
== "> To be or not to be."
)
# Nested blockquotes accumulate one "> " per level, not per ancestor's full
# cumulative prefix, which would double-count outer quote levels.
assert (
to_md("nested ")
== "> > nested"
)
assert to_md(
"a b
"
) == ("> > a\n> >\n> > b")
# Bare text follows the same one-prefix-per-level rule.
assert (
to_md("outerinner ")
== "> outer\n>\n> > inner"
)
assert to_md(
"abc "
" "
) == ("> a\n>\n> > b\n> >\n> > > c")
# The same text-then-nested-blockquote transition, once depth is already
# clamped at BLOCKQUOTE_DEPTH_MAX, must not add yet another level.
assert BLOCKQUOTE_DEPTH_MAX == 4
capped = (
"" * 4
+ "xy "
+ (" " * 4)
)
out = to_md(capped)
assert "> > > > x" in out
assert "> > > > > y" not in out
assert "> > > > y" in out
# Content after a blockquote needs a full boundary without the quote
# prefix.
assert (
to_md("line1
after ")
== "> line1\n\nafter"
)
assert (
to_md("before line1 ")
== "before\n\n> line1"
)
# An entirely empty blockquote (no children at all, nested or not) produces
# no output.
assert to_md("") == ""
assert to_md(" ") == ""
# A blockquote entirely inside a suppressed context contributes nothing,
# and does not disturb sibling content outside it
assert (
to_md(
"hidden "
"text"
)
== "text"
)
# A blockquote following bare text still needs its own boundary.
assert to_md("textquoted ") == ("text\n\n> quoted")
assert to_md("text") == "text"
assert to_md("text ") == "text"
def test_conversion_html_to_markdown_emphasis():
"""Test emphasis edge cases."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Leading/trailing whitespace inside the tag must end up outside the
# delimiters.
assert to_md(" text ") == "*text*"
assert to_md(" bold ") == "**bold**"
assert to_md(" multi space ") == "*multi space*"
# Leading-only and trailing-only whitespace
assert to_md(" text") == "*text*"
assert to_md("text ") == "*text*"
# Relocating emphasis whitespace must not disturb surrounding text.
assert (
to_md("Hello bold world ")
== "Hello **bold** world"
)
# Relocate trailing whitespace even when empty tags split the text
# fragments.
assert to_md("text x") == "**text** x"
# Fully empty, or whitespace-only, spans contribute nothing at all -- not
# even an unpaired delimiter
assert to_md("") == ""
assert to_md(" ") == ""
assert to_md("") == ""
# Adjacent tags, one empty -- the empty one's delimiters must not collide
# with the next tag's into an ambiguous run of asterisks
assert to_md("bold") == "**bold**"
assert to_md("x") == "*x*"
# A stray close tag with no matching open is a no-op, the same as other
# malformed- HTML cases elsewhere in this parser.
assert to_md("text") == "text"
assert to_md("ab ") == "ab"
# Mismatched open/close tags ("xy").
assert to_md("xy") == "*xy*"
# A tag left open with no closing tag at all is auto-closed at end of
# document rather than leaving its opening delimiter unpaired
assert to_md("text") == "**text**"
assert to_md("ab") == "*a**b***"
# Normal, well-formed cases are unaffected
assert to_md("bold") == "**bold**"
assert to_md("italic") == "*italic*"
assert to_md("AB") == "**A****B**"
# Empty block content inside emphasis must not leave an opening delimiter.
assert to_md("x") == "x"
assert to_md("ab") == "ab"
# Empty trailing blocks must not hide whitespace from emphasis cleanup.
assert to_md("text") == ("*text\n\n> *")
def test_conversion_html_to_markdown_empty_blocks():
"""Test empty block handling."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Plain, marker-less block tags with nothing inside them already collapse
# to nothing extra -- no separate blank line is added for each one.
assert to_md("text ") == "text"
assert to_md("a b ") == "a\n\nb"
assert (
to_md("a b ") == "a\n\nb"
)
# Empty blocks do not detach a marker from later content.
assert (
to_md("")
== "- text"
)
assert to_md("text ") == "> text"
# Drop markers that never receive content.
assert to_md("") == ""
assert to_md("") == ""
# A sibling marker arriving after the first one's empty block tags replaces
# it rather than gluing onto it.
assert to_md("") == "- real"
# Empty blocks do not duplicate a blockquote prefix.
assert (
to_md("line1 line2 ")
== "> line1\n>\n> line2"
)
# Real text between two empty blocks still resets the suppression, so the
# block tag right after it starts a new line as normal.
assert to_md("textmore ") == "text\n\nmore"
# Plain whitespace between tags never counts as content
assert to_md("a b ") == "a\n\nb"
# A standalone is a deliberate space, not incidental formatting
# whitespace.
assert to_md("a b ") == "a\n\n\xa0\n\nb"
# used inline within real text is unaffected, and still collapses to
# a regular space like any other inline whitespace
assert (
to_md("Let's handle special html encoding")
== "Let's handle special html encoding"
)
# is a void element (its closing tag may never fire), but it still
# writes real, non-marker content ("---").
assert to_md("
") == "---\n\n---"
assert to_md(" ") == "---\n\n---"
assert to_md("
") == "---\n\n---\n\n---"
assert to_md("a
b ") == "a\n\n---\n\n---\n\nb"
# as the first thing in a blockquote/list item glues onto the marker;
# inside an open blockquote, its own opening boundary still applies.
assert to_md("") == "- ---"
assert to_md("a
") == "> a\n>\n> ---"
# Real page text that happens to *look* like a generated marker (e.g.
assert to_md("- real ") == "\\-\n\nreal"
assert to_md("- ") == "\\-"
assert (
to_md("- real div content ")
== "\\-\n\nreal div content"
)
# Real text directly inside a real - that itself looks like a marker is
# escaped too.
assert to_md("") == "- \\-"
def test_conversion_html_to_markdown_list_indentation():
"""Test list continuation indentation."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Baseline: a single
as an - 's only child still just glues onto the
# marker.
assert to_md("
text ") == "- text"
# Later paragraphs use the current item's continuation indentation.
assert to_md("") == "- one\n\n two"
# Ordered lists need the indentation to match their own (wider) marker
# width, not the bullet list's fixed 2 spaces
assert (
to_md("one two ") == "1. one\n\n two"
)
# Sibling - s must NOT pick up any indentation from each other -- only a
# *continuation within the same item* should ever be indented
assert (
to_md("")
== "- alpha\n\n- beta"
)
assert (
to_md("
a b c ")
== "1. a\n\n2. b\n\n3. c"
)
# A nested sublist's own marker (computed independently for its own depth)
# must not be *additionally* indented on top of that.
assert to_md("") == "- x\n - x"
assert (
to_md("")
== "- L1\n - L2\n - L3"
)
# Nested quotes combine list indentation with quote prefixes.
assert to_md(
""
) == ("- > a\n >\n > b")
# A first-child list inside a blockquote retains the quote prefix.
assert to_md("") == (
"> - text"
)
# Multiple - s inside a
each need "> " restated
assert to_md("") == (
"> - a\n> - b"
)
# Chained blockquotes retain nesting after a paragraph boundary.
assert to_md(
"a nested "
) == ("> a\n>\n> > nested")
# / inside an - : every line of the fence.
assert to_md("") == (
"- code:\n ```\n indented\n here\n ```"
)
# A deeper list adds another indentation level to the fence.
assert to_md(
""
) == ("- outer\n - inner:\n ```\n x = 1\n ```")
def test_conversion_html_to_markdown_br():
"""Test CommonMark hard breaks."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Two trailing spaces then a newline -- a bare "\n" is only a soft break
# under CommonMark (most renderers collapse it to a single space rather.
assert to_md("line1
line2") == "line1 \nline2"
assert to_md("line1 line2") == "line1 \nline2"
assert to_md("line1 line2") == "line1 \nline2"
# Verified against an actual renderer, not just the raw Markdown shape.
rendered = convert_between(
NotifyFormat.MARKDOWN, NotifyFormat.HTML, to_md("line1 line2")
)
assert " tags each contribute their own hard break
assert to_md("a
b") == "a \n \nb"
# A trailing with nothing after it doesn't leave a dangling hard break
# at the very end of the output
assert to_md("line1
") == "line1"
# A hard break inside a blockquote must restate the "> " prefix on its
# continuation line.
assert to_md("line1 line2 ") == (
"> line1 \n> line2"
)
# Same, but inside a list item -- the continuation line must keep the
# marker's indentation so it stays part of the same item.
assert to_md("") == ("- line1 \n line2")
# Both nested together -- a blockquote containing a list item.
assert to_md(
""
) == ("> - line1 \n > line2")
def test_conversion_html_to_markdown_tables():
"""Test GFM table conversion."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Basic table -- first row becomes the header, a "---" separator row is
# inserted right after it
assert to_md(
""
) == ("| A | B |\n| --- | --- |\n| 1 | 2 |")
# // are fully transparent -- header-vs-body is decided
# purely by row order, the same as -less markup
assert to_md(
""
) == ("| Name | Age |\n| --- | --- |\n| Bob | 42 |")
# A single-row table still gets its separator row
assert to_md("") == (
"| only |\n| --- |"
)
# Inline formatting inside cells is preserved
assert to_md(
"'
) == ("| **bold** | [link]() |\n| --- | --- |")
# A literal '|' inside a cell is escaped -- it's the cell delimiter itself,
# and would otherwise be misread as starting a new column
assert to_md("") == (
"| a \\| b |\n| --- |"
)
# A newline a cell's own content produced (here, a ) is flattened to a
# single space.
assert to_md("") == (
"| a b |\n| --- |"
)
# Surrounding content gets ordinary paragraph separation from the table,
# the same as a list or blockquote would
assert to_md("before ") == (
"before\n\n| A |\n| --- |"
)
assert to_md("after ") == (
"| A |\n| --- |\n\nafter"
)
# An entirely empty table, or a table whose only row has no cells at all,
# produces nothing
assert to_md("") == ""
assert to_md("") == ""
# A table fully inside a suppressed container (e.g. ) contributes
# nothing -- not even an empty "| |" row
assert (
to_md(
"text"
)
== "text"
)
# Suppress text outside table cells.
assert to_md("") == (
"| A |\n| --- |"
)
assert to_md("") == (
"| A |\n| --- |"
)
assert to_md("") == (
"| A |\n| --- |"
)
# A stray with no enclosing | at all falls back to ordinary
# paragraph-like treatment -- the same as before table support existed
assert to_md("| standalone | ") == "standalone"
# A stray with no enclosing is treated as a one-row table of
# its own
assert to_md("| a | b | ") == (
"| a | b |\n| --- | --- |"
)
def test_conversion_html_to_markdown_tables_indentation():
"""Test nested table indentation."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
assert to_md(
""
) == ("- before\n\n | A |\n | --- |")
assert to_md(
""
) == ("- before\n\n | A | B |\n | --- | --- |\n | 1 | 2 |")
assert to_md(
""
) == ("> | A | B |\n> | --- | --- |\n> | 1 | 2 |")
def test_conversion_html_to_markdown_tables_hardening():
"""Test malformed table input."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Neither nor | ever closed -- extremely common in real-
# world/legacy table markup
assert to_md("") == (
"| A | B |\n| --- | --- |\n| 1 | 2 |"
)
# Same, but the enclosing is missing too -- the last row and cell
# are recovered at end of document
assert to_md("| A | B | | 1 | 2") == (
"| A | B |\n| --- | --- |\n| 1 | 2 |"
)
# A stray | or with nothing matching open at all (no enclosing
# structure whatsoever, not even an open cell) is a no-op.
assert to_md(" text") == "text"
assert to_md("text") == "text"
assert to_md("ab ") == "ab"
assert to_md("ab ") == "ab"
# A stray with no enclosing renders as a one-row table of its
# own and remains separated from following content.
assert to_md("| cell | after") == (
"| cell |\n| --- |\n\nafter"
)
# A nested inside another table's cell has no Markdown
# representation.
assert to_md(
""
) == ("| outer |\n| --- |")
# Same, with content both before and after the nested table, and the
# nested table itself containing more than one row.
assert to_md(
""
) == ("| a d |\n| --- |")
# Three levels deep -- only the outermost table survives.
assert to_md(
""
) == ("| L1 |\n| --- |")
# A literal '|' alongside a nested table in the same cell -- the '|' is
# still escaped normally; the nested table still contributes nothing.
assert to_md(
""
) == ("| a\\|b |\n| --- |")
# Only the very first is ever closed
assert to_md("") == (
"| A |\n| --- |\n| B |\n| C |"
)
# An unclosed inline element () inside a | is silently discarded
# when a sibling | opens; the cell's text is still captured.
assert (
to_md(
""
)
== "| *unclosed text | second cell |\n| --- | --- |"
)
# Performance: many rows, each with unclosed | / | tags (the legacy-
# markup shape), large enough to expose quadratic recovery.
n = 20000
html = ""
start = default_timer()
out = to_md(html)
elapsed = default_timer() - start
assert out.count("\n") == n # one line per row, output stays linear
# Generous bound -- see the note on the equivalent check above.
assert elapsed < 40.0
def test_conversion_html_to_markdown_pre_code_whitespace():
"""Test preformatted whitespace."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# Internal leading whitespace and blank-looking indentation differences
# between lines are preserved exactly
assert (
to_md(" leading\n more leading\nback to zero ")
== "```\n leading\n more leading\nback to zero\n```"
)
# Leading/trailing spaces inside inline survive too
assert to_md(" leading spaces ") == "` leading spaces `"
# Whitespace is preserved the same way even when nested inside a list item
# (which now adds its own 2-space indentation in front.
assert to_md("") == (
"- ```\n a\n b\n c\n ```"
)
def test_conversion_html_to_markdown_unterminated_pre_code():
"""Test // left open at end of document."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# A // with no closing tag at all is auto-closed and
# rendered at end of document.
assert to_md("unterminated code") == "```\nunterminated code\n```"
assert to_md("inline unterminated") == "`inline unterminated`"
assert to_md("unterminated output") == (
"```\nunterminated output\n```"
)
# Still works with real content before the unterminated block.
assert to_md("textcode") == "text\n```\ncode\n```"
# A suppressed (non-storing) unterminated frame contributes nothing.
assert to_md("hidden") == ""
def test_conversion_html_to_markdown_table_code_pipe():
"""Test '|' inside an inline code span within a table cell."""
def to_md(body):
"""Wrapper to simplify html-to-markdown conversion tests."""
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
# A '|' inside a code span is already literal there.
assert to_md("") == (
"| `a|b` |\n| --- |"
)
# A '|' outside any code span in the same cell is still escaped.
assert to_md("") == (
"| x\\|`a|b`\\|y |\n| --- |"
)
# Literal backtick CHARACTERS typed as ordinary text (not an actual
# element) get backslash-escaped by MARKDOWN_ESCAPE like any other.
assert to_md("") == (
"| \\`a\\|b\\` |\n| --- |"
)
# A real code span and escaped literal backticks can coexist in the same
# cell -- only the real one's '|' stays unescaped.
assert to_md(
""
) == ("| `x|y` and \\`lit\\|eral\\` |\n| --- |")
# A real code span immediately preceded by an ESCAPED literal backslash (an
# even number of '\' characters, i.e.
assert to_md(
""
) == ("| text\\\\`a|b` |\n| --- |")
assert to_md(
""
) == ("| text\\\\\\\\`a|b` |\n| --- |")
# An unmatched (unbalanced) bare backtick run inside a cell.
conv = HTMLMarkdownConverter()
assert conv._escape_cell_pipes("a`b|c") == "a`b\\|c"
# The shared index skips escape pairs and groups runs by exact width.
# A lookup returns None when the requested width does not exist.
assert find_unescaped_run(build_backtick_run_index("\\` `"), 0, 1) == 3
assert (
find_unescaped_run(build_backtick_run_index("no backticks here"), 0, 1)
is None
)
assert (
find_unescaped_run(build_backtick_run_index("``too short"), 0, 3)
is None
)
# Runs of different widths are indexed separately.
assert find_unescaped_run(build_backtick_run_index("`` `"), 0, 1) == 3
# Skip an escaped single backtick before matching a width-two run.
assert find_unescaped_run(build_backtick_run_index("\\` ``x"), 0, 2) == 3
# Skip an unescaped run of the wrong width before matching width two.
assert find_unescaped_run(build_backtick_run_index("` ``x"), 0, 2) == 2
# A genuine match arbitrarily far from `start` is still found.
far = "a" * 200_000 + "`"
assert find_unescaped_run(build_backtick_run_index(far), 0, 1) == 200_000
# A cell containing many distinct, non-matching backtick-run lengths must
# still resolve in roughly linear time, not quadratic.
def adversarial_cell(width_count):
body = ["`" * w + "x" for w in range(1, width_count + 1)]
body.append("`")
return "".join(body)
small = adversarial_cell(400)
large = adversarial_cell(800)
start = default_timer()
conv._escape_cell_pipes(small)
small_time = default_timer() - start
start = default_timer()
conv._escape_cell_pipes(large)
large_time = default_timer() - start
# Double the adversarial width count.
assert large_time < small_time * 6 + 0.05
def test_conversion_text_to():
"""conversion: Test Text to all types"""
response = convert_between(
NotifyFormat.TEXT,
NotifyFormat.HTML,
"Test MessageBody",
)
assert (
response
== "<title>Test Message</title><body>Body<"
"/body>"
)
def test_conversion_markdown_to_html():
"""conversion: Test markdown to html"""
# While this uses the underlining markdown library
# what we're testing for are the edge cases we know it doesn't support
# hence, `-` (a dash) with the markdown library must be a `*` to work
# correctly
response = convert_between(
NotifyFormat.MARKDOWN,
NotifyFormat.HTML,
cleandoc("""
## Some Heading
With Data:
- Foo
- Bar
"""),
)
assert "- Foo
" in response
assert "- Bar
" in response
assert "Some Heading" in response
assert " " not in response
# if the - follows With Data on the very next line, it's consider to not
# requiring indentation
response = convert_between(
NotifyFormat.MARKDOWN,
NotifyFormat.HTML,
cleandoc("""
## Some Heading
With Data:
- Foo
- Bar
"""),
)
# Breaks are added:
assert " " in response
assert "- Foo" in response
assert "- Bar" in response
# Table formatting
response = convert_between(
NotifyFormat.MARKDOWN,
NotifyFormat.HTML,
cleandoc("""
First Header | Second Header
-------------- | -------------
Content Cell1 | Content Cell3
Content Cell2 | Content Cell4
"""),
)
assert "" in response
assert "| First Header | " in response
assert "Second Header | " in response
assert "Content Cell1 | " in response
assert "Content Cell2 | " in response
assert "Content Cell3 | " in response
assert "Content Cell4 | " in response
| |