# 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 from unittest import mock import pytest from apprise import NotifyFormat from apprise.conversion import ( BLOCKQUOTE_DEPTH_MAX, LIST_DEPTH_MAX, MAX_FRAME_DEPTH, HTMLMarkdownConverter, commonmark as commonmark_module, commonmark_can_close_emphasis, commonmark_can_open_emphasis, commonmark_decode_backslash_escapes, commonmark_emphasis_run, commonmark_find_backtick_run, commonmark_headings_to_bold, commonmark_index_backtick_runs, commonmark_match_emphasis, commonmark_materialize_repair, commonmark_pick_emphasis_sentinel, commonmark_render_emphasis_events, commonmark_render_emphasis_markers, commonmark_repair_chunk, commonmark_scan_autolink_dest, commonmark_scan_closer_runs, commonmark_scan_delimiter_run, commonmark_scan_paren_dest, commonmark_scan_repair_region, convert_between, html_to_markdown, markdown_to_html, split_dialect_chunk, truncate_dialect_chunk, ) from apprise.plugins.google_chat import NotifyGoogleChat from apprise.plugins.slack import NotifySlack 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( "
line 1 bold
" " my link" "

3rd line" ) == "line 1 bold\nmy link\n3rd line" ) #


on it's own assert to_html("
") == "---" assert to_html("
") == "---" # We need to handle HTML Encodings assert ( to_html(""" ignore this entry Let's handle special html encoding
""") == "Let's handle special html encoding\n---" ) # If you give nothing, you get nothing in return assert to_html("") == "" # Special case on HR tag assert ( to_html("""

FROM: apprise-test@mydomain.yyy

Hi!
How are you?
red font link you wanted.
""") == "FROM: apprise-test@mydomain.yyy\nHi!\n How are you?\n red font" " link you wanted." ) assert ( to_html("""

FROM: apprise-test@mydomain.yyy


Hi!
How are you?
red font link you wanted.
""") == "FROM: apprise-test@mydomain.yyy\n---\nHi!\n How are you?\n red" " font link you wanted." ) # Special case on HR if text is sorrunded by HR tags # its created a dict element assert ( to_html("""


FROM: apprise-test@mydomain.yyy

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("
  • Lots and lots
  • of lists.
") 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
  • beta
  • gamma
") == "- alpha\n- beta\n- gamma" ) # Flat ordered list with auto-incrementing counter assert ( to_md("
  1. first
  2. second
  3. third
") == "1. first\n2. second\n3. third" ) #
    shifts where the auto-incrementing counter begins assert to_md('
    1. a
    2. b
    ') == "4. a\n5. b" assert to_md('
    1. a
    ') == "0. a" # CommonMark list markers cannot represent negative starting values. assert to_md('
    1. a
    2. b
    ') == "0. a\n1. b" # A non-numeric start is ignored, same as no attribute at all assert to_md('
    1. a
    ') == "1. a" #
  1. resets the counter for that item and every sibling after it assert to_md('
    1. a
    2. b
    ') == "5. a\n6. b" assert ( to_md('
    1. a
    2. b
    3. c
    ') == "1. a\n10. b\n11. c" ) assert to_md('
    1. a
    2. 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('
    1. a
    2. b
    ') == "1. a\n2. b" # Nested unordered lists (2 levels) assert ( to_md( "
    • top A
      • nested A
    • top B
    " ) == "- top A\n - nested A\n- top B" ) # Nested unordered lists (3 levels) assert ( to_md("
    • L1
      • L2
        • L3
    ") == "- L1\n - L2\n - L3" ) # Mixed nesting: ol inside ul assert ( to_md( "
      " "
    • intro
        " "
      1. step one
      2. " "
      3. step two
      4. " "
    • " "
    " ) == "- intro\n 1. step one\n 2. step two" ) # Mixed nesting: ul inside ol assert ( to_md( "
      " "
    1. first
        " "
      • sub A
      • " "
      • sub B
      • " "
    2. " "
    3. second
    4. " "
    " ) == "1. first\n - sub A\n - sub B\n2. second" ) # Malformed HTML: missing
  2. in a
      HTMLParser does not synthesize # implicit close events; each missing is simply absent, but the next. assert ( to_md("
      • item A
      • item B
      • item C
      ") == "- item A\n- item B\n- item C" ) # Without , ordered-list counters cannot advance. assert ( to_md("
      1. one
      2. two
      3. 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
        (no
      • wrapper)
          is in # IGNORE_TAGS so unwrapped text is suppressed entirely assert to_md("
            bare text
          ") == "" # inside
        • : inline code preserved with backticks assert ( to_md("
          • run cmd --flag now
          ") == "- run `cmd --flag` now" ) # Markdown special characters inside are NOT escaped assert ( to_md("
          • see x*2 #tag
          ") == "- see `x*2 #tag`" ) # Fenced blocks retain content and list indentation. assert ( to_md("
          • code:
              indented\n  here
          ") == "- code:\n ```\n indented\n here\n ```" ) # Nested fenced blocks combine content indentation with list indentation. assert ( to_md( "
          • outer
            • inner:
                x = 1
          " ) == "- outer\n - inner:\n ```\n x = 1\n ```" ) # A first-child block shares the list marker's line. # Single item with a

          first child assert to_md("

          • alpha

          ") == "- alpha" # Multiple items each with a

          first child. assert ( to_md("

          • alpha

          • beta

          ") == "- alpha\n\n- beta" ) # Multiple

          children inside one

        • assert to_md("
          • one

            two

          ") == "- one\n\n two" # Mixed: direct text for first item,

          for second. assert ( to_md("

          • direct
          • wrapped

          ") == "- direct\n- wrapped" ) # Numbered list with

          children assert ( to_md("

          1. first

          2. second

          ") == "1. first\n\n2. second" ) # link as first child of
        • -- the marker must share the line assert to_md("") == "- [link]()" # with nested markup as first (and only) child of
        • assert ( to_md("") == "- [**bold link**]()" ) # link followed by a

          sibling inside the same

        • . assert ( to_md("") == "- [link]()\n\n more" ) def test_conversion_html_to_markdown_escaping(): """Test Markdown escaping.""" def to_md(body): """Wrapper to simplify html-to-markdown conversion tests.""" return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) # Embedded backticks widen code delimiters. assert to_md("a`b") == "``a`b``" # Content starting or ending with a backtick gets a padding space, per # CommonMark's code-span disambiguation rule assert to_md("`x") == "`` `x ``" assert to_md("x`") == "`` x` ``" # A run of 3 backticks inside
           widens the fence past 3
              assert to_md("
          boom```
          ") == "````\nboom```\n````" # Plain content with no backticks still uses the minimal delimiter assert to_md("
          x
          ") == "```\nx\n```" # Ignored containers suppress both text and Markdown markers. assert ( to_md( "ignore

          keep

          " ) == "keep" ) # A heading marker ("# ") must not leak from a suppressed container assert ( to_md("

          hidden heading

          text") == "text" ) # A list marker ("- ") must not leak from a
        • nested inside a suppressed # container, even though
        • normally re-enables storage assert ( to_md("
          • hidden item
          text") == "text" ) #

          keep

          ") == "keep" # A
           block fully inside a suppressed container emits nothing, not even
              # an empty fence
              assert to_md("

          keep

          ") == "keep" # Angle destinations preserve whitespace in link targets. assert to_md("link") == "[link]()" # Nested tags are inert inside preformatted content. assert ( to_md("
          before link after
          ") == "```\nbefore link after\n```" ) assert ( to_md("before bold after") == "`before bold after`" ) # Stray code/pre/samp close tags assert to_md("
          text") == "text" assert to_md("
          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 ![x](https://evil.example.com/x.png) 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 \alert\(1\)\" ) # 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 or 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
    • B
    ") == "- 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 + "
    • hidden
    • " + "
    " * 50 + "text" ) == "text" ) # deep
      nesting still resolve correctly. assert ( to_md("
        " * 50 + "
      • visible
      • " + "
      " * 50) == "- visible" ) # List indentation is capped at LIST_DEPTH_MAX --- assert LIST_DEPTH_MAX == 4 one_per_level = "
      • x" * 10 + "
      " * 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 = "
      • 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 # 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_headings_to_bold(): """Convert supported ATX headings for chat dialects without headings.""" # Convert the common heading forms generated from HTML. assert commonmark_headings_to_bold("# Alert") == "**Alert**" assert commonmark_headings_to_bold("###### Alert") == "**Alert**" # An optional closing sequence of "#" is stripped, not kept as text. assert commonmark_headings_to_bold("## foo ##") == "**foo**" assert commonmark_headings_to_bold("# foo #####") == "**foo**" # A hash without preceding whitespace remains part of the heading text. assert commonmark_headings_to_bold("# foo#") == "**foo#**" # Preserve up to three spaces allowed before a heading. assert commonmark_headings_to_bold(" # one space") == " **one space**" assert commonmark_headings_to_bold(" # three spaces") == ( " **three spaces**" ) # Four leading spaces make an indented code block, not a heading. four_spaces = " # four spaces" assert commonmark_headings_to_bold(four_spaces) == four_spaces # Empty headings do not produce empty bold markers. assert commonmark_headings_to_bold("###") == "" assert commonmark_headings_to_bold("### ") == "" # Heading text requires whitespace after its opening hashes. literal = "#nospace" assert commonmark_headings_to_bold(literal) == literal # Inline code spans are never touched. assert commonmark_headings_to_bold("`# inline code`") == ( "`# inline code`" ) # Backtick and tilde fences protect heading-like code. fenced_backtick = "```\n# not a heading\n```" assert commonmark_headings_to_bold(fenced_backtick) == fenced_backtick fenced_tilde = "~~~\n# not a heading either\n~~~" assert commonmark_headings_to_bold(fenced_tilde) == fenced_tilde # An unfinished fence protects the remaining text. unterminated = "```\n# still not a heading\nmore text" assert commonmark_headings_to_bold(unterminated) == unterminated # A real heading before and after a fenced block is still converted. mixed = "# Before\n```\n# inside\n```\n# After" assert commonmark_headings_to_bold(mixed) == ( "**Before**\n```\n# inside\n```\n**After**" ) # Preserve blockquote markers emitted by HTML-to-CommonMark conversion. assert commonmark_headings_to_bold("> # Alert") == "> **Alert**" assert commonmark_headings_to_bold("> > # Alert") == "> > **Alert**" assert commonmark_headings_to_bold("> > > # Alert") == ("> > > **Alert**") # Preserve unordered and ordered list markers. assert commonmark_headings_to_bold("- # Alert") == "- **Alert**" assert commonmark_headings_to_bold("* # Alert") == "* **Alert**" assert commonmark_headings_to_bold("+ # Alert") == "+ **Alert**" assert commonmark_headings_to_bold("1. # Alert") == "1. **Alert**" assert commonmark_headings_to_bold("2) # Alert") == "2) **Alert**" # Preserve combined blockquote and list markers. assert commonmark_headings_to_bold("> - # Alert") == "> - **Alert**" # Keep the blockquote marker for an empty heading. assert commonmark_headings_to_bold("> ###") == "> " # Recognize CRLF fences without protecting later headings. crlf_fence = "```\r\ncode\r\n```\r\n# Real Heading" assert commonmark_headings_to_bold(crlf_fence) == ( "```\r\ncode\r\n```\r\n**Real Heading**" ) # Invalid backtick fence labels do not protect later headings. invalid_opener = ( "Some `inline` text\n" "```code`with`backtick info string\n" "more text\n" "# Real Heading" ) assert commonmark_headings_to_bold(invalid_opener) == ( "Some `inline` text\n" "```code`with`backtick info string\n" "more text\n" "**Real Heading**" ) # Tilde fence labels may contain backticks. tilde_with_backtick = "~~~code`ok\nreal code\n~~~" assert ( commonmark_headings_to_bold(tilde_with_backtick) == tilde_with_backtick ) # Preserve heading-like text inside a quoted tilde fence. quoted_tilde_fence = "> ~~~\n> # literal code\n> ~~~" assert ( commonmark_headings_to_bold(quoted_tilde_fence) == quoted_tilde_fence ) # Repeating ``"- "`` starts a sibling list item, so these are three # separate items. The middle heading remains real Markdown and converts. three_sibling_items = "- ~~~\n- # literal code\n- ~~~~" assert commonmark_headings_to_bold(three_sibling_items) == ( "- ~~~\n- **literal code**\n- ~~~~" ) # A backtick closer wider than its opener still closes the fence, even # when both are nested inside a blockquote. quoted_wider_closer = "> ```\n> # literal code\n> ````" assert ( commonmark_headings_to_bold(quoted_wider_closer) == quoted_wider_closer ) # Nested blockquotes around a fence are recognized at every level. nested_quoted_fence = "> > ~~~\n> > # literal code\n> > ~~~" assert ( commonmark_headings_to_bold(nested_quoted_fence) == nested_quoted_fence ) # Quote markers may have up to three leading spaces. assert commonmark_headings_to_bold(" > # Alert") == " > **Alert**" indented_quoted_fence = " > ~~~\n > # literal code\n > ~~~" assert ( commonmark_headings_to_bold(indented_quoted_fence) == indented_quoted_fence ) # Four leading spaces create indented code, not a top-level fence. # The following real heading must therefore still be converted. four_space_fence_then_heading = ( " ~~~\n not a real fence\n ~~~\n# Real Heading" ) assert commonmark_headings_to_bold(four_space_fence_then_heading) == ( " ~~~\n not a real fence\n ~~~\n**Real Heading**" ) # An ordered-list marker can be wider than three characters ("123. " # is five), so its continuation lines need more than three leading # spaces too. A real heading after the fence must still convert. wide_ordered_fence = "123. ~~~\n # literal\n ~~~\n\n# real" assert commonmark_headings_to_bold(wide_ordered_fence) == ( "123. ~~~\n # literal\n ~~~\n\n**real**" ) # A list containing a quote puts the list marker first, while continuation # lines replace it with spaces. Both prefix orders belong to one container. list_then_quote_fence = "- > ~~~\n > # literal\n > ~~~\n\n# real" assert commonmark_headings_to_bold(list_then_quote_fence) == ( "- > ~~~\n > # literal\n > ~~~\n\n**real**" ) # Up to three leading spaces may belong to a top-level fence rather than # a list. Its heading-like content must remain protected. lightly_indented_fence = " ~~~\n# literal\n ~~~\n# real" assert commonmark_headings_to_bold(lightly_indented_fence) == ( " ~~~\n# literal\n ~~~\n**real**" ) # Opening and closing fences have independent indentation allowances. mismatched_indent_fence = "~~~\n# literal\n ~~~\n# real" assert commonmark_headings_to_bold(mismatched_indent_fence) == ( "~~~\n# literal\n ~~~\n**real**" ) # The same closer slack applies inside a blockquote. quoted_mismatched_indent_fence = "> ~~~\n> # literal\n> ~~~\n> # real" assert commonmark_headings_to_bold(quoted_mismatched_indent_fence) == ( "> ~~~\n> # literal\n> ~~~\n> **real**" ) # A lightly indented fence can continue a list item without repeating # its marker. An unfinished fence stops when that list item ends. unclosed_narrow_list_fence = "- intro\n ~~~\n # literal\n\n# real" assert commonmark_headings_to_bold(unclosed_narrow_list_fence) == ( "- intro\n ~~~\n # literal\n\n**real**" ) # A later top-level fence cannot close the list's unfinished fence. unclosed_narrow_list_fence_with_later_fence = ( "- intro\n ~~~\n # literal\n\n# real\n\n~~~\nunrelated\n~~~" ) assert commonmark_headings_to_bold( unclosed_narrow_list_fence_with_later_fence ) == ("- intro\n ~~~\n # literal\n\n**real**\n\n~~~\nunrelated\n~~~") # Blank lines before the fence may remain within the list item. unclosed_narrow_list_fence_with_blank = ( "- intro\n\n ~~~\n # literal\n\n# real" ) assert commonmark_headings_to_bold( unclosed_narrow_list_fence_with_blank ) == ("- intro\n\n ~~~\n # literal\n\n**real**") # Light indentation without an earlier list marker is top-level. unmarked_indent_no_list_behind_it = ( "Some intro text\n ~~~\n# literal\n ~~~\n# real" ) assert commonmark_headings_to_bold(unmarked_indent_no_list_behind_it) == ( "Some intro text\n ~~~\n# literal\n ~~~\n**real**" ) # The paragraph lazily continues the list, but one-space fence indentation # is still insufficient for the two-space item. list_ended_by_unindented_paragraph = ( "- intro\nunindented paragraph\n ~~~\n# literal\n ~~~\n# real" ) assert commonmark_headings_to_bold(list_ended_by_unindented_paragraph) == ( "- intro\nunindented paragraph\n ~~~\n# literal\n ~~~\n**real**" ) # Indented list text may appear between the marker and fence. unclosed_narrow_list_fence_with_paragraph = ( "- intro\n more text in the same item\n ~~~\n # literal\n\n# real" ) assert commonmark_headings_to_bold( unclosed_narrow_list_fence_with_paragraph ) == ( "- intro\n more text in the same item\n ~~~\n # literal\n\n**real**" ) # The HTML converter replaces a list marker with equal-width spaces on # continuation lines. Test that real output as well as synthetic input. list_only_fence_html = ( "
    • # literal\nmore
    " "

    Real Heading

    " ) list_only_fence_body = html_to_markdown(list_only_fence_html) assert list_only_fence_body == ( "- ```\n # literal\n more\n ```\n\n# Real Heading" ) converted = commonmark_headings_to_bold(list_only_fence_body) # The heading-like line inside the fence stays literal code. assert " # literal\n" in converted # A real heading placed after the fenced block still converts. assert converted.endswith("\n**Real Heading**") # Also cover a preceding paragraph and the wider numbered-list marker. text_then_fence_html = ( "
    • intro
      # literal\nmore
    " "

    Real Heading

    " ) text_then_fence_body = html_to_markdown(text_then_fence_html) assert text_then_fence_body == ( "- intro\n ```\n # literal\n more\n ```\n\n# Real Heading" ) converted = commonmark_headings_to_bold(text_then_fence_body) assert " # literal\n" in converted assert converted.endswith("\n**Real Heading**") ordered_fence_html = ( "
    1. # literal\nmore
    " "

    Real Heading

    " ) ordered_fence_body = html_to_markdown(ordered_fence_html) assert ordered_fence_body == ( "1. ```\n # literal\n more\n ```\n\n# Real Heading" ) converted = commonmark_headings_to_bold(ordered_fence_body) assert " # literal\n" in converted assert converted.endswith("\n**Real Heading**") # List continuation spacing moves before the quote marker on later lines. quoted_list_fence_html = ( "
    • intro" "
      # literal\nmore
    " "

    Real Heading

    " ) quoted_list_fence_body = html_to_markdown(quoted_list_fence_html) assert quoted_list_fence_body == ( "> - intro\n > ```\n > # literal\n > more\n > ```" "\n\n# Real Heading" ) converted = commonmark_headings_to_bold(quoted_list_fence_body) assert " > # literal\n" in converted assert converted.endswith("\n**Real Heading**") # Leading list indentation contributes to the continuation width, whether # the fence begins the item or follows its introductory text. indented_marker_then_fence = " - ~~~\n # literal\n ~~~\n# real" assert commonmark_headings_to_bold(indented_marker_then_fence) == ( " - ~~~\n # literal\n ~~~\n**real**" ) indented_marker_with_intro = " - intro\n ~~~\n # literal\n\n# real" assert commonmark_headings_to_bold(indented_marker_with_intro) == ( " - intro\n ~~~\n # literal\n\n**real**" ) # A literal "- " inside a closed fence must not create list state for the # unfinished top-level fence that follows it. marker_like_text_inside_closed_fence = ( "~~~\n- literal\n ~~~\n ~~~\n# still code" ) assert commonmark_headings_to_bold( marker_like_text_inside_closed_fence ) == ("~~~\n- literal\n ~~~\n ~~~\n# still code") # Ending an inner list restores the still-open outer list width. nested_list_falls_back_to_outer = ( "- outer\n - inner\n text\n ~~~\n # literal\n\n# real" ) assert commonmark_headings_to_bold(nested_list_falls_back_to_outer) == ( "- outer\n - inner\n text\n ~~~\n # literal\n\n**real**" ) # An unindented paragraph may lazily continue an open list item. lazy_continuation_keeps_list_open = ( "- intro\nlazy continuation\n ~~~\n # literal\n\n# real" ) assert commonmark_headings_to_bold(lazy_continuation_keeps_list_open) == ( "- intro\nlazy continuation\n ~~~\n # literal\n\n**real**" ) # A new list marker ends lazy paragraph continuation. new_marker_ends_lazy_continuation = ( "- intro\nordinary text\n- newitem\n ~~~\n # literal\n\n# real" ) assert commonmark_headings_to_bold(new_marker_ends_lazy_continuation) == ( "- intro\nordinary text\n- newitem\n ~~~\n # literal\n\n**real**" ) # A list fence closer may add only three columns of indentation. # Greater indentation leaves it open until the list ends. wildly_overindented_list_closer = ( "- intro\n ```\n code\n ```\n# real" ) assert commonmark_headings_to_bold(wildly_overindented_list_closer) == ( "- intro\n ```\n code\n ```\n**real**" ) # The same three-column closer limit applies outside lists. wildly_overindented_top_level_closer = "```\ncode\n ```\n# after" assert commonmark_headings_to_bold( wildly_overindented_top_level_closer ) == ("```\ncode\n ```\n# after") # ``-\t`` reaches column four. Two spaces cannot continue that list, so # the following unfinished fence is top-level and protects the remainder. tab_expanded_marker_width = "-\tintro\n ```\n # literal\n\n# real" assert commonmark_headings_to_bold(tab_expanded_marker_width) == ( tab_expanded_marker_width ) # A tab reaches the same column as ``-\t``, keeping the fence in the list. tab_expanded_continuation_width = "-\tintro\n\t```\n\t# literal\n\n# real" assert commonmark_headings_to_bold(tab_expanded_continuation_width) == ( "-\tintro\n\t```\n\t# literal\n\n**real**" ) # Accept quote-first continuation lines as well as Apprise's list-first # output when a fenced block is nested in both containers. quote_then_list_continuation = "- > ~~~\n> # literal\n> ~~~\n\n# real" assert commonmark_headings_to_bold(quote_then_list_continuation) == ( "- > ~~~\n> # literal\n> ~~~\n\n**real**" ) # A quote-first closer still needs the list's full indentation. quote_then_list_insufficient_width = ( "- > ~~~\n> # literal\n> ~~~\n> ~~~\n\n# real" ) assert commonmark_headings_to_bold(quote_then_list_insufficient_width) == ( "- > ~~~\n> # literal\n> ~~~\n> ~~~\n\n**real**" ) # List indentation without the required quote marker ends the container. list_width_met_but_no_quote_at_all = ( "- > ~~~\n text without quote\n> ~~~\n\n# real" ) assert commonmark_headings_to_bold(list_width_met_but_no_quote_at_all) == ( "- > ~~~\n text without quote\n> ~~~\n\n**real**" ) # A bare quote marker still satisfies its quote depth. bare_quote_marker_line_in_combo = "- > ~~~\n>\n> ~~~\n\n# real" assert commonmark_headings_to_bold(bare_quote_marker_line_in_combo) == ( "- > ~~~\n>\n> ~~~\n\n**real**" ) # A heading ends the list, making the following unfinished fence top-level. heading_ends_list_before_fence = ( "- intro\n# outside\n ~~~\n # literal\n# still code" ) assert commonmark_headings_to_bold(heading_ends_list_before_fence) == ( "- intro\n**outside**\n ~~~\n # literal\n# still code" ) # A heading inside a list marker cannot gain a lazy continuation. marker_content_is_heading = ( "- # heading\noutside\n ~~~\n # literal\n# still code" ) assert commonmark_headings_to_bold(marker_content_is_heading) == ( "- **heading**\noutside\n ~~~\n # literal\n# still code" ) # Blockquotes and thematic breaks also end lazy list continuation. blockquote_ends_list_before_fence = ( "- intro\n> outside\n ~~~\n # literal\n# still code" ) assert commonmark_headings_to_bold(blockquote_ends_list_before_fence) == ( "- intro\n> outside\n ~~~\n # literal\n# still code" ) thematic_break_ends_list_before_fence = ( "- intro\n---\n ~~~\n # literal\n# still code" ) assert commonmark_headings_to_bold( thematic_break_ends_list_before_fence ) == ("- intro\n---\n ~~~\n # literal\n# still code") # CRLF input follows the same thematic-break boundary rule. thematic_break_ends_list_crlf = ( "- intro\r\n---\r\n ~~~\r\n # literal\r\n# still code" ) assert commonmark_headings_to_bold(thematic_break_ends_list_crlf) == ( "- intro\r\n---\r\n ~~~\r\n # literal\r\n# still code" ) # A tab at column zero reaches column four, creating indented code. tab_at_column_zero_is_not_slack = "\t# literal" assert ( commonmark_headings_to_bold(tab_at_column_zero_is_not_slack) == tab_at_column_zero_is_not_slack ) tab_at_column_zero_fence_is_not_slack = "\t~~~\ncode\n\t~~~\n# real" assert commonmark_headings_to_bold( tab_at_column_zero_fence_is_not_slack ) == ("\t~~~\ncode\n\t~~~\n**real**") # A tab after a quote can remain within the three-column allowance. tab_after_quote_is_slack = ">\t# literal" assert commonmark_headings_to_bold(tab_after_quote_is_slack) == ( ">\t**literal**" ) # Tabs between nested quote markers use one column of marker padding. tab_separated_nested_quote_fence = ( ">\t>\t~~~\n>\t>\t# literal\n>\t>\t~~~\n>\t>\t# real" ) assert commonmark_headings_to_bold(tab_separated_nested_quote_fence) == ( ">\t>\t~~~\n>\t>\t# literal\n>\t>\t~~~\n>\t>\t**real**" ) # Nested quote markers also work without separating spaces. unspaced_nested_quote_fence = ">>~~~\n>>literal\n>>~~~\n>># real" assert commonmark_headings_to_bold(unspaced_nested_quote_fence) == ( ">>~~~\n>>literal\n>>~~~\n>>**real**" ) # Tab-separated quote/list content uses indentation on continuation lines. tab_separated_quote_list_fence = ( ">\t-\tintro\n>\t ~~~\n>\t # literal\n>\t ~~~\n>\t# real" ) assert commonmark_headings_to_bold(tab_separated_quote_list_fence) == ( ">\t-\tintro\n>\t ~~~\n>\t # literal\n>\t ~~~\n>\t**real**" ) # HTML blocks end lazy list paragraphs, making the next fence top-level. html_block_ends_list_before_fence = ( "- intro\n
    \nhtml\n
    \n\n ~~~\n # literal\n# still code" ) assert commonmark_headings_to_bold(html_block_ends_list_before_fence) == ( "- intro\n
    \nhtml\n
    \n\n ~~~\n # literal\n# still code" ) html_comment_ends_list_before_fence = ( "- intro\n\n ~~~\n # literal\n# still code" ) assert commonmark_headings_to_bold( html_comment_ends_list_before_fence ) == ("- intro\n\n ~~~\n # literal\n# still code") # A backtick in a backtick fence's info string makes the opener invalid. invalid_backtick_info_string_not_a_fence = ( "- intro\n ```bad`info\nlazy\n ~~~\n # literal\n# real" ) assert commonmark_headings_to_bold( invalid_backtick_info_string_not_a_fence ) == ("- intro\n ```bad`info\nlazy\n ~~~\n # literal\n**real**") # Four extra columns inside a two-column list create indented code. six_space_indent_not_a_fence = ( "- intro\n ```\nlazy\n ~~~\n # literal\n# real" ) assert commonmark_headings_to_bold(six_space_indent_not_a_fence) == ( "- intro\n ```\nlazy\n ~~~\n # literal\n**real**" ) # A blank line ends a blockquote fence but may remain in a plain list. blank_line_ends_blockquote_fence = "> ~~~\n> code\n\n> # real" assert commonmark_headings_to_bold(blank_line_ends_blockquote_fence) == ( "> ~~~\n> code\n\n> **real**" ) # A fence may use up to three extra columns inside an active list. fence_with_extra_slack_stays_in_list = ( "1. item\n ~~~\n # literal\n ~~~\n# real" ) assert commonmark_headings_to_bold( fence_with_extra_slack_stays_in_list ) == ("1. item\n ~~~\n # literal\n ~~~\n**real**") # Active-list indentation can identify a heading without another marker. assert commonmark_headings_to_bold("- item\n # nested") == ( "- item\n **nested**" ) assert commonmark_headings_to_bold("- item\n\t# nested") == ( "- item\n\t**nested**" ) # Content inside an HTML block passes through unchanged. heading_inside_html_block_untouched = "
    \n# literal\n
    " assert ( commonmark_headings_to_bold(heading_inside_html_block_untouched) == heading_inside_html_block_untouched ) # Fence-looking text inside HTML must not consume the following document. fence_look_alike_inside_html_block = "
    \n~~~\n
    \n\n# real" assert ( commonmark_headings_to_bold(fence_look_alike_inside_html_block) == "
    \n~~~\n
    \n\n**real**" ) # A lowercase CDATA look-alike is ordinary text. lowercase_cdata_is_not_html_block = ( "- intro\n " * 9 + "# real" assert commonmark_headings_to_bold(heading_past_old_depth_cap) == ( "> " * 9 + "**real**" ) # An HTML block is recognized even after an active blockquote prefix, # not just at the very start of a line. html_block_inside_blockquote = ">
    \n> # literal\n>
    " assert ( commonmark_headings_to_bold(html_block_inside_blockquote) == html_block_inside_blockquote ) # A tag-looking line inside a real fence is literal fenced content, # not an HTML block start -- it must not swallow what follows the # fence's own close. html_look_alike_inside_fence = "~~~\n\ncontent\n\nafter\n" "\n# real" ) assert commonmark_headings_to_bold(raw_tag_requires_exact_close) == ( "\nafter\n" "\n**real**" ) # A heading between two same-length backtick runs must not look like # a code span spanning across it -- block structure is resolved # before inline code-span pairing. backtick_run_does_not_cross_heading = "before ``\n# real\nafter ``" assert commonmark_headings_to_bold( backtick_run_does_not_cross_heading ) == ("before ``\n**real**\nafter ``") # Type 7: a complete tag for any other name, alone on its own line, # starts an HTML block too -- but only when not interrupting an # already-open paragraph. custom_tag_at_document_start_protects_content = ( "\n# literal\n" ) assert ( commonmark_headings_to_bold( custom_tag_at_document_start_protects_content ) == custom_tag_at_document_start_protects_content ) custom_tag_cannot_interrupt_paragraph = "some text\n\n# real" assert commonmark_headings_to_bold( custom_tag_cannot_interrupt_paragraph ) == ("some text\n\n**real**") # A space before the self-closing slash makes this an invalid tag. malformed_self_close_not_a_tag = "\n# real" assert commonmark_headings_to_bold(malformed_self_close_not_a_tag) == ( "\n**real**" ) # A ">" inside a quoted attribute does not end the tag early. quoted_attribute_value_with_gt = '\n# literal' assert ( commonmark_headings_to_bold(quoted_attribute_value_with_gt) == quoted_attribute_value_with_gt ) # Any raw-tag closer ends a type-1 block, even if its name differs. raw_tag_close_need_not_match_open = "\nafter" close = text.index("") + len("") assert commonmark_module._commonmark_html_block_spans(text) == [ (0, close + 1) ] # A comment closes at its own terminator, wherever it appears. text = "\nafter" close = text.index("-->") + len("-->") assert commonmark_module._commonmark_html_block_spans(text) == [ (0, close + 1) ] # An unterminated comment runs to the end of the text. text = "\nafter" spans = commonmark_module._commonmark_leaf_block_spans(text) assert spans == [(0, len("> \n"), "html")] # When the quote holds all the way through and no terminator ever # appears, the block runs to the end of the text. text = ">