Debian Codegraph @

tests/test_conversion.py

raw symbols SCIP
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 from inspect import cleandoc
29
30 # Disable logging for a cleaner testing output
31 import logging
32 from timeit import default_timer
33
34 import pytest
35
36 from apprise import NotifyFormat
37 from apprise.conversion import (
38 BLOCKQUOTE_DEPTH_MAX,
39 LIST_DEPTH_MAX,
40 MAX_FRAME_DEPTH,
41 HTMLMarkdownConverter,
42 build_backtick_run_index,
43 convert_between,
44 find_unescaped_run,
45 )
46
47 logging.disable(logging.CRITICAL)
48
49
50 def test_conversion_html_to_text():
51 """conversion: Test HTML to plain text"""
52
53 def to_html(body):
54 """A function to simply html conversion tests."""
55 return convert_between(NotifyFormat.HTML, NotifyFormat.TEXT, body)
56
57 assert to_html("No HTML code here.") == "No HTML code here."
58
59 clist = to_html("<ul><li>Lots and lots</li><li>of lists.</li></ul>")
60 assert "Lots and lots" in clist
61 assert "of lists." in clist
62
63 assert "To be or not to be." in to_html(
64 "<blockquote>To be or not to be.</blockquote>"
65 )
66
67 cspace = to_html(
68 "<h2>Fancy heading</h2><p>And a paragraph too.<br>Plus line break.</p>"
69 )
70 assert "Fancy heading" in cspace
71 assert "And a paragraph too.\nPlus line break." in cspace
72
73 assert (
74 to_html(
75 "<style>body { font: 200%; }</style>"
76 "<p>Some obnoxious text here.</p>"
77 )
78 == "Some obnoxious text here."
79 )
80
81 assert (
82 to_html("<p>line 1</p><p>line 2</p><p>line 3</p>")
83 == "line 1\nline 2\nline 3"
84 )
85
86 # Case sensitivity
87 assert (
88 to_html("<p>line 1</P><P>line 2</P><P>line 3</P>")
89 == "line 1\nline 2\nline 3"
90 )
91
92 # double new lines (testing <br> and </br>)
93 assert (
94 to_html("some information<br/><br>and more information")
95 == "some information\n\nand more information"
96 )
97
98 #
99 # Test bad tags
100 #
101
102 # first 2 entries are okay, but last will do as best as it can
103 assert (
104 to_html("<p>line 1</><p>line 2</gar><p>line 3>")
105 == "line 1\nline 2\nline 3>"
106 )
107
108 # Make sure we ignore fields that aren't important to us
109 assert (
110 to_html(
111 "<script>ignore this</script>"
112 "<p>line 1</p>"
113 "Another line without being enclosed"
114 )
115 == "line 1\nAnother line without being enclosed"
116 )
117
118 # Test cases when there are no new lines (we're dealing with just inline
119 # entries); an empty entry as well
120 assert (
121 to_html("<span></span<<span>test</span> <a href='#'>my link</a>")
122 == "test my link"
123 )
124
125 # </p> missing
126 assert (
127 to_html(
128 "<body><div>line 1 <b>bold</b></div> "
129 " <a href='#'>my link</a>"
130 "<p>3rd line</body>"
131 )
132 == "line 1 bold\nmy link\n3rd line"
133 )
134
135 # <hr/> on it's own
136 assert to_html("<hr/>") == "---"
137 assert to_html("<hr>") == "---"
138
139 # We need to handle HTML Encodings
140 assert (
141 to_html("""
142 <html>
143 <title>ignore this entry</title>
144 <body>
145 Let&apos;s handle&nbsp;special html encoding
146 <hr/>
147 </body>
148 """)
149 == "Let's handle special html encoding\n---"
150 )
151
152 # If you give nothing, you get nothing in return
153 assert to_html("") == ""
154
155 # Special case on HR tag
156 assert (
157 to_html("""
158 <html>
159 <head></head>
160 <body>
161 <p><b>FROM: </b>[email protected]
162 <[email protected]></p>
163 Hi!<br/>
164 How are you?<br/>
165 <font color=3D"#FF0000">red font</font>
166 <a href=3D"http://www.python.org">link</a> you wanted.<br/>
167 </body>
168 </html>
169 """)
170 == "FROM: [email protected]\nHi!\n How are you?\n red font"
171 " link you wanted."
172 )
173
174 assert (
175 to_html("""
176 <html>
177 <head></head>
178 <body>
179 <p><b>FROM: </b>[email protected]
180 <[email protected]><hr></p>
181 Hi!<br/>
182 How are you?<br/>
183 <font color=3D"#FF0000">red font</font>
184 <a href=3D"http://www.python.org">link</a> you wanted.<br/>
185 </body>
186 </html>
187 """)
188 == "FROM: [email protected]\n---\nHi!\n How are you?\n red"
189 " font link you wanted."
190 )
191
192 # Special case on HR if text is sorrunded by HR tags
193 # its created a dict element
194 assert (
195 to_html("""
196 <html>
197 <head></head>
198 <body>
199 <p><hr><b>FROM: </b>[email protected]
200 <[email protected]><hr></p>
201 Hi!<br/>
202 How are you?<br/>
203 <font color=3D"#FF0000">red font</font>
204 <a href=3D"http://www.python.org">link</a> you wanted.<br/>
205 </body>
206 </html>
207 """)
208 == "---\nFROM: [email protected]\n---\nHi!\n How are you?\n"
209 " red font link you wanted."
210 )
211
212 assert (
213 to_html("""
214 <html>
215 <head></head>
216 <body>
217 <p>
218 <hr><b>TEST</b><hr>
219 </p>
220 Hi!<br/>
221 How are you?<br/>
222 <font color=3D"#FF0000">red font</font>
223 <a href=3D"http://www.python.org">link</a> you wanted.<br/>
224 </body>
225 </html>
226 """)
227 == "---\nTEST\n---\nHi!\n How are you?\n red font link you wanted."
228 )
229
230 with pytest.raises(TypeError):
231 # Invalid input
232 assert to_html(None)
233
234 with pytest.raises(TypeError):
235 # Invalid input
236 assert to_html(42)
237
238 with pytest.raises(TypeError):
239 # Invalid input
240 assert to_html(object)
241
242
243 def test_conversion_html_to_markdown():
244 """Test basic HTML-to-Markdown conversion."""
245
246 def to_md(body):
247 """Wrapper to simplify html-to-markdown conversion tests."""
248 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
249
250 # Plain text with no HTML passes through unchanged
251 assert to_md("No HTML code here.") == "No HTML code here."
252
253 # Empty string in, empty string out
254 assert to_md("") == ""
255
256 # Paragraphs need a full blank line between them.
257 assert (
258 to_md("<p>line 1</p><p>line 2</p><p>line 3</p>")
259 == "line 1\n\nline 2\n\nline 3"
260 )
261
262 # Case sensitivity -- tag names are case-insensitive in HTML
263 assert (
264 to_md("<p>line 1</P><P>line 2</P><P>line 3</P>")
265 == "line 1\n\nline 2\n\nline 3"
266 )
267
268 # HTMLParser lowercases ALL tag names -- inline tags included
269 assert to_md("<B>bold text</B>") == "**bold text**"
270 assert to_md("<I>italic</I>") == "*italic*"
271
272 # Uppercase self-closing <BR/> tags also produce CommonMark hard breaks.
273 assert (
274 to_md("line one<BR/>line two<BR />line three")
275 == "line one \nline two \nline three"
276 )
277
278 # <br> and self-closing <br/> both emit a hard break
279 assert (
280 to_md("some information<br/><br>and more information")
281 == "some information \n \nand more information"
282 )
283
284 # Each heading level maps to the correct number of # characters
285 assert to_md("<h1>Heading 1</h1>") == "# Heading 1"
286 assert to_md("<h2>Heading 2</h2>") == "## Heading 2"
287 assert to_md("<h3>Heading 3</h3>") == "### Heading 3"
288 assert to_md("<h4>Heading 4</h4>") == "#### Heading 4"
289 assert to_md("<h5>Heading 5</h5>") == "##### Heading 5"
290 assert to_md("<h6>Heading 6</h6>") == "###### Heading 6"
291
292 # Multiple headings and paragraphs together
293 assert to_md(
294 "<h1>Heading 1</h1>"
295 "<h2>Heading 2</h2>"
296 "<h3>Heading 3</h3>"
297 "<h4>Heading 4</h4>"
298 "<h5>Heading 5</h5>"
299 "<h6>Heading 6</h6>"
300 "<p>line 1</>"
301 "<p><em>line 2</em></gar>"
302 "<p>line 3>"
303 ) == (
304 "# Heading 1\n## Heading 2\n### Heading 3\n"
305 "#### Heading 4\n##### Heading 5\n###### Heading 6\n\n"
306 "line 1\n\n*line 2*\n\nline 3\\>"
307 )
308
309 # <b> and <strong> both produce bold markers
310 assert to_md("<b>bold text</b>") == "**bold text**"
311 assert to_md("<strong>bold text</strong>") == "**bold text**"
312
313 # <i> and <em> both produce italic markers
314 assert to_md("<i>italic</i>") == "*italic*"
315 assert to_md("<em>italic</em>") == "*italic*"
316
317 # Angle destinations prevent parentheses in an href from ending links.
318 assert (
319 to_md(
320 "<body><div>line 1 <b>bold</b></div> "
321 " <a href='/link'>my link</a>"
322 "<p>3rd line</body>"
323 )
324 == "line 1 **bold**\n\n[my link](</link>)\n\n3rd line"
325 )
326
327 # <a href="..."> produces Markdown link syntax
328 assert (
329 to_md("<span></span<<span>test</span> <a href='#'>my link</a>")
330 == "test [my link](<#>)"
331 )
332
333 # <a> with nested inline markup -- the href must survive the child tags
334 assert to_md("<a href='/x'><b>hello</b> world</a>") == (
335 "[**hello** world](</x>)"
336 )
337 assert to_md("<a href='/x'><strong>label</strong></a>") == (
338 "[**label**](</x>)"
339 )
340 assert (
341 to_md("<a href='/x'><em>italic</em> and plain</a>")
342 == "[*italic* and plain](</x>)"
343 )
344
345 # Nested <a> -- inner href wins for its own span; outer wraps the rest
346 assert (
347 to_md("<a href='/outer'>text <a href='/inner'>link</a></a>")
348 == "[text [link](</inner>)](</outer>)"
349 )
350
351 # <a> with no href attribute -- content rendered as plain text
352 assert to_md("<span>test</span> <a>no link</a>") == "test no link"
353
354 # Bare <a name="..."> anchor (no href) -- text passes through unchanged
355 assert to_md("<a name='top'>jump target</a>") == "jump target"
356
357 # <span> is inline -- it passes text through without a newline; <div> is
358 # block-level and paragraph-like, so it adds a blank line.
359 assert to_md("<div>block</div><span>inline</span>") == "block\n\ninline"
360
361 # HTML comments are stripped entirely; surrounding text is preserved
362 assert to_md("<!-- comment --> text") == "text"
363 assert to_md("a<!-- c1 -->b<!-- c2 -->c") == "abc"
364
365 # <![CDATA[...]]> sections are gracefully ignored (content is dropped, text
366 # outside the CDATA boundary is kept)
367 assert to_md("text<![CDATA[data]]> here") == "text here"
368 assert to_md("<![CDATA[data]]>text") == "text"
369
370 # Inline <code> wraps in backticks without a block boundary
371 assert to_md("<code>func()</code>") == "`func()`"
372
373 # Markdown special characters inside <code> are NOT escaped -- backtick
374 # delimiters already make content literal
375 assert to_md("<code>x*2 and #tag</code>") == "`x*2 and #tag`"
376
377 # <pre> produces a fenced code block
378 assert to_md("<pre>line a\nline b</pre>") == "```\nline a\nline b\n```"
379
380 # <samp> is treated the same as <pre> (fenced block)
381 assert to_md("<samp>output\nhere</samp>") == "```\noutput\nhere\n```"
382
383 # Inline code followed immediately by a pre block
384 assert to_md(
385 "<code>multi-line 1\nmulti-line 2</code>more content"
386 "<pre>multi-line 1\nmulti-line 2</pre>more content"
387 ) == (
388 "`multi-line 1\nmulti-line 2`more content"
389 "\n```\nmulti-line 1\nmulti-line 2\n```\nmore content"
390 )
391
392 # Unordered lists produce "- " prefixed items
393 result = to_md("<ul><li>Lots and lots</li><li>of lists.</li></ul>")
394 assert "- Lots and lots" in result
395 assert "- of lists." in result
396
397 assert (
398 to_md("<blockquote>To be or not to be.</blockquote>")
399 == "> To be or not to be."
400 )
401
402 # Standalone <hr/> produces just "---"
403 assert to_md("<hr/>") == "---"
404 assert to_md("<hr>") == "---"
405
406 # <style> content is suppressed
407 assert (
408 to_md(
409 "<style>body { font: 200%; }</style>"
410 "<p>Some obnoxious text here.</p>"
411 )
412 == "Some obnoxious text here."
413 )
414
415 # <script> content is suppressed
416 assert (
417 to_md(
418 "<script>ignore this</script>"
419 "<p>line 1</p>"
420 "Another line without being enclosed"
421 )
422 == "line 1\n\nAnother line without being enclosed"
423 )
424
425 # '*' outside code is escaped so it does not trigger emphasis
426 assert to_md("<p>price: 5 * 3</p>") == r"price: 5 \* 3"
427
428 # '#' outside code is escaped so it does not trigger a heading
429 assert to_md("<p>Tag #1</p>") == r"Tag \#1"
430
431 # Backtick outside code is escaped
432 assert to_md("<p>Use `func`</p>") == r"Use \`func\`"
433
434 assert (
435 to_md(
436 """
437 <html>
438 <title>ignore this entry</title>
439 <body>
440 Let&apos;s handle&nbsp;special html encoding
441 <hr/>
442 </body>
443 """
444 )
445 == "Let's handle special html encoding\n\n---"
446 )
447
448 # Missing </p> is handled gracefully
449 assert (
450 to_md(
451 "<h2>Heading</h2><p>And a paragraph too.<br>Plus line break.</p>"
452 )
453 == "## Heading\n\nAnd a paragraph too. \nPlus line break."
454 )
455
456 with pytest.raises(TypeError):
457 to_md(None)
458
459 with pytest.raises(TypeError):
460 to_md(42)
461
462 with pytest.raises(TypeError):
463 to_md(object)
464
465
466 def test_conversion_html_to_markdown_lists():
467 """Test list nesting and numbering."""
468
469 def to_md(body):
470 """Wrapper to simplify html-to-markdown conversion tests."""
471 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
472
473 # Flat unordered list
474
475 assert (
476 to_md("<ul><li>alpha</li><li>beta</li><li>gamma</li></ul>")
477 == "- alpha\n- beta\n- gamma"
478 )
479
480 # Flat ordered list with auto-incrementing counter
481
482 assert (
483 to_md("<ol><li>first</li><li>second</li><li>third</li></ol>")
484 == "1. first\n2. second\n3. third"
485 )
486
487 # <ol start=> shifts where the auto-incrementing counter begins
488 assert to_md('<ol start="4"><li>a</li><li>b</li></ol>') == "4. a\n5. b"
489 assert to_md('<ol start="0"><li>a</li></ol>') == "0. a"
490
491 # CommonMark list markers cannot represent negative starting values.
492 assert to_md('<ol start="-3"><li>a</li><li>b</li></ol>') == "0. a\n1. b"
493
494 # A non-numeric start is ignored, same as no attribute at all
495 assert to_md('<ol start="abc"><li>a</li></ol>') == "1. a"
496
497 # <li value=> resets the counter for that item and every sibling after it
498 assert to_md('<ol><li value="5">a</li><li>b</li></ol>') == "5. a\n6. b"
499 assert (
500 to_md('<ol><li>a</li><li value="10">b</li><li>c</li></ol>')
501 == "1. a\n10. b\n11. c"
502 )
503 assert to_md('<ol><li value="-5">a</li><li>b</li></ol>') == "0. a\n1. b"
504
505 # A non-numeric value is ignored too -- the counter just keeps incrementing
506 # normally, same as if the attribute weren't there
507 assert to_md('<ol><li value="abc">a</li><li>b</li></ol>') == "1. a\n2. b"
508
509 # Nested unordered lists (2 levels)
510
511 assert (
512 to_md(
513 "<ul><li>top A<ul><li>nested A</li></ul></li><li>top B</li></ul>"
514 )
515 == "- top A\n - nested A\n- top B"
516 )
517
518 # Nested unordered lists (3 levels)
519
520 assert (
521 to_md("<ul><li>L1<ul><li>L2<ul><li>L3</li></ul></li></ul></li></ul>")
522 == "- L1\n - L2\n - L3"
523 )
524
525 # Mixed nesting: ol inside ul
526
527 assert (
528 to_md(
529 "<ul>"
530 "<li>intro<ol>"
531 "<li>step one</li>"
532 "<li>step two</li>"
533 "</ol></li>"
534 "</ul>"
535 )
536 == "- intro\n 1. step one\n 2. step two"
537 )
538
539 # Mixed nesting: ul inside ol
540
541 assert (
542 to_md(
543 "<ol>"
544 "<li>first<ul>"
545 "<li>sub A</li>"
546 "<li>sub B</li>"
547 "</ul></li>"
548 "<li>second</li>"
549 "</ol>"
550 )
551 == "1. first\n - sub A\n - sub B\n2. second"
552 )
553
554 # Malformed HTML: missing </li> in a <ul> HTMLParser does not synthesize
555 # implicit close events; each missing </li> is simply absent, but the next.
556 assert (
557 to_md("<ul><li>item A<li>item B<li>item C</ul>")
558 == "- item A\n- item B\n- item C"
559 )
560
561 # Without </li>, ordered-list counters cannot advance.
562 assert (
563 to_md("<ol><li>one<li>two<li>three</ol>") == "1. one\n1. two\n1. three"
564 )
565
566 # Malformed HTML: missing closing </ul>
567
568 assert to_md("<ul><li>item A</li><li>item B</li>") == "- item A\n- item B"
569
570 # Malformed HTML: missing </li> AND missing </ul>
571
572 assert to_md("<ul><li>item A<li>item B") == "- item A\n- item B"
573
574 # Malformed HTML: bare text inside <ul> (no <li> wrapper) <ul> is in
575 # IGNORE_TAGS so unwrapped text is suppressed entirely
576 assert to_md("<ul>bare text</ul>") == ""
577
578 # <code> inside <li>: inline code preserved with backticks
579
580 assert (
581 to_md("<ul><li>run <code>cmd --flag</code> now</li></ul>")
582 == "- run `cmd --flag` now"
583 )
584
585 # Markdown special characters inside <code> are NOT escaped
586 assert (
587 to_md("<ul><li>see <code>x*2 #tag</code></li></ul>")
588 == "- see `x*2 #tag`"
589 )
590
591 # Fenced blocks retain content and list indentation.
592 assert (
593 to_md("<ul><li>code:<pre> indented\n here</pre></li></ul>")
594 == "- code:\n ```\n indented\n here\n ```"
595 )
596
597 # Nested fenced blocks combine content indentation with list indentation.
598 assert (
599 to_md(
600 "<ul><li>outer<ul><li>inner:<pre> x = 1</pre></li></ul></li></ul>"
601 )
602 == "- outer\n - inner:\n ```\n x = 1\n ```"
603 )
604
605 # A first-child block shares the list marker's line.
606
607 # Single item with a <p> first child
608 assert to_md("<ul><li><p>alpha</p></li></ul>") == "- alpha"
609
610 # Multiple items each with a <p> first child.
611 assert (
612 to_md("<ul><li><p>alpha</p></li><li><p>beta</p></li></ul>")
613 == "- alpha\n\n- beta"
614 )
615
616 # Multiple <p> children inside one <li>
617 assert to_md("<ul><li><p>one</p><p>two</p></li></ul>") == "- one\n\n two"
618
619 # Mixed: direct text for first item, <p> for second.
620 assert (
621 to_md("<ul><li>direct</li><li><p>wrapped</p></li></ul>")
622 == "- direct\n- wrapped"
623 )
624
625 # Numbered list with <p> children
626 assert (
627 to_md("<ol><li><p>first</p></li><li><p>second</p></li></ol>")
628 == "1. first\n\n2. second"
629 )
630
631 # <a> link as first child of <li> -- the marker must share the line
632 assert to_md("<ul><li><a href='/x'>link</a></li></ul>") == "- [link](</x>)"
633
634 # <a> with nested markup as first (and only) child of <li>
635 assert (
636 to_md("<ul><li><a href='/x'><b>bold link</b></a></li></ul>")
637 == "- [**bold link**](</x>)"
638 )
639
640 # <a> link followed by a <p> sibling inside the same <li>.
641 assert (
642 to_md("<ul><li><a href='/x'>link</a><p>more</p></li></ul>")
643 == "- [link](</x>)\n\n more"
644 )
645
646
647 def test_conversion_html_to_markdown_escaping():
648 """Test Markdown escaping."""
649
650 def to_md(body):
651 """Wrapper to simplify html-to-markdown conversion tests."""
652 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
653
654 # Embedded backticks widen code delimiters.
655 assert to_md("<code>a`b</code>") == "``a`b``"
656
657 # Content starting or ending with a backtick gets a padding space, per
658 # CommonMark's code-span disambiguation rule
659 assert to_md("<code>`x</code>") == "`` `x ``"
660 assert to_md("<code>x`</code>") == "`` x` ``"
661
662 # A run of 3 backticks inside <pre> widens the fence past 3
663 assert to_md("<pre>boom```</pre>") == "````\nboom```\n````"
664
665 # Plain content with no backticks still uses the minimal delimiter
666 assert to_md("<pre>x</pre>") == "```\nx\n```"
667
668 # Ignored containers suppress both text and Markdown markers.
669 assert (
670 to_md(
671 "<html><head><b>ignore</b></head><body><p>keep</p></body></html>"
672 )
673 == "keep"
674 )
675
676 # A heading marker ("# ") must not leak from a suppressed container
677 assert (
678 to_md("<head><h1>hidden heading</h1></head><body>text</body>")
679 == "text"
680 )
681
682 # A list marker ("- ") must not leak from a <li> nested inside a suppressed
683 # container, even though <li> normally re-enables storage
684 assert (
685 to_md("<head><ul><li>hidden item</li></ul></head><body>text</body>")
686 == "text"
687 )
688
689 # <script> content (already suppressed) must not leak nested markers
690 assert to_md("<script>ignore <b>this</b></script><p>keep</p>") == "keep"
691
692 # A <pre> block fully inside a suppressed container emits nothing, not even
693 # an empty fence
694 assert to_md("<script>ignore<pre>code</pre></script><p>keep</p>") == "keep"
695
696 # Angle destinations preserve whitespace in link targets.
697 assert to_md("<a href='/my page'>link</a>") == "[link](</my page>)"
698
699 # Nested tags are inert inside preformatted content.
700 assert (
701 to_md("<pre>before <a href='/x'>link</a> after</pre>")
702 == "```\nbefore link after\n```"
703 )
704 assert (
705 to_md("<code>before <b>bold</b> after</code>") == "`before bold after`"
706 )
707
708 # Stray code/pre/samp close tags
709 assert to_md("</code>text") == "text"
710 assert to_md("</pre>text") == "text"
711 assert to_md("</samp>text") == "text"
712
713 # Markdown/HTML injection via plain text content
714 assert (
715 to_md("<p>Click [here](https://evil.example.com) now</p>")
716 == r"Click \[here\]\(https://evil.example.com\) now"
717 )
718 assert (
719 to_md("<p>An image ![x](https://evil.example.com/x.png) too</p>")
720 == r"An image \!\[x\]\(https://evil.example.com/x.png\) too"
721 )
722
723 # A literal backslash must itself be escaped
724 assert to_md("<p>back\\*slash</p>") == r"back\\\*slash"
725
726 # '_' (CommonMark's other emphasis delimiter) and '~' (GFM/chat- dialect
727 # strikethrough) are escaped unconditionally, the same as '*'.
728 assert to_md("<p>_literal_</p>") == r"\_literal\_"
729 assert to_md("<p>my_variable_name</p>") == r"my\_variable\_name"
730 assert to_md("<p>~strikethrough~</p>") == r"\~strikethrough\~"
731
732 # Entity-encoded HTML (decoded to literal "<"/">" text by the parser) must
733 # not survive into the Markdown output unescaped
734 assert (
735 to_md("<p>previously &lt;script&gt;alert(1)&lt;/script&gt;</p>")
736 == r"previously \<script\>alert\(1\)\</script\>"
737 )
738
739 # href cannot break out of the link destination
740 assert to_md(
741 '<a href="https://safe.example.com)[FAKE](https://evil.example.com/p)">'
742 "legit link</a>"
743 ) == (
744 "[legit link]"
745 "(<https://safe.example.com)[FAKE](https://evil.example.com/p)>)"
746 )
747
748 # A '<' or '>' inside the href itself must be escaped, since both are
749 # meaningful within the angle-bracket destination form.
750 assert to_md('<a href="https://x.example.com/<script>">y</a>') == (
751 r"[y](<https://x.example.com/\<script\>>)"
752 )
753
754 # Strip line endings before placing a URL in an angle-bracket destination.
755 assert (
756 to_md('<a href="https://safe/x\n\n# injected">click</a>')
757 == "[click](<https://safe/x# injected>)"
758 )
759
760 # Neutralize schemes that can execute content or expose local files.
761 assert to_md('<a href="javascript:alert(1)">click me</a>') == (
762 "[click me](<#>)"
763 )
764 assert to_md('<a href="data:text/html,x">click</a>') == "[click](<#>)"
765 assert to_md('<a href="vbscript:msgbox(1)">click</a>') == "[click](<#>)"
766 assert to_md('<a href="file:///etc/passwd">click</a>') == "[click](<#>)"
767 assert to_md('<a href="JaVaScRiPt:alert(1)">click</a>') == "[click](<#>)"
768
769 # Leading/trailing whitespace must not defeat scheme detection\
770 assert to_md('<a href=" javascript:alert(1)">click</a>') == (
771 "[click](<#>)"
772 )
773 assert to_md('<a href=" \tjavascript:alert(1)">click</a>') == (
774 "[click](<#>)"
775 )
776 assert to_md('<a href="javascript:alert(1) ">click</a>') == (
777 "[click](<#>)"
778 )
779
780 # BiDi override/embedding characters must not defeat scheme detection.
781 assert to_md('<a href="‮javascript:alert(1)">click</a>') == ("[click](<#>)")
782 assert to_md('<a href="‪javascript:alert(1)">click</a>') == ("[click](<#>)")
783 # U+2066 (LEFT-TO-RIGHT ISOLATE) must also be stripped.
784 assert to_md('<a href="⁦javascript:alert(1)">click</a>') == ("[click](<#>)")
785
786 # Keep legitimate app-specific schemes that are not explicitly unsafe.
787 assert to_md('<a href="https://example.com">x</a>') == (
788 "[x](<https://example.com>)"
789 )
790 assert to_md('<a href="mailto:[email protected]">x</a>') == (
791 "[x](<mailto:[email protected]>)"
792 )
793 assert to_md('<a href="tel:+15551234567">x</a>') == (
794 "[x](<tel:+15551234567>)"
795 )
796 assert to_md('<a href="sms:+15551234567">x</a>') == (
797 "[x](<sms:+15551234567>)"
798 )
799 assert to_md('<a href="geo:37.7,-122.4">x</a>') == (
800 "[x](<geo:37.7,-122.4>)"
801 )
802 assert to_md('<a href="msteams:meeting?id=123">x</a>') == (
803 "[x](<msteams:meeting?id=123>)"
804 )
805 assert to_md('<a href="sharepoint://site/doc">x</a>') == (
806 "[x](<sharepoint://site/doc>)"
807 )
808 assert to_md('<a href="/relative/path">x</a>') == ("[x](</relative/path>)")
809 assert to_md('<a href="#anchor">x</a>') == "[x](<#anchor>)"
810
811
812 def test_conversion_html_to_markdown_line_start_escaping():
813 """Test block syntax escaping."""
814
815 def to_md(body):
816 """Wrapper to simplify html-to-markdown conversion tests."""
817 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
818
819 # Escape ordered-list-shaped text only at the start of a line.
820 assert to_md("<p>1. Apples</p><p>2. Oranges</p>") == (
821 "1\\. Apples\n\n2\\. Oranges"
822 )
823 assert to_md("<p>23. done</p>") == "23\\. done"
824
825 # Match bullet markers at the start of a line.
826 assert to_md("<p>- not a bullet, just a dash</p>") == (
827 "\\- not a bullet, just a dash"
828 )
829 assert to_md("<p>+ plus sign list?</p>") == "\\+ plus sign list?"
830
831 # Escape repeated dashes that could become a thematic break.
832 assert to_md("<p>Some text</p><p>---</p><p>more text</p>") == (
833 "Some text\n\n\\---\n\nmore text"
834 )
835
836 # Escaping the first dash is enough to prevent a thematic break.
837 rendered = convert_between(
838 NotifyFormat.MARKDOWN,
839 NotifyFormat.HTML,
840 to_md("<p>Some text</p><p>---</p><p>more text</p>"),
841 )
842 assert "<hr" not in rendered
843 assert "<h1" not in rendered
844 assert "<h2" not in rendered
845 assert "---" in rendered
846
847 assert to_md("<p>***</p>") == "\\*\\*\\*"
848 assert to_md("<p>___</p>") == "\\_\\_\\_"
849 assert to_md("<p>- - -</p>") == "\\- - -"
850 assert to_md("<p>Hello world<br>===</p>") == "Hello world \n\\==="
851 assert to_md("<p>Heading<br>---</p>") == "Heading \n\\---"
852
853 # None of this is ambiguous -- and so isn't escaped -- anywhere other than
854 # a true line start
855 assert to_md("<p>well-known v1.2 it is not - really</p>") == (
856 "well-known v1.2 it is not - really"
857 )
858 assert to_md("<p>price is $5.00</p>") == "price is $5.00"
859 assert to_md("<p>a-b-c</p>") == "a-b-c"
860 assert to_md("<p>5 - 3 = 2</p>") == "5 - 3 = 2"
861
862
863 def test_conversion_html_to_markdown_hardening():
864 """Test malformed stack input."""
865
866 def to_md(body):
867 """Wrapper to simplify html-to-markdown conversion tests."""
868 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
869
870 # Stray close tags before any matching open tag
871
872 # </ul> and </ol> take the early-return path in handle_endtag
873 assert to_md("</ul>text") == "text"
874 assert to_md("</ol>text") == "text"
875
876 # </li> finds no open <li> anywhere on the stack and is a no-op -- the
877 # text that follows is unindented and stored normally
878 assert to_md("</li>text") == "text"
879
880 # Multiple stray close tags in a row must not crash or corrupt state
881 assert to_md("</ul></ol></li>preamble") == "preamble"
882
883 # A valid list after a stray close must still render correctly
884 assert to_md("</ul><ul><li>A</li><li>B</li></ul>") == "- A\n- B"
885
886 # A stray close tag with content on BOTH sides must be a complete no-op,
887 # not just absorbed because nothing preceded it.
888 assert to_md("a</ul>b") == "ab"
889 assert to_md("a</ol>b") == "ab"
890 assert to_md("a</li>b") == "ab"
891 assert to_md("a</blockquote>b") == "ab"
892 assert to_md("a</td>b") == "ab"
893 assert to_md("a</th>b") == "ab"
894
895 # A stray <td>/<th> close still falls through cleanly when content follows.
896 assert to_md("<p>a</td>b</p>") == "ab"
897
898 # _make_frame() empty-stack guard
899 conv = HTMLMarkdownConverter()
900
901 # Force the stack empty -- this can only happen via direct attribute
902 # manipulation, never through the public parsing API
903 conv._stack = []
904 frame = conv._make_frame("div")
905
906 # The fallback defaults must match the root sentinel values
907 assert frame["tag"] == "div"
908 assert frame["do_store"] is True
909 assert frame["preserve_cr"] is False
910 assert frame["list_type"] is None
911 assert frame["depth"] == 0
912 assert frame["counter"] is None
913 assert frame["list_do_store"] is True
914
915 # A stale open-tag count must not corrupt the stack.
916 conv = HTMLMarkdownConverter()
917 conv._tag_open_counts["nonexistent"] = 1
918 conv._pop_to("nonexistent") # must not raise or corrupt state
919 assert len(conv._stack) == 1 # only the root sentinel remains
920
921 # ignore content found in head
922 assert (
923 to_md(
924 "<head>"
925 + "<ul>" * 50
926 + "<li>hidden</li>"
927 + "</ul>" * 50
928 + "</head><body>text</body>"
929 )
930 == "text"
931 )
932
933 # deep <ul> nesting still resolve correctly.
934 assert (
935 to_md("<ul>" * 50 + "<li>visible</li>" + "</ul>" * 50) == "- visible"
936 )
937
938 # List indentation is capped at LIST_DEPTH_MAX ---
939 assert LIST_DEPTH_MAX == 4
940
941 one_per_level = "<ul><li>x" * 10 + "</li></ul>" * 10
942 out = to_md(one_per_level)
943 lines = out.split("\n")
944 assert len(lines) == 10
945 # Indent grows for the first LIST_DEPTH_MAX levels...
946 assert lines[0] == "- x"
947 assert lines[1] == " - x"
948 assert lines[2] == " - x"
949 assert lines[3] == " - x"
950 # ...then holds steady for every level beyond the cap
951 for line in lines[4:]:
952 assert line == " - x"
953
954 # Performance: same shape, large enough that the old O(N^2)
955 n = 20000
956 deep = "<ul><li>x" * n + "</li></ul>" * n
957 start = default_timer()
958 out = to_md(deep)
959 elapsed = default_timer() - start
960 assert len(out) < 20 * n
961 # Generous bound: this must catch a real return to quadratic
962 # behavior, not just run fast on a quiet dev machine -- shared or
963 # emulated build infrastructure (e.g. a busy Koji builder) can be
964 # many times slower.
965 assert elapsed < 15.0
966
967 # Performance: many UNCLOSED <li> tags nested directly inside one another.
968 n = 20000
969 html = "<li>x" * n
970 start = default_timer()
971 out = to_md(html)
972 elapsed = default_timer() - start
973 assert len(out) < 10 * n # output itself is linear, not quadratic
974 # Generous bound -- see the note on the equivalent check above.
975 assert elapsed < 30.0
976
977 # Performance: many open <blockquote> tags followed by many closing tags of
978 # a *different* kind that's never actually open ("</pre>").
979 n = 20000
980 html = "<blockquote>" * n + "</pre>" * n
981 start = default_timer()
982 out = to_md(html)
983 elapsed = default_timer() - start
984 assert len(out) < 20 * n
985 # Generous bound: this must catch a real return to quadratic
986 # behavior, not just run fast on a quiet dev machine -- shared or
987 # emulated build infrastructure (e.g. a busy Koji builder) can be
988 # many times slower.
989 assert elapsed < 15.0
990
991 # Blockquote depth is capped at BLOCKQUOTE_DEPTH_MAX
992 assert BLOCKQUOTE_DEPTH_MAX == 4
993
994 # Each level is its own <p>, so every line of real content is followed by a
995 # blank (but still "> "-prefixed) separator line.
996 one_per_level = "<blockquote><p>x</p>" * 10 + "</blockquote>" * 10
997 out = to_md(one_per_level)
998 lines = out.split("\n")
999 assert len(lines) == 19
1000 content_lines = lines[0::2]
1001 separator_lines = lines[1::2]
1002 assert len(content_lines) == 10
1003 assert content_lines[0] == "> x"
1004 assert content_lines[1] == "> > x"
1005 assert content_lines[2] == "> > > x"
1006 assert content_lines[3] == "> > > > x"
1007 for line in content_lines[4:]:
1008 assert line == "> > > > x"
1009 # Each separator matches its preceding content line, minus the "x"
1010 for content, separator in zip(content_lines, separator_lines):
1011 assert separator == content[: -len("x")].rstrip()
1012
1013 n = 20000
1014 deep = "<blockquote><p>x</p>" * n + "</blockquote>" * n
1015 start = default_timer()
1016 out = to_md(deep)
1017 elapsed = default_timer() - start
1018 assert len(out) < 20 * n
1019 # Generous bound: this must catch a real return to quadratic
1020 # behavior, not just run fast on a quiet dev machine -- shared or
1021 # emulated build infrastructure (e.g. a busy Koji builder) can be
1022 # many times slower.
1023 assert elapsed < 15.0
1024
1025 # When emphasis or anchor tags are nested past MAX_FRAME_DEPTH, _push_frame
1026 # returns False and the opening delimiter must NOT be emitted.
1027 depth = MAX_FRAME_DEPTH + 1
1028 em_open = "<em>" * depth
1029 em_close = "</em>" * depth
1030 out_em = to_md(f"{em_open}text{em_close}")
1031 # The text must appear; no unmatched bare asterisk may leak through.
1032 assert "text" in out_em
1033 assert out_em.replace("*", "").strip() == "text"
1034
1035 # Same guard for <a> -- no unmatched "[" in the output.
1036 a_open = '<a href="https://example.com">' * depth
1037 a_close = "</a>" * depth
1038 out_a = to_md(f"{a_open}text{a_close}")
1039 assert "text" in out_a
1040 # Count "[" and "](" -- every "[" must have a matching "](".
1041 assert out_a.count("[") == out_a.count("](")
1042
1043 # At MAX_FRAME_DEPTH the <blockquote> frame is discarded and _push_frame
1044 # returns False.
1045 bq_open = "<blockquote>" * depth
1046 bq_close = "</blockquote>" * depth
1047 out_bq = to_md(f"{bq_open}text{bq_close}")
1048 assert "text" in out_bq
1049 # Every ">" line-prefix must correspond to a real nested blockquote level.
1050 first_line = out_bq.splitlines()[0] if out_bq else ""
1051 gt_count = len(first_line) - len(first_line.lstrip("> "))
1052 assert gt_count <= BLOCKQUOTE_DEPTH_MAX * 2 # ">" + " " per level
1053
1054 # At MAX_FRAME_DEPTH the <li> frame is discarded and _push_frame returns
1055 # False. No _ListMarker must be appended without a backing frame.
1056 li_open = "<ul>" + "<li>" * depth
1057 li_close = "</li>" * depth + "</ul>"
1058 out_li = to_md(f"{li_open}text{li_close}")
1059 assert "text" in out_li
1060
1061
1062 def test_conversion_html_to_markdown_blockquotes():
1063 """Test blockquote conversion."""
1064
1065 def to_md(body):
1066 """Wrapper to simplify html-to-markdown conversion tests."""
1067 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
1068
1069 # Single paragraph -- marker and content share the first line
1070 assert to_md("<blockquote><p>line1</p></blockquote>") == "> line1"
1071
1072 # Multiple paragraphs
1073 assert (
1074 to_md("<blockquote><p>line1</p><p>line2</p></blockquote>")
1075 == "> line1\n>\n> line2"
1076 )
1077 assert (
1078 to_md("<blockquote><p>a</p><p>b</p><p>c</p></blockquote>")
1079 == "> a\n>\n> b\n>\n> c"
1080 )
1081
1082 # A heading doesn't need that same blank-line treatment.
1083 assert (
1084 to_md("<blockquote><h2>Title</h2><p>body</p></blockquote>")
1085 == "> ## Title\n> body"
1086 )
1087
1088 # Inline-only content needs no internal prefixing -- it never hits a
1089 # boundary inside the quote in the first place
1090 assert (
1091 to_md("<blockquote>To be or not to be.</blockquote>")
1092 == "> To be or not to be."
1093 )
1094
1095 # Nested blockquotes accumulate one "> " per level, not per ancestor's full
1096 # cumulative prefix, which would double-count outer quote levels.
1097 assert (
1098 to_md("<blockquote><blockquote>nested</blockquote></blockquote>")
1099 == "> > nested"
1100 )
1101 assert to_md(
1102 "<blockquote><blockquote><p>a</p><p>b</p></blockquote></blockquote>"
1103 ) == ("> > a\n> >\n> > b")
1104
1105 # Bare text follows the same one-prefix-per-level rule.
1106 assert (
1107 to_md("<blockquote>outer<blockquote>inner</blockquote></blockquote>")
1108 == "> outer\n>\n> > inner"
1109 )
1110 assert to_md(
1111 "<blockquote>a<blockquote>b<blockquote>c</blockquote>"
1112 "</blockquote></blockquote>"
1113 ) == ("> a\n>\n> > b\n> >\n> > > c")
1114
1115 # The same text-then-nested-blockquote transition, once depth is already
1116 # clamped at BLOCKQUOTE_DEPTH_MAX, must not add yet another level.
1117 assert BLOCKQUOTE_DEPTH_MAX == 4
1118 capped = (
1119 "<blockquote>" * 4
1120 + "x<blockquote>y</blockquote>"
1121 + ("</blockquote>" * 4)
1122 )
1123 out = to_md(capped)
1124 assert "> > > > x" in out
1125 assert "> > > > > y" not in out
1126 assert "> > > > y" in out
1127
1128 # Content after a blockquote needs a full boundary without the quote
1129 # prefix.
1130 assert (
1131 to_md("<blockquote><p>line1</p></blockquote><p>after</p>")
1132 == "> line1\n\nafter"
1133 )
1134 assert (
1135 to_md("<p>before</p><blockquote><p>line1</p></blockquote>")
1136 == "before\n\n> line1"
1137 )
1138
1139 # An entirely empty blockquote (no children at all, nested or not) produces
1140 # no output.
1141 assert to_md("<blockquote></blockquote>") == ""
1142 assert to_md("<blockquote><blockquote></blockquote></blockquote>") == ""
1143
1144 # A blockquote entirely inside a suppressed context contributes nothing,
1145 # and does not disturb sibling content outside it
1146 assert (
1147 to_md(
1148 "<head><blockquote><p>hidden</p></blockquote></head>"
1149 "<body>text</body>"
1150 )
1151 == "text"
1152 )
1153
1154 # A blockquote following bare text still needs its own boundary.
1155 assert to_md("text<blockquote>quoted</blockquote>") == ("text\n\n> quoted")
1156 assert to_md("text<blockquote></blockquote>") == "text"
1157 assert to_md("<p>text<blockquote></blockquote></p>") == "text"
1158
1159
1160 def test_conversion_html_to_markdown_emphasis():
1161 """Test emphasis edge cases."""
1162
1163 def to_md(body):
1164 """Wrapper to simplify html-to-markdown conversion tests."""
1165 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
1166
1167 # Leading/trailing whitespace inside the tag must end up outside the
1168 # delimiters.
1169 assert to_md("<em> text </em>") == "*text*"
1170 assert to_md("<strong> bold </strong>") == "**bold**"
1171 assert to_md("<em> multi space </em>") == "*multi space*"
1172
1173 # Leading-only and trailing-only whitespace
1174 assert to_md("<em> text</em>") == "*text*"
1175 assert to_md("<em>text </em>") == "*text*"
1176
1177 # Relocating emphasis whitespace must not disturb surrounding text.
1178 assert (
1179 to_md("<p>Hello <strong> bold </strong> world</p>")
1180 == "Hello **bold** world"
1181 )
1182
1183 # Relocate trailing whitespace even when empty tags split the text
1184 # fragments.
1185 assert to_md("<strong>text<span></span> </strong>x") == "**text** x"
1186
1187 # Fully empty, or whitespace-only, spans contribute nothing at all -- not
1188 # even an unpaired delimiter
1189 assert to_md("<strong></strong>") == ""
1190 assert to_md("<em> </em>") == ""
1191 assert to_md("<strong><em></em></strong>") == ""
1192
1193 # Adjacent tags, one empty -- the empty one's delimiters must not collide
1194 # with the next tag's into an ambiguous run of asterisks
1195 assert to_md("<strong></strong><strong>bold</strong>") == "**bold**"
1196 assert to_md("<em></em><em>x</em>") == "*x*"
1197
1198 # A stray close tag with no matching open is a no-op, the same as other
1199 # malformed- HTML cases elsewhere in this parser.
1200 assert to_md("</b>text") == "text"
1201 assert to_md("<p>a</b>b</p>") == "ab"
1202
1203 # Mismatched open/close tags ("<i>x</b>y").
1204 assert to_md("<i>x</b>y") == "*xy*"
1205
1206 # A tag left open with no closing tag at all is auto-closed at end of
1207 # document rather than leaving its opening delimiter unpaired
1208 assert to_md("<b>text") == "**text**"
1209 assert to_md("<p><em>a<strong>b") == "*a**b***"
1210
1211 # Normal, well-formed cases are unaffected
1212 assert to_md("<strong>bold</strong>") == "**bold**"
1213 assert to_md("<em>italic</em>") == "*italic*"
1214 assert to_md("<strong>A</strong><strong>B</strong>") == "**A****B**"
1215
1216 # Empty block content inside emphasis must not leave an opening delimiter.
1217 assert to_md("<em><ul><li></li></ul></em>x") == "x"
1218 assert to_md("a<em><ul><li></li></ul></em>b") == "ab"
1219
1220 # Empty trailing blocks must not hide whitespace from emphasis cleanup.
1221 assert to_md("<em>text<blockquote></blockquote></em>") == ("*text\n\n> *")
1222
1223
1224 def test_conversion_html_to_markdown_empty_blocks():
1225 """Test empty block handling."""
1226
1227 def to_md(body):
1228 """Wrapper to simplify html-to-markdown conversion tests."""
1229 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
1230
1231 # Plain, marker-less block tags with nothing inside them already collapse
1232 # to nothing extra -- no separate blank line is added for each one.
1233 assert to_md("<div></div><div></div><p>text</p>") == "text"
1234 assert to_md("<p>a</p><div></div><p>b</p>") == "a\n\nb"
1235 assert (
1236 to_md("<p>a</p><div></div><div></div><div></div><p>b</p>") == "a\n\nb"
1237 )
1238
1239 # Empty blocks do not detach a marker from later content.
1240 assert (
1241 to_md("<ul><li><div></div><div></div><p>text</p></li></ul>")
1242 == "- text"
1243 )
1244 assert to_md("<blockquote><div></div><p>text</p></blockquote>") == "> text"
1245
1246 # Drop markers that never receive content.
1247 assert to_md("<ul><li></li></ul>") == ""
1248 assert to_md("<ul><li><div></div></li></ul>") == ""
1249
1250 # A sibling marker arriving after the first one's empty block tags replaces
1251 # it rather than gluing onto it.
1252 assert to_md("<ul><li><div></div></li><li>real</li></ul>") == "- real"
1253
1254 # Empty blocks do not duplicate a blockquote prefix.
1255 assert (
1256 to_md("<blockquote><p>line1</p><div></div><p>line2</p></blockquote>")
1257 == "> line1\n>\n> line2"
1258 )
1259
1260 # Real text between two empty blocks still resets the suppression, so the
1261 # block tag right after it starts a new line as normal.
1262 assert to_md("<div></div>text<div></div><p>more</p>") == "text\n\nmore"
1263
1264 # Plain whitespace between tags never counts as content
1265 assert to_md("<p>a</p> <p>b</p>") == "a\n\nb"
1266
1267 # A standalone &nbsp; is a deliberate space, not incidental formatting
1268 # whitespace.
1269 assert to_md("<p>a</p>&nbsp;<p>b</p>") == "a\n\n\xa0\n\nb"
1270
1271 # &nbsp; used inline within real text is unaffected, and still collapses to
1272 # a regular space like any other inline whitespace
1273 assert (
1274 to_md("Let's handle&nbsp;special html encoding")
1275 == "Let's handle special html encoding"
1276 )
1277
1278 # <hr> is a void element (its closing tag may never fire), but it still
1279 # writes real, non-marker content ("---").
1280 assert to_md("<hr><hr>") == "---\n\n---"
1281 assert to_md("<hr> <hr>") == "---\n\n---"
1282 assert to_md("<hr/><hr/><hr/>") == "---\n\n---\n\n---"
1283 assert to_md("<p>a</p><hr><hr><p>b</p>") == "a\n\n---\n\n---\n\nb"
1284
1285 # <hr> as the first thing in a blockquote/list item glues onto the marker;
1286 # inside an open blockquote, its own opening boundary still applies.
1287 assert to_md("<ul><li><hr></li></ul>") == "- ---"
1288 assert to_md("<blockquote><p>a</p><hr></blockquote>") == "> a\n>\n> ---"
1289
1290 # Real page text that happens to *look* like a generated marker (e.g.
1291 assert to_md("<p>- </p><p>real</p>") == "\\-\n\nreal"
1292 assert to_md("<p>- </p>") == "\\-"
1293 assert (
1294 to_md("<p>- </p><div>real div content</div>")
1295 == "\\-\n\nreal div content"
1296 )
1297 # Real text directly inside a real <li> that itself looks like a marker is
1298 # escaped too.
1299 assert to_md("<ul><li>- </li></ul>") == "- \\-"
1300
1301
1302 def test_conversion_html_to_markdown_list_indentation():
1303 """Test list continuation indentation."""
1304
1305 def to_md(body):
1306 """Wrapper to simplify html-to-markdown conversion tests."""
1307 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
1308
1309 # Baseline: a single <p> as an <li>'s only child still just glues onto the
1310 # marker.
1311 assert to_md("<li><p>text</p></li>") == "- text"
1312
1313 # Later paragraphs use the current item's continuation indentation.
1314 assert to_md("<ul><li><p>one</p><p>two</p></li></ul>") == "- one\n\n two"
1315
1316 # Ordered lists need the indentation to match their own (wider) marker
1317 # width, not the bullet list's fixed 2 spaces
1318 assert (
1319 to_md("<ol><li><p>one</p><p>two</p></li></ol>") == "1. one\n\n two"
1320 )
1321
1322 # Sibling <li>s must NOT pick up any indentation from each other -- only a
1323 # *continuation within the same item* should ever be indented
1324 assert (
1325 to_md("<ul><li><p>alpha</p></li><li><p>beta</p></li></ul>")
1326 == "- alpha\n\n- beta"
1327 )
1328 assert (
1329 to_md("<ol><li><p>a</p></li><li><p>b</p></li><li><p>c</p></li></ol>")
1330 == "1. a\n\n2. b\n\n3. c"
1331 )
1332
1333 # A nested sublist's own marker (computed independently for its own depth)
1334 # must not be *additionally* indented on top of that.
1335 assert to_md("<ul><li>x<ul><li>x</li></ul></li></ul>") == "- x\n - x"
1336 assert (
1337 to_md("<ul><li>L1<ul><li>L2<ul><li>L3</li></ul></li></ul></li></ul>")
1338 == "- L1\n - L2\n - L3"
1339 )
1340
1341 # Nested quotes combine list indentation with quote prefixes.
1342 assert to_md(
1343 "<ul><li><blockquote><p>a</p><p>b</p></blockquote></li></ul>"
1344 ) == ("- > a\n >\n > b")
1345
1346 # A first-child list inside a blockquote retains the quote prefix.
1347 assert to_md("<blockquote><ul><li>text</li></ul></blockquote>") == (
1348 "> - text"
1349 )
1350
1351 # Multiple <li>s inside a <blockquote> each need "> " restated
1352 assert to_md("<blockquote><ul><li>a</li><li>b</li></ul></blockquote>") == (
1353 "> - a\n> - b"
1354 )
1355
1356 # Chained blockquotes retain nesting after a paragraph boundary.
1357 assert to_md(
1358 "<blockquote><p>a</p><blockquote>nested</blockquote></blockquote>"
1359 ) == ("> a\n>\n> > nested")
1360
1361 # <pre>/<samp> inside an <li>: every line of the fence.
1362 assert to_md("<ul><li>code:<pre> indented\n here</pre></li></ul>") == (
1363 "- code:\n ```\n indented\n here\n ```"
1364 )
1365
1366 # A deeper list adds another indentation level to the fence.
1367 assert to_md(
1368 "<ul><li>outer<ul><li>inner:<pre> x = 1</pre></li></ul></li></ul>"
1369 ) == ("- outer\n - inner:\n ```\n x = 1\n ```")
1370
1371
1372 def test_conversion_html_to_markdown_br():
1373 """Test CommonMark hard breaks."""
1374
1375 def to_md(body):
1376 """Wrapper to simplify html-to-markdown conversion tests."""
1377 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
1378
1379 # Two trailing spaces then a newline -- a bare "\n" is only a soft break
1380 # under CommonMark (most renderers collapse it to a single space rather.
1381 assert to_md("line1<br>line2") == "line1 \nline2"
1382 assert to_md("line1<br/>line2") == "line1 \nline2"
1383 assert to_md("line1<br />line2") == "line1 \nline2"
1384
1385 # Verified against an actual renderer, not just the raw Markdown shape.
1386 rendered = convert_between(
1387 NotifyFormat.MARKDOWN, NotifyFormat.HTML, to_md("line1<br>line2")
1388 )
1389 assert "<br" in rendered
1390 assert "\\" not in rendered
1391
1392 # Consecutive <br> tags each contribute their own hard break
1393 assert to_md("a<br><br>b") == "a \n \nb"
1394
1395 # A trailing <br> with nothing after it doesn't leave a dangling hard break
1396 # at the very end of the output
1397 assert to_md("<p>line1<br></p>") == "line1"
1398
1399 # A hard break inside a blockquote must restate the "> " prefix on its
1400 # continuation line.
1401 assert to_md("<blockquote>line1<br>line2</blockquote>") == (
1402 "> line1 \n> line2"
1403 )
1404
1405 # Same, but inside a list item -- the continuation line must keep the
1406 # marker's indentation so it stays part of the same item.
1407 assert to_md("<ul><li>line1<br>line2</li></ul>") == ("- line1 \n line2")
1408
1409 # Both nested together -- a blockquote containing a list item.
1410 assert to_md(
1411 "<blockquote><ul><li>line1<br>line2</li></ul></blockquote>"
1412 ) == ("> - line1 \n > line2")
1413
1414
1415 def test_conversion_html_to_markdown_tables():
1416 """Test GFM table conversion."""
1417
1418 def to_md(body):
1419 """Wrapper to simplify html-to-markdown conversion tests."""
1420 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
1421
1422 # Basic table -- first row becomes the header, a "---" separator row is
1423 # inserted right after it
1424 assert to_md(
1425 "<table><tr><td>A</td><td>B</td></tr>"
1426 "<tr><td>1</td><td>2</td></tr></table>"
1427 ) == ("| A | B |\n| --- | --- |\n| 1 | 2 |")
1428
1429 # <thead>/<tbody>/<th> are fully transparent -- header-vs-body is decided
1430 # purely by row order, the same as <thead>-less markup
1431 assert to_md(
1432 "<table><thead><tr><th>Name</th><th>Age</th></tr></thead>"
1433 "<tbody><tr><td>Bob</td><td>42</td></tr></tbody></table>"
1434 ) == ("| Name | Age |\n| --- | --- |\n| Bob | 42 |")
1435
1436 # A single-row table still gets its separator row
1437 assert to_md("<table><tr><td>only</td></tr></table>") == (
1438 "| only |\n| --- |"
1439 )
1440
1441 # Inline formatting inside cells is preserved
1442 assert to_md(
1443 "<table><tr><td><b>bold</b></td>"
1444 '<td><a href="https://x.com">link</a></td></tr></table>'
1445 ) == ("| **bold** | [link](<https://x.com>) |\n| --- | --- |")
1446
1447 # A literal '|' inside a cell is escaped -- it's the cell delimiter itself,
1448 # and would otherwise be misread as starting a new column
1449 assert to_md("<table><tr><td>a | b</td></tr></table>") == (
1450 "| a \\| b |\n| --- |"
1451 )
1452
1453 # A newline a cell's own content produced (here, a <br>) is flattened to a
1454 # single space.
1455 assert to_md("<table><tr><td>a<br>b</td></tr></table>") == (
1456 "| a b |\n| --- |"
1457 )
1458
1459 # Surrounding content gets ordinary paragraph separation from the table,
1460 # the same as a list or blockquote would
1461 assert to_md("<p>before</p><table><tr><td>A</td></tr></table>") == (
1462 "before\n\n| A |\n| --- |"
1463 )
1464 assert to_md("<table><tr><td>A</td></tr></table><p>after</p>") == (
1465 "| A |\n| --- |\n\nafter"
1466 )
1467
1468 # An entirely empty table, or a table whose only row has no cells at all,
1469 # produces nothing
1470 assert to_md("<table></table>") == ""
1471 assert to_md("<table><tr></tr></table>") == ""
1472
1473 # A table fully inside a suppressed container (e.g. <head>) contributes
1474 # nothing -- not even an empty "| |" row
1475 assert (
1476 to_md(
1477 "<head><table><tr><td>x</td></tr></table></head><body>text</body>"
1478 )
1479 == "text"
1480 )
1481
1482 # Suppress text outside table cells.
1483 assert to_md("<table>stray<tr><td>A</td></tr></table>") == (
1484 "| A |\n| --- |"
1485 )
1486 assert to_md("<table><tr>stray<td>A</td></tr></table>") == (
1487 "| A |\n| --- |"
1488 )
1489 assert to_md("<table>\n <tr>\n <td>A</td>\n </tr>\n</table>") == (
1490 "| A |\n| --- |"
1491 )
1492
1493 # A stray <td> with no enclosing <tr> at all falls back to ordinary
1494 # paragraph-like treatment -- the same as before table support existed
1495 assert to_md("<td>standalone</td>") == "standalone"
1496
1497 # A stray <tr> with no enclosing <table> is treated as a one-row table of
1498 # its own
1499 assert to_md("<tr><td>a</td><td>b</td></tr>") == (
1500 "| a | b |\n| --- | --- |"
1501 )
1502
1503
1504 def test_conversion_html_to_markdown_tables_indentation():
1505 """Test nested table indentation."""
1506
1507 def to_md(body):
1508 """Wrapper to simplify html-to-markdown conversion tests."""
1509 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
1510
1511 assert to_md(
1512 "<ul><li>before<table><tr><td>A</td></tr></table></li></ul>"
1513 ) == ("- before\n\n | A |\n | --- |")
1514
1515 assert to_md(
1516 "<ul><li>before<table><tr><td>A</td><td>B</td></tr>"
1517 "<tr><td>1</td><td>2</td></tr></table></li></ul>"
1518 ) == ("- before\n\n | A | B |\n | --- | --- |\n | 1 | 2 |")
1519
1520 assert to_md(
1521 "<blockquote><table><tr><td>A</td><td>B</td></tr>"
1522 "<tr><td>1</td><td>2</td></tr></table></blockquote>"
1523 ) == ("> | A | B |\n> | --- | --- |\n> | 1 | 2 |")
1524
1525
1526 def test_conversion_html_to_markdown_tables_hardening():
1527 """Test malformed table input."""
1528
1529 def to_md(body):
1530 """Wrapper to simplify html-to-markdown conversion tests."""
1531 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
1532
1533 # Neither <td> nor <tr> ever closed -- extremely common in real-
1534 # world/legacy table markup
1535 assert to_md("<table><tr><td>A<td>B<tr><td>1<td>2</table>") == (
1536 "| A | B |\n| --- | --- |\n| 1 | 2 |"
1537 )
1538
1539 # Same, but the enclosing </table> is missing too -- the last row and cell
1540 # are recovered at end of document
1541 assert to_md("<table><tr><td>A<td>B<tr><td>1<td>2") == (
1542 "| A | B |\n| --- | --- |\n| 1 | 2 |"
1543 )
1544
1545 # A stray </tr> or </table> with nothing matching open at all (no enclosing
1546 # structure whatsoever, not even an open cell) is a no-op.
1547 assert to_md("</tr>text") == "text"
1548 assert to_md("</table>text") == "text"
1549 assert to_md("<p>a</tr>b</p>") == "ab"
1550 assert to_md("<p>a</table>b</p>") == "ab"
1551
1552 # A stray <tr> with no enclosing <table> renders as a one-row table of its
1553 # own and remains separated from following content.
1554 assert to_md("<tr><td>cell</td></tr>after") == (
1555 "| cell |\n| --- |\n\nafter"
1556 )
1557
1558 # A <table> nested inside another table's cell has no Markdown
1559 # representation.
1560 assert to_md(
1561 "<table><tr><td>outer<table><tr><td>inner</td></tr></table>"
1562 "</td></tr></table>"
1563 ) == ("| outer |\n| --- |")
1564
1565 # Same, with content both before and after the nested table, and the
1566 # nested table itself containing more than one row.
1567 assert to_md(
1568 "<table><tr><td>a<table><tr><td>b</td></tr><tr><td>c</td></tr>"
1569 "</table>d</td></tr></table>"
1570 ) == ("| a d |\n| --- |")
1571
1572 # Three levels deep -- only the outermost table survives.
1573 assert to_md(
1574 "<table><tr><td>L1<table><tr><td>L2<table><tr><td>L3</td></tr>"
1575 "</table></td></tr></table></td></tr></table>"
1576 ) == ("| L1 |\n| --- |")
1577
1578 # A literal '|' alongside a nested table in the same cell -- the '|' is
1579 # still escaped normally; the nested table still contributes nothing.
1580 assert to_md(
1581 "<table><tr><td>a|b<table><tr><td>c</td></tr></table></td></tr>"
1582 "</table>"
1583 ) == ("| a\\|b |\n| --- |")
1584
1585 # Only the very first <tr> is ever closed
1586 assert to_md("<table><tr><td>A</td></tr><tr><td>B<tr><td>C</table>") == (
1587 "| A |\n| --- |\n| B |\n| C |"
1588 )
1589
1590 # An unclosed inline element (<em>) inside a <td> is silently discarded
1591 # when a sibling <td> opens; the cell's text is still captured.
1592 assert (
1593 to_md(
1594 "<table><tr><td><em>unclosed text<td>second cell</td></tr></table>"
1595 )
1596 == "| *unclosed text | second cell |\n| --- | --- |"
1597 )
1598
1599 # Performance: many rows, each with unclosed <td>/<tr> tags (the legacy-
1600 # markup shape), large enough to expose quadratic recovery.
1601 n = 20000
1602 html = "<table>" + "<tr><td>a<td>b" * n + "</table>"
1603 start = default_timer()
1604 out = to_md(html)
1605 elapsed = default_timer() - start
1606 assert out.count("\n") == n # one line per row, output stays linear
1607 # Generous bound -- see the note on the equivalent check above.
1608 assert elapsed < 40.0
1609
1610
1611 def test_conversion_html_to_markdown_pre_code_whitespace():
1612 """Test preformatted whitespace."""
1613
1614 def to_md(body):
1615 """Wrapper to simplify html-to-markdown conversion tests."""
1616 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
1617
1618 # Internal leading whitespace and blank-looking indentation differences
1619 # between lines are preserved exactly
1620 assert (
1621 to_md("<pre> leading\n more leading\nback to zero</pre>")
1622 == "```\n leading\n more leading\nback to zero\n```"
1623 )
1624
1625 # Leading/trailing spaces inside inline <code> survive too
1626 assert to_md("<code> leading spaces </code>") == "` leading spaces `"
1627
1628 # Whitespace is preserved the same way even when nested inside a list item
1629 # (which now adds its own 2-space indentation in front.
1630 assert to_md("<ul><li><pre> a\n b\nc</pre></li></ul>") == (
1631 "- ```\n a\n b\n c\n ```"
1632 )
1633
1634
1635 def test_conversion_html_to_markdown_unterminated_pre_code():
1636 """Test <pre>/<code>/<samp> left open at end of document."""
1637
1638 def to_md(body):
1639 """Wrapper to simplify html-to-markdown conversion tests."""
1640 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
1641
1642 # A <pre>/<code>/<samp> with no closing tag at all is auto-closed and
1643 # rendered at end of document.
1644 assert to_md("<pre>unterminated code") == "```\nunterminated code\n```"
1645 assert to_md("<code>inline unterminated") == "`inline unterminated`"
1646 assert to_md("<samp>unterminated output") == (
1647 "```\nunterminated output\n```"
1648 )
1649
1650 # Still works with real content before the unterminated block.
1651 assert to_md("text<pre>code") == "text\n```\ncode\n```"
1652
1653 # A suppressed (non-storing) unterminated frame contributes nothing.
1654 assert to_md("<head><pre>hidden") == ""
1655
1656
1657 def test_conversion_html_to_markdown_table_code_pipe():
1658 """Test '|' inside an inline code span within a table cell."""
1659
1660 def to_md(body):
1661 """Wrapper to simplify html-to-markdown conversion tests."""
1662 return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body)
1663
1664 # A '|' inside a code span is already literal there.
1665 assert to_md("<table><tr><td><code>a|b</code></td></tr></table>") == (
1666 "| `a|b` |\n| --- |"
1667 )
1668
1669 # A '|' outside any code span in the same cell is still escaped.
1670 assert to_md("<table><tr><td>x|<code>a|b</code>|y</td></tr></table>") == (
1671 "| x\\|`a|b`\\|y |\n| --- |"
1672 )
1673
1674 # Literal backtick CHARACTERS typed as ordinary text (not an actual <code>
1675 # element) get backslash-escaped by MARKDOWN_ESCAPE like any other.
1676 assert to_md("<table><tr><td>`a|b`</td></tr></table>") == (
1677 "| \\`a\\|b\\` |\n| --- |"
1678 )
1679
1680 # A real code span and escaped literal backticks can coexist in the same
1681 # cell -- only the real one's '|' stays unescaped.
1682 assert to_md(
1683 "<table><tr><td><code>x|y</code> and `lit|eral`</td></tr></table>"
1684 ) == ("| `x|y` and \\`lit\\|eral\\` |\n| --- |")
1685
1686 # A real code span immediately preceded by an ESCAPED literal backslash (an
1687 # even number of '\' characters, i.e.
1688 assert to_md(
1689 "<table><tr><td>text\\<code>a|b</code></td></tr></table>"
1690 ) == ("| text\\\\`a|b` |\n| --- |")
1691 assert to_md(
1692 "<table><tr><td>text\\\\<code>a|b</code></td></tr></table>"
1693 ) == ("| text\\\\\\\\`a|b` |\n| --- |")
1694
1695 # An unmatched (unbalanced) bare backtick run inside a cell.
1696 conv = HTMLMarkdownConverter()
1697 assert conv._escape_cell_pipes("a`b|c") == "a`b\\|c"
1698
1699 # The shared index skips escape pairs and groups runs by exact width.
1700 # A lookup returns None when the requested width does not exist.
1701 assert find_unescaped_run(build_backtick_run_index("\\` `"), 0, 1) == 3
1702 assert (
1703 find_unescaped_run(build_backtick_run_index("no backticks here"), 0, 1)
1704 is None
1705 )
1706 assert (
1707 find_unescaped_run(build_backtick_run_index("``too short"), 0, 3)
1708 is None
1709 )
1710
1711 # Runs of different widths are indexed separately.
1712 assert find_unescaped_run(build_backtick_run_index("`` `"), 0, 1) == 3
1713
1714 # Skip an escaped single backtick before matching a width-two run.
1715 assert find_unescaped_run(build_backtick_run_index("\\` ``x"), 0, 2) == 3
1716
1717 # Skip an unescaped run of the wrong width before matching width two.
1718 assert find_unescaped_run(build_backtick_run_index("` ``x"), 0, 2) == 2
1719
1720 # A genuine match arbitrarily far from `start` is still found.
1721 far = "a" * 200_000 + "`"
1722 assert find_unescaped_run(build_backtick_run_index(far), 0, 1) == 200_000
1723
1724 # A cell containing many distinct, non-matching backtick-run lengths must
1725 # still resolve in roughly linear time, not quadratic.
1726 def adversarial_cell(width_count):
1727 body = ["`" * w + "x" for w in range(1, width_count + 1)]
1728 body.append("`")
1729 return "".join(body)
1730
1731 small = adversarial_cell(400)
1732 large = adversarial_cell(800)
1733
1734 start = default_timer()
1735 conv._escape_cell_pipes(small)
1736 small_time = default_timer() - start
1737
1738 start = default_timer()
1739 conv._escape_cell_pipes(large)
1740 large_time = default_timer() - start
1741
1742 # Double the adversarial width count.
1743 assert large_time < small_time * 6 + 0.05
1744
1745
1746 def test_conversion_text_to():
1747 """conversion: Test Text to all types"""
1748
1749 response = convert_between(
1750 NotifyFormat.TEXT,
1751 NotifyFormat.HTML,
1752 "<title>Test Message</title><body>Body</body>",
1753 )
1754
1755 assert (
1756 response
1757 == "&lt;title&gt;Test&nbsp;Message&lt;/title&gt;&lt;body&gt;Body&lt;"
1758 "/body&gt;"
1759 )
1760
1761
1762 def test_conversion_markdown_to_html():
1763 """conversion: Test markdown to html"""
1764
1765 # While this uses the underlining markdown library
1766 # what we're testing for are the edge cases we know it doesn't support
1767 # hence, `-` (a dash) with the markdown library must be a `*` to work
1768 # correctly
1769 response = convert_between(
1770 NotifyFormat.MARKDOWN,
1771 NotifyFormat.HTML,
1772 cleandoc("""
1773 ## Some Heading
1774
1775 With Data:
1776
1777 - Foo
1778 - Bar
1779 """),
1780 )
1781
1782 assert "<li>Foo</li>" in response
1783 assert "<li>Bar</li>" in response
1784 assert "<h2>Some Heading</h2>" in response
1785 assert "<br />" not in response
1786
1787 # if the - follows With Data on the very next line, it's consider to not
1788 # requiring indentation
1789 response = convert_between(
1790 NotifyFormat.MARKDOWN,
1791 NotifyFormat.HTML,
1792 cleandoc("""
1793 ## Some Heading
1794
1795 With Data:
1796 - Foo
1797 - Bar
1798 """),
1799 )
1800
1801 # Breaks are added:
1802 assert "<br />" in response
1803 assert "- Foo" in response
1804 assert "- Bar" in response
1805
1806 # Table formatting
1807 response = convert_between(
1808 NotifyFormat.MARKDOWN,
1809 NotifyFormat.HTML,
1810 cleandoc("""
1811 First Header | Second Header
1812 -------------- | -------------
1813 Content Cell1 | Content Cell3
1814 Content Cell2 | Content Cell4
1815 """),
1816 )
1817
1818 assert "<table>" in response
1819 assert "<th>First Header</th>" in response
1820 assert "<th>Second Header</th>" in response
1821 assert "<td>Content Cell1</td>" in response
1822 assert "<td>Content Cell2</td>" in response
1823 assert "<td>Content Cell3</td>" in response
1824 assert "<td>Content Cell4</td>" in response