| 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 |
from unittest import mock |
| 34 |
|
| 35 |
import pytest |
| 36 |
|
| 37 |
from apprise import NotifyFormat |
| 38 |
from apprise.conversion import ( |
| 39 |
BLOCKQUOTE_DEPTH_MAX, |
| 40 |
LIST_DEPTH_MAX, |
| 41 |
MAX_FRAME_DEPTH, |
| 42 |
HTMLMarkdownConverter, |
| 43 |
commonmark as commonmark_module, |
| 44 |
commonmark_can_close_emphasis, |
| 45 |
commonmark_can_open_emphasis, |
| 46 |
commonmark_decode_backslash_escapes, |
| 47 |
commonmark_emphasis_run, |
| 48 |
commonmark_find_backtick_run, |
| 49 |
commonmark_headings_to_bold, |
| 50 |
commonmark_index_backtick_runs, |
| 51 |
commonmark_match_emphasis, |
| 52 |
commonmark_materialize_repair, |
| 53 |
commonmark_pick_emphasis_sentinel, |
| 54 |
commonmark_render_emphasis_events, |
| 55 |
commonmark_render_emphasis_markers, |
| 56 |
commonmark_repair_chunk, |
| 57 |
commonmark_scan_autolink_dest, |
| 58 |
commonmark_scan_closer_runs, |
| 59 |
commonmark_scan_delimiter_run, |
| 60 |
commonmark_scan_paren_dest, |
| 61 |
commonmark_scan_repair_region, |
| 62 |
convert_between, |
| 63 |
html_to_markdown, |
| 64 |
markdown_to_html, |
| 65 |
split_dialect_chunk, |
| 66 |
truncate_dialect_chunk, |
| 67 |
) |
| 68 |
from apprise.plugins.google_chat import NotifyGoogleChat |
| 69 |
from apprise.plugins.slack import NotifySlack |
| 70 |
|
| 71 |
logging.disable(logging.CRITICAL) |
| 72 |
|
| 73 |
|
| 74 |
def test_conversion_html_to_text(): |
| 75 |
"""conversion: Test HTML to plain text""" |
| 76 |
|
| 77 |
def to_html(body): |
| 78 |
"""A function to simply html conversion tests.""" |
| 79 |
return convert_between(NotifyFormat.HTML, NotifyFormat.TEXT, body) |
| 80 |
|
| 81 |
assert to_html("No HTML code here.") == "No HTML code here." |
| 82 |
|
| 83 |
clist = to_html("<ul><li>Lots and lots</li><li>of lists.</li></ul>") |
| 84 |
assert "Lots and lots" in clist |
| 85 |
assert "of lists." in clist |
| 86 |
|
| 87 |
assert "To be or not to be." in to_html( |
| 88 |
"<blockquote>To be or not to be.</blockquote>" |
| 89 |
) |
| 90 |
|
| 91 |
cspace = to_html( |
| 92 |
"<h2>Fancy heading</h2><p>And a paragraph too.<br>Plus line break.</p>" |
| 93 |
) |
| 94 |
assert "Fancy heading" in cspace |
| 95 |
assert "And a paragraph too.\nPlus line break." in cspace |
| 96 |
|
| 97 |
assert ( |
| 98 |
to_html( |
| 99 |
"<style>body { font: 200%; }</style>" |
| 100 |
"<p>Some obnoxious text here.</p>" |
| 101 |
) |
| 102 |
== "Some obnoxious text here." |
| 103 |
) |
| 104 |
|
| 105 |
assert ( |
| 106 |
to_html("<p>line 1</p><p>line 2</p><p>line 3</p>") |
| 107 |
== "line 1\nline 2\nline 3" |
| 108 |
) |
| 109 |
|
| 110 |
# Case sensitivity |
| 111 |
assert ( |
| 112 |
to_html("<p>line 1</P><P>line 2</P><P>line 3</P>") |
| 113 |
== "line 1\nline 2\nline 3" |
| 114 |
) |
| 115 |
|
| 116 |
# double new lines (testing <br> and </br>) |
| 117 |
assert ( |
| 118 |
to_html("some information<br/><br>and more information") |
| 119 |
== "some information\n\nand more information" |
| 120 |
) |
| 121 |
|
| 122 |
# |
| 123 |
# Test bad tags |
| 124 |
# |
| 125 |
|
| 126 |
# first 2 entries are okay, but last will do as best as it can |
| 127 |
assert ( |
| 128 |
to_html("<p>line 1</><p>line 2</gar><p>line 3>") |
| 129 |
== "line 1\nline 2\nline 3>" |
| 130 |
) |
| 131 |
|
| 132 |
# Make sure we ignore fields that aren't important to us |
| 133 |
assert ( |
| 134 |
to_html( |
| 135 |
"<script>ignore this</script>" |
| 136 |
"<p>line 1</p>" |
| 137 |
"Another line without being enclosed" |
| 138 |
) |
| 139 |
== "line 1\nAnother line without being enclosed" |
| 140 |
) |
| 141 |
|
| 142 |
# Test cases when there are no new lines (we're dealing with just inline |
| 143 |
# entries); an empty entry as well |
| 144 |
assert ( |
| 145 |
to_html("<span></span<<span>test</span> <a href='#'>my link</a>") |
| 146 |
== "test my link" |
| 147 |
) |
| 148 |
|
| 149 |
# </p> missing |
| 150 |
assert ( |
| 151 |
to_html( |
| 152 |
"<body><div>line 1 <b>bold</b></div> " |
| 153 |
" <a href='#'>my link</a>" |
| 154 |
"<p>3rd line</body>" |
| 155 |
) |
| 156 |
== "line 1 bold\nmy link\n3rd line" |
| 157 |
) |
| 158 |
|
| 159 |
# <hr/> on it's own |
| 160 |
assert to_html("<hr/>") == "---" |
| 161 |
assert to_html("<hr>") == "---" |
| 162 |
|
| 163 |
# We need to handle HTML Encodings |
| 164 |
assert ( |
| 165 |
to_html(""" |
| 166 |
<html> |
| 167 |
<title>ignore this entry</title> |
| 168 |
<body> |
| 169 |
Let's handle special html encoding |
| 170 |
<hr/> |
| 171 |
</body> |
| 172 |
""") |
| 173 |
== "Let's handle special html encoding\n---" |
| 174 |
) |
| 175 |
|
| 176 |
# If you give nothing, you get nothing in return |
| 177 |
assert to_html("") == "" |
| 178 |
|
| 179 |
# Special case on HR tag |
| 180 |
assert ( |
| 181 |
to_html(""" |
| 182 |
<html> |
| 183 |
<head></head> |
| 184 |
<body> |
| 185 |
<p><b>FROM: </b>[email protected] |
| 186 |
<[email protected]></p> |
| 187 |
Hi!<br/> |
| 188 |
How are you?<br/> |
| 189 |
<font color=3D"#FF0000">red font</font> |
| 190 |
<a href=3D"http://www.python.org">link</a> you wanted.<br/> |
| 191 |
</body> |
| 192 |
</html> |
| 193 |
""") |
| 194 |
== "FROM: [email protected]\nHi!\n How are you?\n red font" |
| 195 |
" link you wanted." |
| 196 |
) |
| 197 |
|
| 198 |
assert ( |
| 199 |
to_html(""" |
| 200 |
<html> |
| 201 |
<head></head> |
| 202 |
<body> |
| 203 |
<p><b>FROM: </b>[email protected] |
| 204 |
<[email protected]><hr></p> |
| 205 |
Hi!<br/> |
| 206 |
How are you?<br/> |
| 207 |
<font color=3D"#FF0000">red font</font> |
| 208 |
<a href=3D"http://www.python.org">link</a> you wanted.<br/> |
| 209 |
</body> |
| 210 |
</html> |
| 211 |
""") |
| 212 |
== "FROM: [email protected]\n---\nHi!\n How are you?\n red" |
| 213 |
" font link you wanted." |
| 214 |
) |
| 215 |
|
| 216 |
# Special case on HR if text is sorrunded by HR tags |
| 217 |
# its created a dict element |
| 218 |
assert ( |
| 219 |
to_html(""" |
| 220 |
<html> |
| 221 |
<head></head> |
| 222 |
<body> |
| 223 |
<p><hr><b>FROM: </b>[email protected] |
| 224 |
<[email protected]><hr></p> |
| 225 |
Hi!<br/> |
| 226 |
How are you?<br/> |
| 227 |
<font color=3D"#FF0000">red font</font> |
| 228 |
<a href=3D"http://www.python.org">link</a> you wanted.<br/> |
| 229 |
</body> |
| 230 |
</html> |
| 231 |
""") |
| 232 |
== "---\nFROM: [email protected]\n---\nHi!\n How are you?\n" |
| 233 |
" red font link you wanted." |
| 234 |
) |
| 235 |
|
| 236 |
assert ( |
| 237 |
to_html(""" |
| 238 |
<html> |
| 239 |
<head></head> |
| 240 |
<body> |
| 241 |
<p> |
| 242 |
<hr><b>TEST</b><hr> |
| 243 |
</p> |
| 244 |
Hi!<br/> |
| 245 |
How are you?<br/> |
| 246 |
<font color=3D"#FF0000">red font</font> |
| 247 |
<a href=3D"http://www.python.org">link</a> you wanted.<br/> |
| 248 |
</body> |
| 249 |
</html> |
| 250 |
""") |
| 251 |
== "---\nTEST\n---\nHi!\n How are you?\n red font link you wanted." |
| 252 |
) |
| 253 |
|
| 254 |
with pytest.raises(TypeError): |
| 255 |
# Invalid input |
| 256 |
assert to_html(None) |
| 257 |
|
| 258 |
with pytest.raises(TypeError): |
| 259 |
# Invalid input |
| 260 |
assert to_html(42) |
| 261 |
|
| 262 |
with pytest.raises(TypeError): |
| 263 |
# Invalid input |
| 264 |
assert to_html(object) |
| 265 |
|
| 266 |
|
| 267 |
def test_conversion_html_to_markdown(): |
| 268 |
"""Test basic HTML-to-Markdown conversion.""" |
| 269 |
|
| 270 |
def to_md(body): |
| 271 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 272 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 273 |
|
| 274 |
# Plain text with no HTML passes through unchanged |
| 275 |
assert to_md("No HTML code here.") == "No HTML code here." |
| 276 |
|
| 277 |
# Empty string in, empty string out |
| 278 |
assert to_md("") == "" |
| 279 |
|
| 280 |
# Paragraphs need a full blank line between them. |
| 281 |
assert ( |
| 282 |
to_md("<p>line 1</p><p>line 2</p><p>line 3</p>") |
| 283 |
== "line 1\n\nline 2\n\nline 3" |
| 284 |
) |
| 285 |
|
| 286 |
# Case sensitivity -- tag names are case-insensitive in HTML |
| 287 |
assert ( |
| 288 |
to_md("<p>line 1</P><P>line 2</P><P>line 3</P>") |
| 289 |
== "line 1\n\nline 2\n\nline 3" |
| 290 |
) |
| 291 |
|
| 292 |
# HTMLParser lowercases ALL tag names -- inline tags included |
| 293 |
assert to_md("<B>bold text</B>") == "**bold text**" |
| 294 |
assert to_md("<I>italic</I>") == "*italic*" |
| 295 |
|
| 296 |
# Uppercase self-closing <BR/> tags also produce CommonMark hard breaks. |
| 297 |
assert ( |
| 298 |
to_md("line one<BR/>line two<BR />line three") |
| 299 |
== "line one \nline two \nline three" |
| 300 |
) |
| 301 |
|
| 302 |
# <br> and self-closing <br/> both emit a hard break |
| 303 |
assert ( |
| 304 |
to_md("some information<br/><br>and more information") |
| 305 |
== "some information \n \nand more information" |
| 306 |
) |
| 307 |
|
| 308 |
# Each heading level maps to the correct number of # characters |
| 309 |
assert to_md("<h1>Heading 1</h1>") == "# Heading 1" |
| 310 |
assert to_md("<h2>Heading 2</h2>") == "## Heading 2" |
| 311 |
assert to_md("<h3>Heading 3</h3>") == "### Heading 3" |
| 312 |
assert to_md("<h4>Heading 4</h4>") == "#### Heading 4" |
| 313 |
assert to_md("<h5>Heading 5</h5>") == "##### Heading 5" |
| 314 |
assert to_md("<h6>Heading 6</h6>") == "###### Heading 6" |
| 315 |
|
| 316 |
# Multiple headings and paragraphs together |
| 317 |
assert to_md( |
| 318 |
"<h1>Heading 1</h1>" |
| 319 |
"<h2>Heading 2</h2>" |
| 320 |
"<h3>Heading 3</h3>" |
| 321 |
"<h4>Heading 4</h4>" |
| 322 |
"<h5>Heading 5</h5>" |
| 323 |
"<h6>Heading 6</h6>" |
| 324 |
"<p>line 1</>" |
| 325 |
"<p><em>line 2</em></gar>" |
| 326 |
"<p>line 3>" |
| 327 |
) == ( |
| 328 |
"# Heading 1\n## Heading 2\n### Heading 3\n" |
| 329 |
"#### Heading 4\n##### Heading 5\n###### Heading 6\n\n" |
| 330 |
"line 1\n\n*line 2*\n\nline 3\\>" |
| 331 |
) |
| 332 |
|
| 333 |
# <b> and <strong> both produce bold markers |
| 334 |
assert to_md("<b>bold text</b>") == "**bold text**" |
| 335 |
assert to_md("<strong>bold text</strong>") == "**bold text**" |
| 336 |
|
| 337 |
# <i> and <em> both produce italic markers |
| 338 |
assert to_md("<i>italic</i>") == "*italic*" |
| 339 |
assert to_md("<em>italic</em>") == "*italic*" |
| 340 |
|
| 341 |
# Angle destinations prevent parentheses in an href from ending links. |
| 342 |
assert ( |
| 343 |
to_md( |
| 344 |
"<body><div>line 1 <b>bold</b></div> " |
| 345 |
" <a href='/link'>my link</a>" |
| 346 |
"<p>3rd line</body>" |
| 347 |
) |
| 348 |
== "line 1 **bold**\n\n[my link](</link>)\n\n3rd line" |
| 349 |
) |
| 350 |
|
| 351 |
# <a href="..."> produces Markdown link syntax |
| 352 |
assert ( |
| 353 |
to_md("<span></span<<span>test</span> <a href='#'>my link</a>") |
| 354 |
== "test [my link](<#>)" |
| 355 |
) |
| 356 |
|
| 357 |
# <a> with nested inline markup -- the href must survive the child tags |
| 358 |
assert to_md("<a href='/x'><b>hello</b> world</a>") == ( |
| 359 |
"[**hello** world](</x>)" |
| 360 |
) |
| 361 |
assert to_md("<a href='/x'><strong>label</strong></a>") == ( |
| 362 |
"[**label**](</x>)" |
| 363 |
) |
| 364 |
assert ( |
| 365 |
to_md("<a href='/x'><em>italic</em> and plain</a>") |
| 366 |
== "[*italic* and plain](</x>)" |
| 367 |
) |
| 368 |
|
| 369 |
# Nested <a> -- inner href wins for its own span; outer wraps the rest |
| 370 |
assert ( |
| 371 |
to_md("<a href='/outer'>text <a href='/inner'>link</a></a>") |
| 372 |
== "[text [link](</inner>)](</outer>)" |
| 373 |
) |
| 374 |
|
| 375 |
# <a> with no href attribute -- content rendered as plain text |
| 376 |
assert to_md("<span>test</span> <a>no link</a>") == "test no link" |
| 377 |
|
| 378 |
# Bare <a name="..."> anchor (no href) -- text passes through unchanged |
| 379 |
assert to_md("<a name='top'>jump target</a>") == "jump target" |
| 380 |
|
| 381 |
# <span> is inline -- it passes text through without a newline; <div> is |
| 382 |
# block-level and paragraph-like, so it adds a blank line. |
| 383 |
assert to_md("<div>block</div><span>inline</span>") == "block\n\ninline" |
| 384 |
|
| 385 |
# HTML comments are stripped entirely; surrounding text is preserved |
| 386 |
assert to_md("<!-- comment --> text") == "text" |
| 387 |
assert to_md("a<!-- c1 -->b<!-- c2 -->c") == "abc" |
| 388 |
|
| 389 |
# <![CDATA[...]]> sections are gracefully ignored (content is dropped, text |
| 390 |
# outside the CDATA boundary is kept) |
| 391 |
assert to_md("text<![CDATA[data]]> here") == "text here" |
| 392 |
assert to_md("<![CDATA[data]]>text") == "text" |
| 393 |
|
| 394 |
# Inline <code> wraps in backticks without a block boundary |
| 395 |
assert to_md("<code>func()</code>") == "`func()`" |
| 396 |
|
| 397 |
# Markdown special characters inside <code> are NOT escaped -- backtick |
| 398 |
# delimiters already make content literal |
| 399 |
assert to_md("<code>x*2 and #tag</code>") == "`x*2 and #tag`" |
| 400 |
|
| 401 |
# <pre> produces a fenced code block |
| 402 |
assert to_md("<pre>line a\nline b</pre>") == "```\nline a\nline b\n```" |
| 403 |
|
| 404 |
# <samp> is treated the same as <pre> (fenced block) |
| 405 |
assert to_md("<samp>output\nhere</samp>") == "```\noutput\nhere\n```" |
| 406 |
|
| 407 |
# Inline code followed immediately by a pre block |
| 408 |
assert to_md( |
| 409 |
"<code>multi-line 1\nmulti-line 2</code>more content" |
| 410 |
"<pre>multi-line 1\nmulti-line 2</pre>more content" |
| 411 |
) == ( |
| 412 |
"`multi-line 1\nmulti-line 2`more content" |
| 413 |
"\n```\nmulti-line 1\nmulti-line 2\n```\nmore content" |
| 414 |
) |
| 415 |
|
| 416 |
# Unordered lists produce "- " prefixed items |
| 417 |
result = to_md("<ul><li>Lots and lots</li><li>of lists.</li></ul>") |
| 418 |
assert "- Lots and lots" in result |
| 419 |
assert "- of lists." in result |
| 420 |
|
| 421 |
assert ( |
| 422 |
to_md("<blockquote>To be or not to be.</blockquote>") |
| 423 |
== "> To be or not to be." |
| 424 |
) |
| 425 |
|
| 426 |
# Standalone <hr/> produces just "---" |
| 427 |
assert to_md("<hr/>") == "---" |
| 428 |
assert to_md("<hr>") == "---" |
| 429 |
|
| 430 |
# <style> content is suppressed |
| 431 |
assert ( |
| 432 |
to_md( |
| 433 |
"<style>body { font: 200%; }</style>" |
| 434 |
"<p>Some obnoxious text here.</p>" |
| 435 |
) |
| 436 |
== "Some obnoxious text here." |
| 437 |
) |
| 438 |
|
| 439 |
# <script> content is suppressed |
| 440 |
assert ( |
| 441 |
to_md( |
| 442 |
"<script>ignore this</script>" |
| 443 |
"<p>line 1</p>" |
| 444 |
"Another line without being enclosed" |
| 445 |
) |
| 446 |
== "line 1\n\nAnother line without being enclosed" |
| 447 |
) |
| 448 |
|
| 449 |
# '*' outside code is escaped so it does not trigger emphasis |
| 450 |
assert to_md("<p>price: 5 * 3</p>") == r"price: 5 \* 3" |
| 451 |
|
| 452 |
# '#' outside code is escaped so it does not trigger a heading |
| 453 |
assert to_md("<p>Tag #1</p>") == r"Tag \#1" |
| 454 |
|
| 455 |
# Backtick outside code is escaped |
| 456 |
assert to_md("<p>Use `func`</p>") == r"Use \`func\`" |
| 457 |
|
| 458 |
assert ( |
| 459 |
to_md( |
| 460 |
""" |
| 461 |
<html> |
| 462 |
<title>ignore this entry</title> |
| 463 |
<body> |
| 464 |
Let's handle special html encoding |
| 465 |
<hr/> |
| 466 |
</body> |
| 467 |
""" |
| 468 |
) |
| 469 |
== "Let's handle special html encoding\n\n---" |
| 470 |
) |
| 471 |
|
| 472 |
# Missing </p> is handled gracefully |
| 473 |
assert ( |
| 474 |
to_md( |
| 475 |
"<h2>Heading</h2><p>And a paragraph too.<br>Plus line break.</p>" |
| 476 |
) |
| 477 |
== "## Heading\n\nAnd a paragraph too. \nPlus line break." |
| 478 |
) |
| 479 |
|
| 480 |
with pytest.raises(TypeError): |
| 481 |
to_md(None) |
| 482 |
|
| 483 |
with pytest.raises(TypeError): |
| 484 |
to_md(42) |
| 485 |
|
| 486 |
with pytest.raises(TypeError): |
| 487 |
to_md(object) |
| 488 |
|
| 489 |
|
| 490 |
def test_conversion_html_to_markdown_lists(): |
| 491 |
"""Test list nesting and numbering.""" |
| 492 |
|
| 493 |
def to_md(body): |
| 494 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 495 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 496 |
|
| 497 |
# Flat unordered list |
| 498 |
|
| 499 |
assert ( |
| 500 |
to_md("<ul><li>alpha</li><li>beta</li><li>gamma</li></ul>") |
| 501 |
== "- alpha\n- beta\n- gamma" |
| 502 |
) |
| 503 |
|
| 504 |
# Flat ordered list with auto-incrementing counter |
| 505 |
|
| 506 |
assert ( |
| 507 |
to_md("<ol><li>first</li><li>second</li><li>third</li></ol>") |
| 508 |
== "1. first\n2. second\n3. third" |
| 509 |
) |
| 510 |
|
| 511 |
# <ol start=> shifts where the auto-incrementing counter begins |
| 512 |
assert to_md('<ol start="4"><li>a</li><li>b</li></ol>') == "4. a\n5. b" |
| 513 |
assert to_md('<ol start="0"><li>a</li></ol>') == "0. a" |
| 514 |
|
| 515 |
# CommonMark list markers cannot represent negative starting values. |
| 516 |
assert to_md('<ol start="-3"><li>a</li><li>b</li></ol>') == "0. a\n1. b" |
| 517 |
|
| 518 |
# A non-numeric start is ignored, same as no attribute at all |
| 519 |
assert to_md('<ol start="abc"><li>a</li></ol>') == "1. a" |
| 520 |
|
| 521 |
# <li value=> resets the counter for that item and every sibling after it |
| 522 |
assert to_md('<ol><li value="5">a</li><li>b</li></ol>') == "5. a\n6. b" |
| 523 |
assert ( |
| 524 |
to_md('<ol><li>a</li><li value="10">b</li><li>c</li></ol>') |
| 525 |
== "1. a\n10. b\n11. c" |
| 526 |
) |
| 527 |
assert to_md('<ol><li value="-5">a</li><li>b</li></ol>') == "0. a\n1. b" |
| 528 |
|
| 529 |
# A non-numeric value is ignored too -- the counter just keeps incrementing |
| 530 |
# normally, same as if the attribute weren't there |
| 531 |
assert to_md('<ol><li value="abc">a</li><li>b</li></ol>') == "1. a\n2. b" |
| 532 |
|
| 533 |
# Nested unordered lists (2 levels) |
| 534 |
|
| 535 |
assert ( |
| 536 |
to_md( |
| 537 |
"<ul><li>top A<ul><li>nested A</li></ul></li><li>top B</li></ul>" |
| 538 |
) |
| 539 |
== "- top A\n - nested A\n- top B" |
| 540 |
) |
| 541 |
|
| 542 |
# Nested unordered lists (3 levels) |
| 543 |
|
| 544 |
assert ( |
| 545 |
to_md("<ul><li>L1<ul><li>L2<ul><li>L3</li></ul></li></ul></li></ul>") |
| 546 |
== "- L1\n - L2\n - L3" |
| 547 |
) |
| 548 |
|
| 549 |
# Mixed nesting: ol inside ul |
| 550 |
|
| 551 |
assert ( |
| 552 |
to_md( |
| 553 |
"<ul>" |
| 554 |
"<li>intro<ol>" |
| 555 |
"<li>step one</li>" |
| 556 |
"<li>step two</li>" |
| 557 |
"</ol></li>" |
| 558 |
"</ul>" |
| 559 |
) |
| 560 |
== "- intro\n 1. step one\n 2. step two" |
| 561 |
) |
| 562 |
|
| 563 |
# Mixed nesting: ul inside ol |
| 564 |
|
| 565 |
assert ( |
| 566 |
to_md( |
| 567 |
"<ol>" |
| 568 |
"<li>first<ul>" |
| 569 |
"<li>sub A</li>" |
| 570 |
"<li>sub B</li>" |
| 571 |
"</ul></li>" |
| 572 |
"<li>second</li>" |
| 573 |
"</ol>" |
| 574 |
) |
| 575 |
== "1. first\n - sub A\n - sub B\n2. second" |
| 576 |
) |
| 577 |
|
| 578 |
# Malformed HTML: missing </li> in a <ul> HTMLParser does not synthesize |
| 579 |
# implicit close events; each missing </li> is simply absent, but the next. |
| 580 |
assert ( |
| 581 |
to_md("<ul><li>item A<li>item B<li>item C</ul>") |
| 582 |
== "- item A\n- item B\n- item C" |
| 583 |
) |
| 584 |
|
| 585 |
# Without </li>, ordered-list counters cannot advance. |
| 586 |
assert ( |
| 587 |
to_md("<ol><li>one<li>two<li>three</ol>") == "1. one\n1. two\n1. three" |
| 588 |
) |
| 589 |
|
| 590 |
# Malformed HTML: missing closing </ul> |
| 591 |
|
| 592 |
assert to_md("<ul><li>item A</li><li>item B</li>") == "- item A\n- item B" |
| 593 |
|
| 594 |
# Malformed HTML: missing </li> AND missing </ul> |
| 595 |
|
| 596 |
assert to_md("<ul><li>item A<li>item B") == "- item A\n- item B" |
| 597 |
|
| 598 |
# Malformed HTML: bare text inside <ul> (no <li> wrapper) <ul> is in |
| 599 |
# IGNORE_TAGS so unwrapped text is suppressed entirely |
| 600 |
assert to_md("<ul>bare text</ul>") == "" |
| 601 |
|
| 602 |
# <code> inside <li>: inline code preserved with backticks |
| 603 |
|
| 604 |
assert ( |
| 605 |
to_md("<ul><li>run <code>cmd --flag</code> now</li></ul>") |
| 606 |
== "- run `cmd --flag` now" |
| 607 |
) |
| 608 |
|
| 609 |
# Markdown special characters inside <code> are NOT escaped |
| 610 |
assert ( |
| 611 |
to_md("<ul><li>see <code>x*2 #tag</code></li></ul>") |
| 612 |
== "- see `x*2 #tag`" |
| 613 |
) |
| 614 |
|
| 615 |
# Fenced blocks retain content and list indentation. |
| 616 |
assert ( |
| 617 |
to_md("<ul><li>code:<pre> indented\n here</pre></li></ul>") |
| 618 |
== "- code:\n ```\n indented\n here\n ```" |
| 619 |
) |
| 620 |
|
| 621 |
# Nested fenced blocks combine content indentation with list indentation. |
| 622 |
assert ( |
| 623 |
to_md( |
| 624 |
"<ul><li>outer<ul><li>inner:<pre> x = 1</pre></li></ul></li></ul>" |
| 625 |
) |
| 626 |
== "- outer\n - inner:\n ```\n x = 1\n ```" |
| 627 |
) |
| 628 |
|
| 629 |
# A first-child block shares the list marker's line. |
| 630 |
|
| 631 |
# Single item with a <p> first child |
| 632 |
assert to_md("<ul><li><p>alpha</p></li></ul>") == "- alpha" |
| 633 |
|
| 634 |
# Multiple items each with a <p> first child. |
| 635 |
assert ( |
| 636 |
to_md("<ul><li><p>alpha</p></li><li><p>beta</p></li></ul>") |
| 637 |
== "- alpha\n\n- beta" |
| 638 |
) |
| 639 |
|
| 640 |
# Multiple <p> children inside one <li> |
| 641 |
assert to_md("<ul><li><p>one</p><p>two</p></li></ul>") == "- one\n\n two" |
| 642 |
|
| 643 |
# Mixed: direct text for first item, <p> for second. |
| 644 |
assert ( |
| 645 |
to_md("<ul><li>direct</li><li><p>wrapped</p></li></ul>") |
| 646 |
== "- direct\n- wrapped" |
| 647 |
) |
| 648 |
|
| 649 |
# Numbered list with <p> children |
| 650 |
assert ( |
| 651 |
to_md("<ol><li><p>first</p></li><li><p>second</p></li></ol>") |
| 652 |
== "1. first\n\n2. second" |
| 653 |
) |
| 654 |
|
| 655 |
# <a> link as first child of <li> -- the marker must share the line |
| 656 |
assert to_md("<ul><li><a href='/x'>link</a></li></ul>") == "- [link](</x>)" |
| 657 |
|
| 658 |
# <a> with nested markup as first (and only) child of <li> |
| 659 |
assert ( |
| 660 |
to_md("<ul><li><a href='/x'><b>bold link</b></a></li></ul>") |
| 661 |
== "- [**bold link**](</x>)" |
| 662 |
) |
| 663 |
|
| 664 |
# <a> link followed by a <p> sibling inside the same <li>. |
| 665 |
assert ( |
| 666 |
to_md("<ul><li><a href='/x'>link</a><p>more</p></li></ul>") |
| 667 |
== "- [link](</x>)\n\n more" |
| 668 |
) |
| 669 |
|
| 670 |
|
| 671 |
def test_conversion_html_to_markdown_escaping(): |
| 672 |
"""Test Markdown escaping.""" |
| 673 |
|
| 674 |
def to_md(body): |
| 675 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 676 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 677 |
|
| 678 |
# Embedded backticks widen code delimiters. |
| 679 |
assert to_md("<code>a`b</code>") == "``a`b``" |
| 680 |
|
| 681 |
# Content starting or ending with a backtick gets a padding space, per |
| 682 |
# CommonMark's code-span disambiguation rule |
| 683 |
assert to_md("<code>`x</code>") == "`` `x ``" |
| 684 |
assert to_md("<code>x`</code>") == "`` x` ``" |
| 685 |
|
| 686 |
# A run of 3 backticks inside <pre> widens the fence past 3 |
| 687 |
assert to_md("<pre>boom```</pre>") == "````\nboom```\n````" |
| 688 |
|
| 689 |
# Plain content with no backticks still uses the minimal delimiter |
| 690 |
assert to_md("<pre>x</pre>") == "```\nx\n```" |
| 691 |
|
| 692 |
# Ignored containers suppress both text and Markdown markers. |
| 693 |
assert ( |
| 694 |
to_md( |
| 695 |
"<html><head><b>ignore</b></head><body><p>keep</p></body></html>" |
| 696 |
) |
| 697 |
== "keep" |
| 698 |
) |
| 699 |
|
| 700 |
# A heading marker ("# ") must not leak from a suppressed container |
| 701 |
assert ( |
| 702 |
to_md("<head><h1>hidden heading</h1></head><body>text</body>") |
| 703 |
== "text" |
| 704 |
) |
| 705 |
|
| 706 |
# A list marker ("- ") must not leak from a <li> nested inside a suppressed |
| 707 |
# container, even though <li> normally re-enables storage |
| 708 |
assert ( |
| 709 |
to_md("<head><ul><li>hidden item</li></ul></head><body>text</body>") |
| 710 |
== "text" |
| 711 |
) |
| 712 |
|
| 713 |
# <script> content (already suppressed) must not leak nested markers |
| 714 |
assert to_md("<script>ignore <b>this</b></script><p>keep</p>") == "keep" |
| 715 |
|
| 716 |
# A <pre> block fully inside a suppressed container emits nothing, not even |
| 717 |
# an empty fence |
| 718 |
assert to_md("<script>ignore<pre>code</pre></script><p>keep</p>") == "keep" |
| 719 |
|
| 720 |
# Angle destinations preserve whitespace in link targets. |
| 721 |
assert to_md("<a href='/my page'>link</a>") == "[link](</my page>)" |
| 722 |
|
| 723 |
# Nested tags are inert inside preformatted content. |
| 724 |
assert ( |
| 725 |
to_md("<pre>before <a href='/x'>link</a> after</pre>") |
| 726 |
== "```\nbefore link after\n```" |
| 727 |
) |
| 728 |
assert ( |
| 729 |
to_md("<code>before <b>bold</b> after</code>") == "`before bold after`" |
| 730 |
) |
| 731 |
|
| 732 |
# Stray code/pre/samp close tags |
| 733 |
assert to_md("</code>text") == "text" |
| 734 |
assert to_md("</pre>text") == "text" |
| 735 |
assert to_md("</samp>text") == "text" |
| 736 |
|
| 737 |
# Markdown/HTML injection via plain text content |
| 738 |
assert ( |
| 739 |
to_md("<p>Click [here](https://evil.example.com) now</p>") |
| 740 |
== r"Click \[here\]\(https://evil.example.com\) now" |
| 741 |
) |
| 742 |
assert ( |
| 743 |
to_md("<p>An image  too</p>") |
| 744 |
== r"An image \!\[x\]\(https://evil.example.com/x.png\) too" |
| 745 |
) |
| 746 |
|
| 747 |
# A literal backslash must itself be escaped |
| 748 |
assert to_md("<p>back\\*slash</p>") == r"back\\\*slash" |
| 749 |
|
| 750 |
# '_' (CommonMark's other emphasis delimiter) and '~' (GFM/chat- dialect |
| 751 |
# strikethrough) are escaped unconditionally, the same as '*'. |
| 752 |
assert to_md("<p>_literal_</p>") == r"\_literal\_" |
| 753 |
assert to_md("<p>my_variable_name</p>") == r"my\_variable\_name" |
| 754 |
assert to_md("<p>~strikethrough~</p>") == r"\~strikethrough\~" |
| 755 |
|
| 756 |
# Entity-encoded HTML (decoded to literal "<"/">" text by the parser) must |
| 757 |
# not survive into the Markdown output unescaped |
| 758 |
assert ( |
| 759 |
to_md("<p>previously <script>alert(1)</script></p>") |
| 760 |
== r"previously \<script\>alert\(1\)\</script\>" |
| 761 |
) |
| 762 |
|
| 763 |
# href cannot break out of the link destination |
| 764 |
assert to_md( |
| 765 |
'<a href="https://safe.example.com)[FAKE](https://evil.example.com/p)">' |
| 766 |
"legit link</a>" |
| 767 |
) == ( |
| 768 |
"[legit link]" |
| 769 |
"(<https://safe.example.com)[FAKE](https://evil.example.com/p)>)" |
| 770 |
) |
| 771 |
|
| 772 |
# A '<' or '>' inside the href itself must be escaped, since both are |
| 773 |
# meaningful within the angle-bracket destination form. |
| 774 |
assert to_md('<a href="https://x.example.com/<script>">y</a>') == ( |
| 775 |
r"[y](<https://x.example.com/\<script\>>)" |
| 776 |
) |
| 777 |
|
| 778 |
# Strip line endings before placing a URL in an angle-bracket destination. |
| 779 |
assert ( |
| 780 |
to_md('<a href="https://safe/x\n\n# injected">click</a>') |
| 781 |
== "[click](<https://safe/x# injected>)" |
| 782 |
) |
| 783 |
|
| 784 |
# Neutralize schemes that can execute content or expose local files. |
| 785 |
assert to_md('<a href="javascript:alert(1)">click me</a>') == ( |
| 786 |
"[click me](<#>)" |
| 787 |
) |
| 788 |
assert to_md('<a href="data:text/html,x">click</a>') == "[click](<#>)" |
| 789 |
assert to_md('<a href="vbscript:msgbox(1)">click</a>') == "[click](<#>)" |
| 790 |
assert to_md('<a href="file:///etc/passwd">click</a>') == "[click](<#>)" |
| 791 |
assert to_md('<a href="JaVaScRiPt:alert(1)">click</a>') == "[click](<#>)" |
| 792 |
|
| 793 |
# Leading or trailing whitespace must not defeat scheme detection. |
| 794 |
assert to_md('<a href=" javascript:alert(1)">click</a>') == ( |
| 795 |
"[click](<#>)" |
| 796 |
) |
| 797 |
assert to_md('<a href=" \tjavascript:alert(1)">click</a>') == ( |
| 798 |
"[click](<#>)" |
| 799 |
) |
| 800 |
assert to_md('<a href="javascript:alert(1) ">click</a>') == ( |
| 801 |
"[click](<#>)" |
| 802 |
) |
| 803 |
|
| 804 |
# BiDi override/embedding characters must not defeat scheme detection. |
| 805 |
assert to_md('<a href="javascript:alert(1)">click</a>') == ("[click](<#>)") |
| 806 |
assert to_md('<a href="javascript:alert(1)">click</a>') == ("[click](<#>)") |
| 807 |
# U+2066 (LEFT-TO-RIGHT ISOLATE) must also be stripped. |
| 808 |
assert to_md('<a href="javascript:alert(1)">click</a>') == ("[click](<#>)") |
| 809 |
|
| 810 |
# Keep legitimate app-specific schemes that are not explicitly unsafe. |
| 811 |
assert to_md('<a href="https://example.com">x</a>') == ( |
| 812 |
"[x](<https://example.com>)" |
| 813 |
) |
| 814 |
assert to_md('<a href="mailto:[email protected]">x</a>') == ( |
| 815 |
"[x](<mailto:[email protected]>)" |
| 816 |
) |
| 817 |
assert to_md('<a href="tel:+15551234567">x</a>') == ( |
| 818 |
"[x](<tel:+15551234567>)" |
| 819 |
) |
| 820 |
assert to_md('<a href="sms:+15551234567">x</a>') == ( |
| 821 |
"[x](<sms:+15551234567>)" |
| 822 |
) |
| 823 |
assert to_md('<a href="geo:37.7,-122.4">x</a>') == ( |
| 824 |
"[x](<geo:37.7,-122.4>)" |
| 825 |
) |
| 826 |
assert to_md('<a href="msteams:meeting?id=123">x</a>') == ( |
| 827 |
"[x](<msteams:meeting?id=123>)" |
| 828 |
) |
| 829 |
assert to_md('<a href="sharepoint://site/doc">x</a>') == ( |
| 830 |
"[x](<sharepoint://site/doc>)" |
| 831 |
) |
| 832 |
assert to_md('<a href="/relative/path">x</a>') == ("[x](</relative/path>)") |
| 833 |
assert to_md('<a href="#anchor">x</a>') == "[x](<#anchor>)" |
| 834 |
|
| 835 |
|
| 836 |
def test_conversion_html_to_markdown_line_start_escaping(): |
| 837 |
"""Test block syntax escaping.""" |
| 838 |
|
| 839 |
def to_md(body): |
| 840 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 841 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 842 |
|
| 843 |
# Escape ordered-list-shaped text only at the start of a line. |
| 844 |
assert to_md("<p>1. Apples</p><p>2. Oranges</p>") == ( |
| 845 |
"1\\. Apples\n\n2\\. Oranges" |
| 846 |
) |
| 847 |
assert to_md("<p>23. done</p>") == "23\\. done" |
| 848 |
|
| 849 |
# Match bullet markers at the start of a line. |
| 850 |
assert to_md("<p>- not a bullet, just a dash</p>") == ( |
| 851 |
"\\- not a bullet, just a dash" |
| 852 |
) |
| 853 |
assert to_md("<p>+ plus sign list?</p>") == "\\+ plus sign list?" |
| 854 |
|
| 855 |
# Escape repeated dashes that could become a thematic break. |
| 856 |
assert to_md("<p>Some text</p><p>---</p><p>more text</p>") == ( |
| 857 |
"Some text\n\n\\---\n\nmore text" |
| 858 |
) |
| 859 |
|
| 860 |
# Escaping the first dash is enough to prevent a thematic break. |
| 861 |
rendered = convert_between( |
| 862 |
NotifyFormat.MARKDOWN, |
| 863 |
NotifyFormat.HTML, |
| 864 |
to_md("<p>Some text</p><p>---</p><p>more text</p>"), |
| 865 |
) |
| 866 |
assert "<hr" not in rendered |
| 867 |
assert "<h1" not in rendered |
| 868 |
assert "<h2" not in rendered |
| 869 |
assert "---" in rendered |
| 870 |
|
| 871 |
assert to_md("<p>***</p>") == "\\*\\*\\*" |
| 872 |
assert to_md("<p>___</p>") == "\\_\\_\\_" |
| 873 |
assert to_md("<p>- - -</p>") == "\\- - -" |
| 874 |
assert to_md("<p>Hello world<br>===</p>") == "Hello world \n\\===" |
| 875 |
assert to_md("<p>Heading<br>---</p>") == "Heading \n\\---" |
| 876 |
|
| 877 |
# None of this is ambiguous -- and so isn't escaped -- anywhere other than |
| 878 |
# a true line start |
| 879 |
assert to_md("<p>well-known v1.2 it is not - really</p>") == ( |
| 880 |
"well-known v1.2 it is not - really" |
| 881 |
) |
| 882 |
assert to_md("<p>price is $5.00</p>") == "price is $5.00" |
| 883 |
assert to_md("<p>a-b-c</p>") == "a-b-c" |
| 884 |
assert to_md("<p>5 - 3 = 2</p>") == "5 - 3 = 2" |
| 885 |
|
| 886 |
|
| 887 |
def test_conversion_html_to_markdown_hardening(): |
| 888 |
"""Test malformed stack input.""" |
| 889 |
|
| 890 |
def to_md(body): |
| 891 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 892 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 893 |
|
| 894 |
# Stray close tags before any matching open tag |
| 895 |
|
| 896 |
# </ul> and </ol> take the early-return path in handle_endtag |
| 897 |
assert to_md("</ul>text") == "text" |
| 898 |
assert to_md("</ol>text") == "text" |
| 899 |
|
| 900 |
# </li> finds no open <li> anywhere on the stack and is a no-op -- the |
| 901 |
# text that follows is unindented and stored normally |
| 902 |
assert to_md("</li>text") == "text" |
| 903 |
|
| 904 |
# Multiple stray close tags in a row must not crash or corrupt state |
| 905 |
assert to_md("</ul></ol></li>preamble") == "preamble" |
| 906 |
|
| 907 |
# A valid list after a stray close must still render correctly |
| 908 |
assert to_md("</ul><ul><li>A</li><li>B</li></ul>") == "- A\n- B" |
| 909 |
|
| 910 |
# A stray close tag with content on BOTH sides must be a complete no-op, |
| 911 |
# not just absorbed because nothing preceded it. |
| 912 |
assert to_md("a</ul>b") == "ab" |
| 913 |
assert to_md("a</ol>b") == "ab" |
| 914 |
assert to_md("a</li>b") == "ab" |
| 915 |
assert to_md("a</blockquote>b") == "ab" |
| 916 |
assert to_md("a</td>b") == "ab" |
| 917 |
assert to_md("a</th>b") == "ab" |
| 918 |
|
| 919 |
# A stray <td>/<th> close still falls through cleanly when content follows. |
| 920 |
assert to_md("<p>a</td>b</p>") == "ab" |
| 921 |
|
| 922 |
# _make_frame() empty-stack guard |
| 923 |
conv = HTMLMarkdownConverter() |
| 924 |
|
| 925 |
# Force the stack empty -- this can only happen via direct attribute |
| 926 |
# manipulation, never through the public parsing API |
| 927 |
conv._stack = [] |
| 928 |
frame = conv._make_frame("div") |
| 929 |
|
| 930 |
# The fallback defaults must match the root sentinel values |
| 931 |
assert frame["tag"] == "div" |
| 932 |
assert frame["do_store"] is True |
| 933 |
assert frame["preserve_cr"] is False |
| 934 |
assert frame["list_type"] is None |
| 935 |
assert frame["depth"] == 0 |
| 936 |
assert frame["counter"] is None |
| 937 |
assert frame["list_do_store"] is True |
| 938 |
|
| 939 |
# A stale open-tag count must not corrupt the stack. |
| 940 |
conv = HTMLMarkdownConverter() |
| 941 |
conv._tag_open_counts["nonexistent"] = 1 |
| 942 |
conv._pop_to("nonexistent") # must not raise or corrupt state |
| 943 |
assert len(conv._stack) == 1 # only the root sentinel remains |
| 944 |
|
| 945 |
# ignore content found in head |
| 946 |
assert ( |
| 947 |
to_md( |
| 948 |
"<head>" |
| 949 |
+ "<ul>" * 50 |
| 950 |
+ "<li>hidden</li>" |
| 951 |
+ "</ul>" * 50 |
| 952 |
+ "</head><body>text</body>" |
| 953 |
) |
| 954 |
== "text" |
| 955 |
) |
| 956 |
|
| 957 |
# deep <ul> nesting still resolve correctly. |
| 958 |
assert ( |
| 959 |
to_md("<ul>" * 50 + "<li>visible</li>" + "</ul>" * 50) == "- visible" |
| 960 |
) |
| 961 |
|
| 962 |
# List indentation is capped at LIST_DEPTH_MAX --- |
| 963 |
assert LIST_DEPTH_MAX == 4 |
| 964 |
|
| 965 |
one_per_level = "<ul><li>x" * 10 + "</li></ul>" * 10 |
| 966 |
out = to_md(one_per_level) |
| 967 |
lines = out.split("\n") |
| 968 |
assert len(lines) == 10 |
| 969 |
# Indent grows for the first LIST_DEPTH_MAX levels... |
| 970 |
assert lines[0] == "- x" |
| 971 |
assert lines[1] == " - x" |
| 972 |
assert lines[2] == " - x" |
| 973 |
assert lines[3] == " - x" |
| 974 |
# ...then holds steady for every level beyond the cap |
| 975 |
for line in lines[4:]: |
| 976 |
assert line == " - x" |
| 977 |
|
| 978 |
# Performance: same shape, large enough that the old O(N^2) |
| 979 |
n = 20000 |
| 980 |
deep = "<ul><li>x" * n + "</li></ul>" * n |
| 981 |
start = default_timer() |
| 982 |
out = to_md(deep) |
| 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 |
# Performance: many UNCLOSED <li> tags nested directly inside one another. |
| 992 |
n = 20000 |
| 993 |
html = "<li>x" * n |
| 994 |
start = default_timer() |
| 995 |
out = to_md(html) |
| 996 |
elapsed = default_timer() - start |
| 997 |
assert len(out) < 10 * n # output itself is linear, not quadratic |
| 998 |
# Generous bound -- see the note on the equivalent check above. |
| 999 |
assert elapsed < 30.0 |
| 1000 |
|
| 1001 |
# Performance: many open <blockquote> tags followed by many closing tags of |
| 1002 |
# a *different* kind that's never actually open ("</pre>"). |
| 1003 |
n = 20000 |
| 1004 |
html = "<blockquote>" * n + "</pre>" * n |
| 1005 |
start = default_timer() |
| 1006 |
out = to_md(html) |
| 1007 |
elapsed = default_timer() - start |
| 1008 |
assert len(out) < 20 * n |
| 1009 |
# Generous bound: this must catch a real return to quadratic |
| 1010 |
# behavior, not just run fast on a quiet dev machine -- shared or |
| 1011 |
# emulated build infrastructure (e.g. a busy Koji builder) can be |
| 1012 |
# many times slower. |
| 1013 |
assert elapsed < 15.0 |
| 1014 |
|
| 1015 |
# Blockquote depth is capped at BLOCKQUOTE_DEPTH_MAX |
| 1016 |
assert BLOCKQUOTE_DEPTH_MAX == 4 |
| 1017 |
|
| 1018 |
# Each level is its own <p>, so every line of real content is followed by a |
| 1019 |
# blank (but still "> "-prefixed) separator line. |
| 1020 |
one_per_level = "<blockquote><p>x</p>" * 10 + "</blockquote>" * 10 |
| 1021 |
out = to_md(one_per_level) |
| 1022 |
lines = out.split("\n") |
| 1023 |
assert len(lines) == 19 |
| 1024 |
content_lines = lines[0::2] |
| 1025 |
separator_lines = lines[1::2] |
| 1026 |
assert len(content_lines) == 10 |
| 1027 |
assert content_lines[0] == "> x" |
| 1028 |
assert content_lines[1] == "> > x" |
| 1029 |
assert content_lines[2] == "> > > x" |
| 1030 |
assert content_lines[3] == "> > > > x" |
| 1031 |
for line in content_lines[4:]: |
| 1032 |
assert line == "> > > > x" |
| 1033 |
# Each separator matches its preceding content line, minus the "x" |
| 1034 |
for content, separator in zip(content_lines, separator_lines): |
| 1035 |
assert separator == content[: -len("x")].rstrip() |
| 1036 |
|
| 1037 |
n = 20000 |
| 1038 |
deep = "<blockquote><p>x</p>" * n + "</blockquote>" * n |
| 1039 |
start = default_timer() |
| 1040 |
out = to_md(deep) |
| 1041 |
elapsed = default_timer() - start |
| 1042 |
assert len(out) < 20 * n |
| 1043 |
# Generous bound: this must catch a real return to quadratic |
| 1044 |
# behavior, not just run fast on a quiet dev machine -- shared or |
| 1045 |
# emulated build infrastructure (e.g. a busy Koji builder) can be |
| 1046 |
# many times slower. |
| 1047 |
assert elapsed < 15.0 |
| 1048 |
|
| 1049 |
# When emphasis or anchor tags are nested past MAX_FRAME_DEPTH, _push_frame |
| 1050 |
# returns False and the opening delimiter must NOT be emitted. |
| 1051 |
depth = MAX_FRAME_DEPTH + 1 |
| 1052 |
em_open = "<em>" * depth |
| 1053 |
em_close = "</em>" * depth |
| 1054 |
out_em = to_md(f"{em_open}text{em_close}") |
| 1055 |
# The text must appear; no unmatched bare asterisk may leak through. |
| 1056 |
assert "text" in out_em |
| 1057 |
assert out_em.replace("*", "").strip() == "text" |
| 1058 |
|
| 1059 |
# Same guard for <a> -- no unmatched "[" in the output. |
| 1060 |
a_open = '<a href="https://example.com">' * depth |
| 1061 |
a_close = "</a>" * depth |
| 1062 |
out_a = to_md(f"{a_open}text{a_close}") |
| 1063 |
assert "text" in out_a |
| 1064 |
# Count "[" and "](" -- every "[" must have a matching "](". |
| 1065 |
assert out_a.count("[") == out_a.count("](") |
| 1066 |
|
| 1067 |
# At MAX_FRAME_DEPTH the <blockquote> frame is discarded and _push_frame |
| 1068 |
# returns False. |
| 1069 |
bq_open = "<blockquote>" * depth |
| 1070 |
bq_close = "</blockquote>" * depth |
| 1071 |
out_bq = to_md(f"{bq_open}text{bq_close}") |
| 1072 |
assert "text" in out_bq |
| 1073 |
# Every ">" line-prefix must correspond to a real nested blockquote level. |
| 1074 |
first_line = out_bq.splitlines()[0] if out_bq else "" |
| 1075 |
gt_count = len(first_line) - len(first_line.lstrip("> ")) |
| 1076 |
assert gt_count <= BLOCKQUOTE_DEPTH_MAX * 2 # ">" + " " per level |
| 1077 |
|
| 1078 |
# At MAX_FRAME_DEPTH the <li> frame is discarded and _push_frame returns |
| 1079 |
# False. No _ListMarker must be appended without a backing frame. |
| 1080 |
li_open = "<ul>" + "<li>" * depth |
| 1081 |
li_close = "</li>" * depth + "</ul>" |
| 1082 |
out_li = to_md(f"{li_open}text{li_close}") |
| 1083 |
assert "text" in out_li |
| 1084 |
|
| 1085 |
|
| 1086 |
def test_conversion_headings_to_bold(): |
| 1087 |
"""Convert supported ATX headings for chat dialects without headings.""" |
| 1088 |
|
| 1089 |
# Convert the common heading forms generated from HTML. |
| 1090 |
assert commonmark_headings_to_bold("# Alert") == "**Alert**" |
| 1091 |
assert commonmark_headings_to_bold("###### Alert") == "**Alert**" |
| 1092 |
|
| 1093 |
# An optional closing sequence of "#" is stripped, not kept as text. |
| 1094 |
assert commonmark_headings_to_bold("## foo ##") == "**foo**" |
| 1095 |
assert commonmark_headings_to_bold("# foo #####") == "**foo**" |
| 1096 |
|
| 1097 |
# A hash without preceding whitespace remains part of the heading text. |
| 1098 |
assert commonmark_headings_to_bold("# foo#") == "**foo#**" |
| 1099 |
|
| 1100 |
# Preserve up to three spaces allowed before a heading. |
| 1101 |
assert commonmark_headings_to_bold(" # one space") == " **one space**" |
| 1102 |
assert commonmark_headings_to_bold(" # three spaces") == ( |
| 1103 |
" **three spaces**" |
| 1104 |
) |
| 1105 |
|
| 1106 |
# Four leading spaces make an indented code block, not a heading. |
| 1107 |
four_spaces = " # four spaces" |
| 1108 |
assert commonmark_headings_to_bold(four_spaces) == four_spaces |
| 1109 |
|
| 1110 |
# Empty headings do not produce empty bold markers. |
| 1111 |
assert commonmark_headings_to_bold("###") == "" |
| 1112 |
assert commonmark_headings_to_bold("### ") == "" |
| 1113 |
|
| 1114 |
# Heading text requires whitespace after its opening hashes. |
| 1115 |
literal = "#nospace" |
| 1116 |
assert commonmark_headings_to_bold(literal) == literal |
| 1117 |
|
| 1118 |
# Inline code spans are never touched. |
| 1119 |
assert commonmark_headings_to_bold("`# inline code`") == ( |
| 1120 |
"`# inline code`" |
| 1121 |
) |
| 1122 |
|
| 1123 |
# Backtick and tilde fences protect heading-like code. |
| 1124 |
fenced_backtick = "```\n# not a heading\n```" |
| 1125 |
assert commonmark_headings_to_bold(fenced_backtick) == fenced_backtick |
| 1126 |
|
| 1127 |
fenced_tilde = "~~~\n# not a heading either\n~~~" |
| 1128 |
assert commonmark_headings_to_bold(fenced_tilde) == fenced_tilde |
| 1129 |
|
| 1130 |
# An unfinished fence protects the remaining text. |
| 1131 |
unterminated = "```\n# still not a heading\nmore text" |
| 1132 |
assert commonmark_headings_to_bold(unterminated) == unterminated |
| 1133 |
|
| 1134 |
# A real heading before and after a fenced block is still converted. |
| 1135 |
mixed = "# Before\n```\n# inside\n```\n# After" |
| 1136 |
assert commonmark_headings_to_bold(mixed) == ( |
| 1137 |
"**Before**\n```\n# inside\n```\n**After**" |
| 1138 |
) |
| 1139 |
|
| 1140 |
# Preserve blockquote markers emitted by HTML-to-CommonMark conversion. |
| 1141 |
assert commonmark_headings_to_bold("> # Alert") == "> **Alert**" |
| 1142 |
assert commonmark_headings_to_bold("> > # Alert") == "> > **Alert**" |
| 1143 |
assert commonmark_headings_to_bold("> > > # Alert") == ("> > > **Alert**") |
| 1144 |
|
| 1145 |
# Preserve unordered and ordered list markers. |
| 1146 |
assert commonmark_headings_to_bold("- # Alert") == "- **Alert**" |
| 1147 |
assert commonmark_headings_to_bold("* # Alert") == "* **Alert**" |
| 1148 |
assert commonmark_headings_to_bold("+ # Alert") == "+ **Alert**" |
| 1149 |
assert commonmark_headings_to_bold("1. # Alert") == "1. **Alert**" |
| 1150 |
assert commonmark_headings_to_bold("2) # Alert") == "2) **Alert**" |
| 1151 |
|
| 1152 |
# Preserve combined blockquote and list markers. |
| 1153 |
assert commonmark_headings_to_bold("> - # Alert") == "> - **Alert**" |
| 1154 |
|
| 1155 |
# Keep the blockquote marker for an empty heading. |
| 1156 |
assert commonmark_headings_to_bold("> ###") == "> " |
| 1157 |
|
| 1158 |
# Recognize CRLF fences without protecting later headings. |
| 1159 |
crlf_fence = "```\r\ncode\r\n```\r\n# Real Heading" |
| 1160 |
assert commonmark_headings_to_bold(crlf_fence) == ( |
| 1161 |
"```\r\ncode\r\n```\r\n**Real Heading**" |
| 1162 |
) |
| 1163 |
|
| 1164 |
# Invalid backtick fence labels do not protect later headings. |
| 1165 |
invalid_opener = ( |
| 1166 |
"Some `inline` text\n" |
| 1167 |
"```code`with`backtick info string\n" |
| 1168 |
"more text\n" |
| 1169 |
"# Real Heading" |
| 1170 |
) |
| 1171 |
assert commonmark_headings_to_bold(invalid_opener) == ( |
| 1172 |
"Some `inline` text\n" |
| 1173 |
"```code`with`backtick info string\n" |
| 1174 |
"more text\n" |
| 1175 |
"**Real Heading**" |
| 1176 |
) |
| 1177 |
|
| 1178 |
# Tilde fence labels may contain backticks. |
| 1179 |
tilde_with_backtick = "~~~code`ok\nreal code\n~~~" |
| 1180 |
assert ( |
| 1181 |
commonmark_headings_to_bold(tilde_with_backtick) == tilde_with_backtick |
| 1182 |
) |
| 1183 |
|
| 1184 |
# Preserve heading-like text inside a quoted tilde fence. |
| 1185 |
quoted_tilde_fence = "> ~~~\n> # literal code\n> ~~~" |
| 1186 |
assert ( |
| 1187 |
commonmark_headings_to_bold(quoted_tilde_fence) == quoted_tilde_fence |
| 1188 |
) |
| 1189 |
|
| 1190 |
# Repeating ``"- "`` starts a sibling list item, so these are three |
| 1191 |
# separate items. The middle heading remains real Markdown and converts. |
| 1192 |
three_sibling_items = "- ~~~\n- # literal code\n- ~~~~" |
| 1193 |
assert commonmark_headings_to_bold(three_sibling_items) == ( |
| 1194 |
"- ~~~\n- **literal code**\n- ~~~~" |
| 1195 |
) |
| 1196 |
|
| 1197 |
# A backtick closer wider than its opener still closes the fence, even |
| 1198 |
# when both are nested inside a blockquote. |
| 1199 |
quoted_wider_closer = "> ```\n> # literal code\n> ````" |
| 1200 |
assert ( |
| 1201 |
commonmark_headings_to_bold(quoted_wider_closer) == quoted_wider_closer |
| 1202 |
) |
| 1203 |
|
| 1204 |
# Nested blockquotes around a fence are recognized at every level. |
| 1205 |
nested_quoted_fence = "> > ~~~\n> > # literal code\n> > ~~~" |
| 1206 |
assert ( |
| 1207 |
commonmark_headings_to_bold(nested_quoted_fence) == nested_quoted_fence |
| 1208 |
) |
| 1209 |
|
| 1210 |
# Quote markers may have up to three leading spaces. |
| 1211 |
assert commonmark_headings_to_bold(" > # Alert") == " > **Alert**" |
| 1212 |
indented_quoted_fence = " > ~~~\n > # literal code\n > ~~~" |
| 1213 |
assert ( |
| 1214 |
commonmark_headings_to_bold(indented_quoted_fence) |
| 1215 |
== indented_quoted_fence |
| 1216 |
) |
| 1217 |
|
| 1218 |
# Four leading spaces create indented code, not a top-level fence. |
| 1219 |
# The following real heading must therefore still be converted. |
| 1220 |
four_space_fence_then_heading = ( |
| 1221 |
" ~~~\n not a real fence\n ~~~\n# Real Heading" |
| 1222 |
) |
| 1223 |
assert commonmark_headings_to_bold(four_space_fence_then_heading) == ( |
| 1224 |
" ~~~\n not a real fence\n ~~~\n**Real Heading**" |
| 1225 |
) |
| 1226 |
|
| 1227 |
# An ordered-list marker can be wider than three characters ("123. " |
| 1228 |
# is five), so its continuation lines need more than three leading |
| 1229 |
# spaces too. A real heading after the fence must still convert. |
| 1230 |
wide_ordered_fence = "123. ~~~\n # literal\n ~~~\n\n# real" |
| 1231 |
assert commonmark_headings_to_bold(wide_ordered_fence) == ( |
| 1232 |
"123. ~~~\n # literal\n ~~~\n\n**real**" |
| 1233 |
) |
| 1234 |
|
| 1235 |
# A list containing a quote puts the list marker first, while continuation |
| 1236 |
# lines replace it with spaces. Both prefix orders belong to one container. |
| 1237 |
list_then_quote_fence = "- > ~~~\n > # literal\n > ~~~\n\n# real" |
| 1238 |
assert commonmark_headings_to_bold(list_then_quote_fence) == ( |
| 1239 |
"- > ~~~\n > # literal\n > ~~~\n\n**real**" |
| 1240 |
) |
| 1241 |
|
| 1242 |
# Up to three leading spaces may belong to a top-level fence rather than |
| 1243 |
# a list. Its heading-like content must remain protected. |
| 1244 |
lightly_indented_fence = " ~~~\n# literal\n ~~~\n# real" |
| 1245 |
assert commonmark_headings_to_bold(lightly_indented_fence) == ( |
| 1246 |
" ~~~\n# literal\n ~~~\n**real**" |
| 1247 |
) |
| 1248 |
|
| 1249 |
# Opening and closing fences have independent indentation allowances. |
| 1250 |
mismatched_indent_fence = "~~~\n# literal\n ~~~\n# real" |
| 1251 |
assert commonmark_headings_to_bold(mismatched_indent_fence) == ( |
| 1252 |
"~~~\n# literal\n ~~~\n**real**" |
| 1253 |
) |
| 1254 |
|
| 1255 |
# The same closer slack applies inside a blockquote. |
| 1256 |
quoted_mismatched_indent_fence = "> ~~~\n> # literal\n> ~~~\n> # real" |
| 1257 |
assert commonmark_headings_to_bold(quoted_mismatched_indent_fence) == ( |
| 1258 |
"> ~~~\n> # literal\n> ~~~\n> **real**" |
| 1259 |
) |
| 1260 |
|
| 1261 |
# A lightly indented fence can continue a list item without repeating |
| 1262 |
# its marker. An unfinished fence stops when that list item ends. |
| 1263 |
unclosed_narrow_list_fence = "- intro\n ~~~\n # literal\n\n# real" |
| 1264 |
assert commonmark_headings_to_bold(unclosed_narrow_list_fence) == ( |
| 1265 |
"- intro\n ~~~\n # literal\n\n**real**" |
| 1266 |
) |
| 1267 |
|
| 1268 |
# A later top-level fence cannot close the list's unfinished fence. |
| 1269 |
unclosed_narrow_list_fence_with_later_fence = ( |
| 1270 |
"- intro\n ~~~\n # literal\n\n# real\n\n~~~\nunrelated\n~~~" |
| 1271 |
) |
| 1272 |
assert commonmark_headings_to_bold( |
| 1273 |
unclosed_narrow_list_fence_with_later_fence |
| 1274 |
) == ("- intro\n ~~~\n # literal\n\n**real**\n\n~~~\nunrelated\n~~~") |
| 1275 |
|
| 1276 |
# Blank lines before the fence may remain within the list item. |
| 1277 |
unclosed_narrow_list_fence_with_blank = ( |
| 1278 |
"- intro\n\n ~~~\n # literal\n\n# real" |
| 1279 |
) |
| 1280 |
assert commonmark_headings_to_bold( |
| 1281 |
unclosed_narrow_list_fence_with_blank |
| 1282 |
) == ("- intro\n\n ~~~\n # literal\n\n**real**") |
| 1283 |
|
| 1284 |
# Light indentation without an earlier list marker is top-level. |
| 1285 |
unmarked_indent_no_list_behind_it = ( |
| 1286 |
"Some intro text\n ~~~\n# literal\n ~~~\n# real" |
| 1287 |
) |
| 1288 |
assert commonmark_headings_to_bold(unmarked_indent_no_list_behind_it) == ( |
| 1289 |
"Some intro text\n ~~~\n# literal\n ~~~\n**real**" |
| 1290 |
) |
| 1291 |
|
| 1292 |
# The paragraph lazily continues the list, but one-space fence indentation |
| 1293 |
# is still insufficient for the two-space item. |
| 1294 |
list_ended_by_unindented_paragraph = ( |
| 1295 |
"- intro\nunindented paragraph\n ~~~\n# literal\n ~~~\n# real" |
| 1296 |
) |
| 1297 |
assert commonmark_headings_to_bold(list_ended_by_unindented_paragraph) == ( |
| 1298 |
"- intro\nunindented paragraph\n ~~~\n# literal\n ~~~\n**real**" |
| 1299 |
) |
| 1300 |
|
| 1301 |
# Indented list text may appear between the marker and fence. |
| 1302 |
unclosed_narrow_list_fence_with_paragraph = ( |
| 1303 |
"- intro\n more text in the same item\n ~~~\n # literal\n\n# real" |
| 1304 |
) |
| 1305 |
assert commonmark_headings_to_bold( |
| 1306 |
unclosed_narrow_list_fence_with_paragraph |
| 1307 |
) == ( |
| 1308 |
"- intro\n more text in the same item\n ~~~\n # literal\n\n**real**" |
| 1309 |
) |
| 1310 |
|
| 1311 |
# The HTML converter replaces a list marker with equal-width spaces on |
| 1312 |
# continuation lines. Test that real output as well as synthetic input. |
| 1313 |
list_only_fence_html = ( |
| 1314 |
"<ul><li><pre><code># literal\nmore</code></pre></li></ul>" |
| 1315 |
"<h1>Real Heading</h1>" |
| 1316 |
) |
| 1317 |
list_only_fence_body = html_to_markdown(list_only_fence_html) |
| 1318 |
assert list_only_fence_body == ( |
| 1319 |
"- ```\n # literal\n more\n ```\n\n# Real Heading" |
| 1320 |
) |
| 1321 |
converted = commonmark_headings_to_bold(list_only_fence_body) |
| 1322 |
# The heading-like line inside the fence stays literal code. |
| 1323 |
assert " # literal\n" in converted |
| 1324 |
# A real heading placed after the fenced block still converts. |
| 1325 |
assert converted.endswith("\n**Real Heading**") |
| 1326 |
|
| 1327 |
# Also cover a preceding paragraph and the wider numbered-list marker. |
| 1328 |
text_then_fence_html = ( |
| 1329 |
"<ul><li>intro<pre><code># literal\nmore</code></pre></li></ul>" |
| 1330 |
"<h1>Real Heading</h1>" |
| 1331 |
) |
| 1332 |
text_then_fence_body = html_to_markdown(text_then_fence_html) |
| 1333 |
assert text_then_fence_body == ( |
| 1334 |
"- intro\n ```\n # literal\n more\n ```\n\n# Real Heading" |
| 1335 |
) |
| 1336 |
converted = commonmark_headings_to_bold(text_then_fence_body) |
| 1337 |
assert " # literal\n" in converted |
| 1338 |
assert converted.endswith("\n**Real Heading**") |
| 1339 |
|
| 1340 |
ordered_fence_html = ( |
| 1341 |
"<ol><li><pre><code># literal\nmore</code></pre></li></ol>" |
| 1342 |
"<h1>Real Heading</h1>" |
| 1343 |
) |
| 1344 |
ordered_fence_body = html_to_markdown(ordered_fence_html) |
| 1345 |
assert ordered_fence_body == ( |
| 1346 |
"1. ```\n # literal\n more\n ```\n\n# Real Heading" |
| 1347 |
) |
| 1348 |
converted = commonmark_headings_to_bold(ordered_fence_body) |
| 1349 |
assert " # literal\n" in converted |
| 1350 |
assert converted.endswith("\n**Real Heading**") |
| 1351 |
|
| 1352 |
# List continuation spacing moves before the quote marker on later lines. |
| 1353 |
quoted_list_fence_html = ( |
| 1354 |
"<blockquote><ul><li>intro" |
| 1355 |
"<pre><code># literal\nmore</code></pre></li></ul></blockquote>" |
| 1356 |
"<h1>Real Heading</h1>" |
| 1357 |
) |
| 1358 |
quoted_list_fence_body = html_to_markdown(quoted_list_fence_html) |
| 1359 |
assert quoted_list_fence_body == ( |
| 1360 |
"> - intro\n > ```\n > # literal\n > more\n > ```" |
| 1361 |
"\n\n# Real Heading" |
| 1362 |
) |
| 1363 |
converted = commonmark_headings_to_bold(quoted_list_fence_body) |
| 1364 |
assert " > # literal\n" in converted |
| 1365 |
assert converted.endswith("\n**Real Heading**") |
| 1366 |
|
| 1367 |
# Leading list indentation contributes to the continuation width, whether |
| 1368 |
# the fence begins the item or follows its introductory text. |
| 1369 |
indented_marker_then_fence = " - ~~~\n # literal\n ~~~\n# real" |
| 1370 |
assert commonmark_headings_to_bold(indented_marker_then_fence) == ( |
| 1371 |
" - ~~~\n # literal\n ~~~\n**real**" |
| 1372 |
) |
| 1373 |
|
| 1374 |
indented_marker_with_intro = " - intro\n ~~~\n # literal\n\n# real" |
| 1375 |
assert commonmark_headings_to_bold(indented_marker_with_intro) == ( |
| 1376 |
" - intro\n ~~~\n # literal\n\n**real**" |
| 1377 |
) |
| 1378 |
|
| 1379 |
# A literal "- " inside a closed fence must not create list state for the |
| 1380 |
# unfinished top-level fence that follows it. |
| 1381 |
marker_like_text_inside_closed_fence = ( |
| 1382 |
"~~~\n- literal\n ~~~\n ~~~\n# still code" |
| 1383 |
) |
| 1384 |
assert commonmark_headings_to_bold( |
| 1385 |
marker_like_text_inside_closed_fence |
| 1386 |
) == ("~~~\n- literal\n ~~~\n ~~~\n# still code") |
| 1387 |
|
| 1388 |
# Ending an inner list restores the still-open outer list width. |
| 1389 |
nested_list_falls_back_to_outer = ( |
| 1390 |
"- outer\n - inner\n text\n ~~~\n # literal\n\n# real" |
| 1391 |
) |
| 1392 |
assert commonmark_headings_to_bold(nested_list_falls_back_to_outer) == ( |
| 1393 |
"- outer\n - inner\n text\n ~~~\n # literal\n\n**real**" |
| 1394 |
) |
| 1395 |
|
| 1396 |
# An unindented paragraph may lazily continue an open list item. |
| 1397 |
lazy_continuation_keeps_list_open = ( |
| 1398 |
"- intro\nlazy continuation\n ~~~\n # literal\n\n# real" |
| 1399 |
) |
| 1400 |
assert commonmark_headings_to_bold(lazy_continuation_keeps_list_open) == ( |
| 1401 |
"- intro\nlazy continuation\n ~~~\n # literal\n\n**real**" |
| 1402 |
) |
| 1403 |
|
| 1404 |
# A new list marker ends lazy paragraph continuation. |
| 1405 |
new_marker_ends_lazy_continuation = ( |
| 1406 |
"- intro\nordinary text\n- newitem\n ~~~\n # literal\n\n# real" |
| 1407 |
) |
| 1408 |
assert commonmark_headings_to_bold(new_marker_ends_lazy_continuation) == ( |
| 1409 |
"- intro\nordinary text\n- newitem\n ~~~\n # literal\n\n**real**" |
| 1410 |
) |
| 1411 |
|
| 1412 |
# A list fence closer may add only three columns of indentation. |
| 1413 |
# Greater indentation leaves it open until the list ends. |
| 1414 |
wildly_overindented_list_closer = ( |
| 1415 |
"- intro\n ```\n code\n ```\n# real" |
| 1416 |
) |
| 1417 |
assert commonmark_headings_to_bold(wildly_overindented_list_closer) == ( |
| 1418 |
"- intro\n ```\n code\n ```\n**real**" |
| 1419 |
) |
| 1420 |
|
| 1421 |
# The same three-column closer limit applies outside lists. |
| 1422 |
wildly_overindented_top_level_closer = "```\ncode\n ```\n# after" |
| 1423 |
assert commonmark_headings_to_bold( |
| 1424 |
wildly_overindented_top_level_closer |
| 1425 |
) == ("```\ncode\n ```\n# after") |
| 1426 |
|
| 1427 |
# ``-\t`` reaches column four. Two spaces cannot continue that list, so |
| 1428 |
# the following unfinished fence is top-level and protects the remainder. |
| 1429 |
tab_expanded_marker_width = "-\tintro\n ```\n # literal\n\n# real" |
| 1430 |
assert commonmark_headings_to_bold(tab_expanded_marker_width) == ( |
| 1431 |
tab_expanded_marker_width |
| 1432 |
) |
| 1433 |
|
| 1434 |
# A tab reaches the same column as ``-\t``, keeping the fence in the list. |
| 1435 |
tab_expanded_continuation_width = "-\tintro\n\t```\n\t# literal\n\n# real" |
| 1436 |
assert commonmark_headings_to_bold(tab_expanded_continuation_width) == ( |
| 1437 |
"-\tintro\n\t```\n\t# literal\n\n**real**" |
| 1438 |
) |
| 1439 |
|
| 1440 |
# Accept quote-first continuation lines as well as Apprise's list-first |
| 1441 |
# output when a fenced block is nested in both containers. |
| 1442 |
quote_then_list_continuation = "- > ~~~\n> # literal\n> ~~~\n\n# real" |
| 1443 |
assert commonmark_headings_to_bold(quote_then_list_continuation) == ( |
| 1444 |
"- > ~~~\n> # literal\n> ~~~\n\n**real**" |
| 1445 |
) |
| 1446 |
|
| 1447 |
# A quote-first closer still needs the list's full indentation. |
| 1448 |
quote_then_list_insufficient_width = ( |
| 1449 |
"- > ~~~\n> # literal\n> ~~~\n> ~~~\n\n# real" |
| 1450 |
) |
| 1451 |
assert commonmark_headings_to_bold(quote_then_list_insufficient_width) == ( |
| 1452 |
"- > ~~~\n> # literal\n> ~~~\n> ~~~\n\n**real**" |
| 1453 |
) |
| 1454 |
|
| 1455 |
# List indentation without the required quote marker ends the container. |
| 1456 |
list_width_met_but_no_quote_at_all = ( |
| 1457 |
"- > ~~~\n text without quote\n> ~~~\n\n# real" |
| 1458 |
) |
| 1459 |
assert commonmark_headings_to_bold(list_width_met_but_no_quote_at_all) == ( |
| 1460 |
"- > ~~~\n text without quote\n> ~~~\n\n**real**" |
| 1461 |
) |
| 1462 |
|
| 1463 |
# A bare quote marker still satisfies its quote depth. |
| 1464 |
bare_quote_marker_line_in_combo = "- > ~~~\n>\n> ~~~\n\n# real" |
| 1465 |
assert commonmark_headings_to_bold(bare_quote_marker_line_in_combo) == ( |
| 1466 |
"- > ~~~\n>\n> ~~~\n\n**real**" |
| 1467 |
) |
| 1468 |
|
| 1469 |
# A heading ends the list, making the following unfinished fence top-level. |
| 1470 |
heading_ends_list_before_fence = ( |
| 1471 |
"- intro\n# outside\n ~~~\n # literal\n# still code" |
| 1472 |
) |
| 1473 |
assert commonmark_headings_to_bold(heading_ends_list_before_fence) == ( |
| 1474 |
"- intro\n**outside**\n ~~~\n # literal\n# still code" |
| 1475 |
) |
| 1476 |
|
| 1477 |
# A heading inside a list marker cannot gain a lazy continuation. |
| 1478 |
marker_content_is_heading = ( |
| 1479 |
"- # heading\noutside\n ~~~\n # literal\n# still code" |
| 1480 |
) |
| 1481 |
assert commonmark_headings_to_bold(marker_content_is_heading) == ( |
| 1482 |
"- **heading**\noutside\n ~~~\n # literal\n# still code" |
| 1483 |
) |
| 1484 |
|
| 1485 |
# Blockquotes and thematic breaks also end lazy list continuation. |
| 1486 |
blockquote_ends_list_before_fence = ( |
| 1487 |
"- intro\n> outside\n ~~~\n # literal\n# still code" |
| 1488 |
) |
| 1489 |
assert commonmark_headings_to_bold(blockquote_ends_list_before_fence) == ( |
| 1490 |
"- intro\n> outside\n ~~~\n # literal\n# still code" |
| 1491 |
) |
| 1492 |
|
| 1493 |
thematic_break_ends_list_before_fence = ( |
| 1494 |
"- intro\n---\n ~~~\n # literal\n# still code" |
| 1495 |
) |
| 1496 |
assert commonmark_headings_to_bold( |
| 1497 |
thematic_break_ends_list_before_fence |
| 1498 |
) == ("- intro\n---\n ~~~\n # literal\n# still code") |
| 1499 |
|
| 1500 |
# CRLF input follows the same thematic-break boundary rule. |
| 1501 |
thematic_break_ends_list_crlf = ( |
| 1502 |
"- intro\r\n---\r\n ~~~\r\n # literal\r\n# still code" |
| 1503 |
) |
| 1504 |
assert commonmark_headings_to_bold(thematic_break_ends_list_crlf) == ( |
| 1505 |
"- intro\r\n---\r\n ~~~\r\n # literal\r\n# still code" |
| 1506 |
) |
| 1507 |
|
| 1508 |
# A tab at column zero reaches column four, creating indented code. |
| 1509 |
tab_at_column_zero_is_not_slack = "\t# literal" |
| 1510 |
assert ( |
| 1511 |
commonmark_headings_to_bold(tab_at_column_zero_is_not_slack) |
| 1512 |
== tab_at_column_zero_is_not_slack |
| 1513 |
) |
| 1514 |
|
| 1515 |
tab_at_column_zero_fence_is_not_slack = "\t~~~\ncode\n\t~~~\n# real" |
| 1516 |
assert commonmark_headings_to_bold( |
| 1517 |
tab_at_column_zero_fence_is_not_slack |
| 1518 |
) == ("\t~~~\ncode\n\t~~~\n**real**") |
| 1519 |
|
| 1520 |
# A tab after a quote can remain within the three-column allowance. |
| 1521 |
tab_after_quote_is_slack = ">\t# literal" |
| 1522 |
assert commonmark_headings_to_bold(tab_after_quote_is_slack) == ( |
| 1523 |
">\t**literal**" |
| 1524 |
) |
| 1525 |
|
| 1526 |
# Tabs between nested quote markers use one column of marker padding. |
| 1527 |
tab_separated_nested_quote_fence = ( |
| 1528 |
">\t>\t~~~\n>\t>\t# literal\n>\t>\t~~~\n>\t>\t# real" |
| 1529 |
) |
| 1530 |
assert commonmark_headings_to_bold(tab_separated_nested_quote_fence) == ( |
| 1531 |
">\t>\t~~~\n>\t>\t# literal\n>\t>\t~~~\n>\t>\t**real**" |
| 1532 |
) |
| 1533 |
|
| 1534 |
# Nested quote markers also work without separating spaces. |
| 1535 |
unspaced_nested_quote_fence = ">>~~~\n>>literal\n>>~~~\n>># real" |
| 1536 |
assert commonmark_headings_to_bold(unspaced_nested_quote_fence) == ( |
| 1537 |
">>~~~\n>>literal\n>>~~~\n>>**real**" |
| 1538 |
) |
| 1539 |
|
| 1540 |
# Tab-separated quote/list content uses indentation on continuation lines. |
| 1541 |
tab_separated_quote_list_fence = ( |
| 1542 |
">\t-\tintro\n>\t ~~~\n>\t # literal\n>\t ~~~\n>\t# real" |
| 1543 |
) |
| 1544 |
assert commonmark_headings_to_bold(tab_separated_quote_list_fence) == ( |
| 1545 |
">\t-\tintro\n>\t ~~~\n>\t # literal\n>\t ~~~\n>\t**real**" |
| 1546 |
) |
| 1547 |
|
| 1548 |
# HTML blocks end lazy list paragraphs, making the next fence top-level. |
| 1549 |
html_block_ends_list_before_fence = ( |
| 1550 |
"- intro\n<div>\nhtml\n</div>\n\n ~~~\n # literal\n# still code" |
| 1551 |
) |
| 1552 |
assert commonmark_headings_to_bold(html_block_ends_list_before_fence) == ( |
| 1553 |
"- intro\n<div>\nhtml\n</div>\n\n ~~~\n # literal\n# still code" |
| 1554 |
) |
| 1555 |
|
| 1556 |
html_comment_ends_list_before_fence = ( |
| 1557 |
"- intro\n<!-- comment -->\n ~~~\n # literal\n# still code" |
| 1558 |
) |
| 1559 |
assert commonmark_headings_to_bold( |
| 1560 |
html_comment_ends_list_before_fence |
| 1561 |
) == ("- intro\n<!-- comment -->\n ~~~\n # literal\n# still code") |
| 1562 |
|
| 1563 |
# A backtick in a backtick fence's info string makes the opener invalid. |
| 1564 |
invalid_backtick_info_string_not_a_fence = ( |
| 1565 |
"- intro\n ```bad`info\nlazy\n ~~~\n # literal\n# real" |
| 1566 |
) |
| 1567 |
assert commonmark_headings_to_bold( |
| 1568 |
invalid_backtick_info_string_not_a_fence |
| 1569 |
) == ("- intro\n ```bad`info\nlazy\n ~~~\n # literal\n**real**") |
| 1570 |
|
| 1571 |
# Four extra columns inside a two-column list create indented code. |
| 1572 |
six_space_indent_not_a_fence = ( |
| 1573 |
"- intro\n ```\nlazy\n ~~~\n # literal\n# real" |
| 1574 |
) |
| 1575 |
assert commonmark_headings_to_bold(six_space_indent_not_a_fence) == ( |
| 1576 |
"- intro\n ```\nlazy\n ~~~\n # literal\n**real**" |
| 1577 |
) |
| 1578 |
|
| 1579 |
# A blank line ends a blockquote fence but may remain in a plain list. |
| 1580 |
blank_line_ends_blockquote_fence = "> ~~~\n> code\n\n> # real" |
| 1581 |
assert commonmark_headings_to_bold(blank_line_ends_blockquote_fence) == ( |
| 1582 |
"> ~~~\n> code\n\n> **real**" |
| 1583 |
) |
| 1584 |
|
| 1585 |
# A fence may use up to three extra columns inside an active list. |
| 1586 |
fence_with_extra_slack_stays_in_list = ( |
| 1587 |
"1. item\n ~~~\n # literal\n ~~~\n# real" |
| 1588 |
) |
| 1589 |
assert commonmark_headings_to_bold( |
| 1590 |
fence_with_extra_slack_stays_in_list |
| 1591 |
) == ("1. item\n ~~~\n # literal\n ~~~\n**real**") |
| 1592 |
|
| 1593 |
# Active-list indentation can identify a heading without another marker. |
| 1594 |
assert commonmark_headings_to_bold("- item\n # nested") == ( |
| 1595 |
"- item\n **nested**" |
| 1596 |
) |
| 1597 |
assert commonmark_headings_to_bold("- item\n\t# nested") == ( |
| 1598 |
"- item\n\t**nested**" |
| 1599 |
) |
| 1600 |
|
| 1601 |
# Content inside an HTML block passes through unchanged. |
| 1602 |
heading_inside_html_block_untouched = "<div>\n# literal\n</div>" |
| 1603 |
assert ( |
| 1604 |
commonmark_headings_to_bold(heading_inside_html_block_untouched) |
| 1605 |
== heading_inside_html_block_untouched |
| 1606 |
) |
| 1607 |
|
| 1608 |
# Fence-looking text inside HTML must not consume the following document. |
| 1609 |
fence_look_alike_inside_html_block = "<div>\n~~~\n</div>\n\n# real" |
| 1610 |
assert ( |
| 1611 |
commonmark_headings_to_bold(fence_look_alike_inside_html_block) |
| 1612 |
== "<div>\n~~~\n</div>\n\n**real**" |
| 1613 |
) |
| 1614 |
|
| 1615 |
# A lowercase CDATA look-alike is ordinary text. |
| 1616 |
lowercase_cdata_is_not_html_block = ( |
| 1617 |
"- intro\n<![cdata[\n\n ~~~\n # literal\n# real" |
| 1618 |
) |
| 1619 |
assert commonmark_headings_to_bold(lowercase_cdata_is_not_html_block) == ( |
| 1620 |
"- intro\n<![cdata[\n\n ~~~\n # literal\n**real**" |
| 1621 |
) |
| 1622 |
|
| 1623 |
# A heading nested nine levels deep still converts -- the scanner |
| 1624 |
# imposes no depth limit. |
| 1625 |
heading_past_old_depth_cap = "> " * 9 + "# real" |
| 1626 |
assert commonmark_headings_to_bold(heading_past_old_depth_cap) == ( |
| 1627 |
"> " * 9 + "**real**" |
| 1628 |
) |
| 1629 |
|
| 1630 |
# An HTML block is recognized even after an active blockquote prefix, |
| 1631 |
# not just at the very start of a line. |
| 1632 |
html_block_inside_blockquote = "> <div>\n> # literal\n> </div>" |
| 1633 |
assert ( |
| 1634 |
commonmark_headings_to_bold(html_block_inside_blockquote) |
| 1635 |
== html_block_inside_blockquote |
| 1636 |
) |
| 1637 |
|
| 1638 |
# A tag-looking line inside a real fence is literal fenced content, |
| 1639 |
# not an HTML block start -- it must not swallow what follows the |
| 1640 |
# fence's own close. |
| 1641 |
html_look_alike_inside_fence = "~~~\n<script>\n~~~\n# real" |
| 1642 |
assert commonmark_headings_to_bold(html_look_alike_inside_fence) == ( |
| 1643 |
"~~~\n<script>\n~~~\n**real**" |
| 1644 |
) |
| 1645 |
|
| 1646 |
# A raw tag's closing form must be complete; a partial closer such as |
| 1647 |
# "</script nope" does not end the block. |
| 1648 |
raw_tag_requires_exact_close = ( |
| 1649 |
"<script>\ncontent\n</script nope\nreal end\n</script>\nafter\n" |
| 1650 |
"\n# real" |
| 1651 |
) |
| 1652 |
assert commonmark_headings_to_bold(raw_tag_requires_exact_close) == ( |
| 1653 |
"<script>\ncontent\n</script nope\nreal end\n</script>\nafter\n" |
| 1654 |
"\n**real**" |
| 1655 |
) |
| 1656 |
|
| 1657 |
# A heading between two same-length backtick runs must not look like |
| 1658 |
# a code span spanning across it -- block structure is resolved |
| 1659 |
# before inline code-span pairing. |
| 1660 |
backtick_run_does_not_cross_heading = "before ``\n# real\nafter ``" |
| 1661 |
assert commonmark_headings_to_bold( |
| 1662 |
backtick_run_does_not_cross_heading |
| 1663 |
) == ("before ``\n**real**\nafter ``") |
| 1664 |
|
| 1665 |
# Type 7: a complete tag for any other name, alone on its own line, |
| 1666 |
# starts an HTML block too -- but only when not interrupting an |
| 1667 |
# already-open paragraph. |
| 1668 |
custom_tag_at_document_start_protects_content = ( |
| 1669 |
"<custom>\n# literal\n</custom>" |
| 1670 |
) |
| 1671 |
assert ( |
| 1672 |
commonmark_headings_to_bold( |
| 1673 |
custom_tag_at_document_start_protects_content |
| 1674 |
) |
| 1675 |
== custom_tag_at_document_start_protects_content |
| 1676 |
) |
| 1677 |
custom_tag_cannot_interrupt_paragraph = "some text\n<custom>\n# real" |
| 1678 |
assert commonmark_headings_to_bold( |
| 1679 |
custom_tag_cannot_interrupt_paragraph |
| 1680 |
) == ("some text\n<custom>\n**real**") |
| 1681 |
|
| 1682 |
# A space before the self-closing slash makes this an invalid tag. |
| 1683 |
malformed_self_close_not_a_tag = "<custom / >\n# real" |
| 1684 |
assert commonmark_headings_to_bold(malformed_self_close_not_a_tag) == ( |
| 1685 |
"<custom / >\n**real**" |
| 1686 |
) |
| 1687 |
|
| 1688 |
# A ">" inside a quoted attribute does not end the tag early. |
| 1689 |
quoted_attribute_value_with_gt = '<custom title=">">\n# literal' |
| 1690 |
assert ( |
| 1691 |
commonmark_headings_to_bold(quoted_attribute_value_with_gt) |
| 1692 |
== quoted_attribute_value_with_gt |
| 1693 |
) |
| 1694 |
|
| 1695 |
# Any raw-tag closer ends a type-1 block, even if its name differs. |
| 1696 |
raw_tag_close_need_not_match_open = "<script>\nx\n</style>\n# real" |
| 1697 |
assert commonmark_headings_to_bold(raw_tag_close_need_not_match_open) == ( |
| 1698 |
"<script>\nx\n</style>\n**real**" |
| 1699 |
) |
| 1700 |
|
| 1701 |
# An empty list item opens no paragraph, so type-7 HTML may follow. |
| 1702 |
empty_list_item_allows_type7 = "-\n<custom>\n# literal" |
| 1703 |
assert ( |
| 1704 |
commonmark_headings_to_bold(empty_list_item_allows_type7) |
| 1705 |
== empty_list_item_allows_type7 |
| 1706 |
) |
| 1707 |
empty_quote_item_allows_type7 = ">\n<custom>\n# literal" |
| 1708 |
assert ( |
| 1709 |
commonmark_headings_to_bold(empty_quote_item_allows_type7) |
| 1710 |
== empty_quote_item_allows_type7 |
| 1711 |
) |
| 1712 |
|
| 1713 |
# Extra marker padding makes this indented code, not a heading. |
| 1714 |
excess_list_marker_padding_is_indented_code = "- # literal" |
| 1715 |
assert commonmark_headings_to_bold( |
| 1716 |
excess_list_marker_padding_is_indented_code |
| 1717 |
) == ("- # literal") |
| 1718 |
|
| 1719 |
# Nested HTML ends with its blockquote, so the later heading converts. |
| 1720 |
html_block_ends_with_its_blockquote = "> <div>\n# real" |
| 1721 |
assert commonmark_headings_to_bold( |
| 1722 |
html_block_ends_with_its_blockquote |
| 1723 |
) == ("> <div>\n**real**") |
| 1724 |
|
| 1725 |
# A quote marker by itself is blank and ends the nested HTML block. |
| 1726 |
quote_marker_only_line_ends_html_block = "> <div>\n>\n> # real" |
| 1727 |
assert commonmark_headings_to_bold( |
| 1728 |
quote_marker_only_line_ends_html_block |
| 1729 |
) == ("> <div>\n>\n> **real**") |
| 1730 |
|
| 1731 |
# A blank line ends type-6/7 HTML even inside a list. |
| 1732 |
blank_line_ends_html_block_inside_list = "- <div>\n\n # real" |
| 1733 |
assert commonmark_headings_to_bold( |
| 1734 |
blank_line_ends_html_block_inside_list |
| 1735 |
) == ("- <div>\n\n **real**") |
| 1736 |
|
| 1737 |
# Excess tab padding belongs to the item's indented code content. |
| 1738 |
tab_padding_after_marker_is_indented_code = "-\t\t\t# literal" |
| 1739 |
assert commonmark_headings_to_bold( |
| 1740 |
tab_padding_after_marker_is_indented_code |
| 1741 |
) == ("-\t\t\t# literal") |
| 1742 |
|
| 1743 |
# A setext underline closes the paragraph before the type-7 tag. |
| 1744 |
setext_underline_ends_paragraph = "text\n===\n<custom>\n# literal" |
| 1745 |
assert ( |
| 1746 |
commonmark_headings_to_bold(setext_underline_ends_paragraph) |
| 1747 |
== setext_underline_ends_paragraph |
| 1748 |
) |
| 1749 |
|
| 1750 |
# Indented text lazily continues the paragraph, blocking type-7 HTML. |
| 1751 |
indented_text_continues_paragraph_lazily = ( |
| 1752 |
"text\n continuation\n<custom>\n# real" |
| 1753 |
) |
| 1754 |
assert commonmark_headings_to_bold( |
| 1755 |
indented_text_continues_paragraph_lazily |
| 1756 |
) == ("text\n continuation\n<custom>\n**real**") |
| 1757 |
|
| 1758 |
# An empty list marker cannot interrupt the open paragraph. |
| 1759 |
empty_marker_cannot_interrupt_paragraph = "text\n+\n<custom>\n# literal" |
| 1760 |
assert commonmark_headings_to_bold( |
| 1761 |
empty_marker_cannot_interrupt_paragraph |
| 1762 |
) == ("text\n+\n<custom>\n**literal**") |
| 1763 |
|
| 1764 |
# A non-empty list marker interrupts the open paragraph. |
| 1765 |
nonempty_marker_interrupts_paragraph = "text\n+ item\n<custom>\n# literal" |
| 1766 |
assert ( |
| 1767 |
commonmark_headings_to_bold(nonempty_marker_interrupts_paragraph) |
| 1768 |
== nonempty_marker_interrupts_paragraph |
| 1769 |
) |
| 1770 |
|
| 1771 |
|
| 1772 |
def test_conversion_headings_type7_regex_performance(): |
| 1773 |
"""Keep malformed type-7 tags with long whitespace runs near linear.""" |
| 1774 |
times = [] |
| 1775 |
for spaces in (1600, 6400): |
| 1776 |
body = "<x " + (" " * spaces) + "<\n# real" |
| 1777 |
start = default_timer() |
| 1778 |
commonmark_headings_to_bold(body) |
| 1779 |
times.append(default_timer() - start) |
| 1780 |
|
| 1781 |
# A 4x input must stay well below the roughly 16x cost of quadratic work. |
| 1782 |
assert times[1] < times[0] * 8 + 0.2 |
| 1783 |
|
| 1784 |
|
| 1785 |
def test_conversion_headings_nested_quotes_performance(): |
| 1786 |
"""Keep deeply nested blockquotes fast without limiting their depth.""" |
| 1787 |
start = default_timer() |
| 1788 |
commonmark_headings_to_bold("> " * 5000 + "x") |
| 1789 |
elapsed = default_timer() - start |
| 1790 |
|
| 1791 |
assert elapsed < 0.5 |
| 1792 |
|
| 1793 |
|
| 1794 |
def test_conversion_headings_deep_lines_performance(): |
| 1795 |
"""Keep repeated deeply nested lines fast as message size grows.""" |
| 1796 |
body = ("> " * 8 + "x\n") * 1000 |
| 1797 |
|
| 1798 |
start = default_timer() |
| 1799 |
commonmark_headings_to_bold(body) |
| 1800 |
elapsed = default_timer() - start |
| 1801 |
|
| 1802 |
assert elapsed < 1.0 |
| 1803 |
|
| 1804 |
|
| 1805 |
def test_conversion_html_block_spans(): |
| 1806 |
"""_commonmark_html_block_spans: per-type closing rules.""" |
| 1807 |
|
| 1808 |
# Type 6 (a named block tag) closes at the next blank line. |
| 1809 |
text = "<div>\ncontent\n</div>\n\nafter" |
| 1810 |
assert commonmark_module._commonmark_html_block_spans(text) == [ |
| 1811 |
(0, len("<div>\ncontent\n</div>\n")) |
| 1812 |
] |
| 1813 |
|
| 1814 |
# Without a blank line, the block runs to the end of the text. |
| 1815 |
text = "<div>\ncontent\n</div>" |
| 1816 |
assert commonmark_module._commonmark_html_block_spans(text) == [ |
| 1817 |
(0, len(text)) |
| 1818 |
] |
| 1819 |
|
| 1820 |
# A raw tag closes at a complete raw-tag end, even across what would |
| 1821 |
# otherwise be a blank-line boundary. |
| 1822 |
text = "<script>\nvar x = 1;\n\nmore\n</script>\nafter" |
| 1823 |
close = text.index("</script>") + len("</script>") |
| 1824 |
assert commonmark_module._commonmark_html_block_spans(text) == [ |
| 1825 |
(0, close + 1) |
| 1826 |
] |
| 1827 |
|
| 1828 |
# A comment closes at its own terminator, wherever it appears. |
| 1829 |
text = "<!-- start\nstill a comment -->\nafter" |
| 1830 |
close = text.index("-->") + len("-->") |
| 1831 |
assert commonmark_module._commonmark_html_block_spans(text) == [ |
| 1832 |
(0, close + 1) |
| 1833 |
] |
| 1834 |
|
| 1835 |
# An unterminated comment runs to the end of the text. |
| 1836 |
text = "<!-- never closes\nmore text" |
| 1837 |
assert commonmark_module._commonmark_html_block_spans(text) == [ |
| 1838 |
(0, len(text)) |
| 1839 |
] |
| 1840 |
|
| 1841 |
# A processing instruction closes at "?>". |
| 1842 |
text = "<?php\necho 1;\n?>\nafter" |
| 1843 |
close = text.index("?>") + len("?>") |
| 1844 |
assert commonmark_module._commonmark_html_block_spans(text) == [ |
| 1845 |
(0, close + 1) |
| 1846 |
] |
| 1847 |
|
| 1848 |
# A declaration closes at the next literal ">", extended through the |
| 1849 |
# end of the line containing it. |
| 1850 |
text = "<!DOCTYPE html>\nafter" |
| 1851 |
close = text.index(">", text.index("<!DOCTYPE")) |
| 1852 |
assert commonmark_module._commonmark_html_block_spans(text) == [ |
| 1853 |
(0, close + 2) |
| 1854 |
] |
| 1855 |
|
| 1856 |
# A CDATA section closes at "]]>". |
| 1857 |
text = "<![CDATA[\ndata\n]]>\nafter" |
| 1858 |
close = text.index("]]>") + len("]]>") |
| 1859 |
assert commonmark_module._commonmark_html_block_spans(text) == [ |
| 1860 |
(0, close + 1) |
| 1861 |
] |
| 1862 |
|
| 1863 |
# Lowercase "cdata" is not a valid opener at all -- case-sensitive. |
| 1864 |
text = "<![cdata[\nnot a block\n\nafter" |
| 1865 |
assert commonmark_module._commonmark_html_block_spans(text) == [] |
| 1866 |
|
| 1867 |
# Plain text with no HTML block start yields no spans. |
| 1868 |
assert commonmark_module._commonmark_html_block_spans("just text") == [] |
| 1869 |
|
| 1870 |
# A non-raw closing tag does not end a raw HTML block. |
| 1871 |
text = "<script>\nvar x = 1;\n</div>\nmore\n</script>\nafter" |
| 1872 |
close = text.rindex("</script>") + len("</script>") |
| 1873 |
assert commonmark_module._commonmark_html_block_spans(text) == [ |
| 1874 |
(0, close + 1) |
| 1875 |
] |
| 1876 |
|
| 1877 |
# A partial string like "</script nope" must not count as "</script>". |
| 1878 |
text = "<script>\ncontent\n</script nope\nreal end\n</script>\nafter" |
| 1879 |
close = text.rindex("</script>") + len("</script>") |
| 1880 |
assert commonmark_module._commonmark_html_block_spans(text) == [ |
| 1881 |
(0, close + 1) |
| 1882 |
] |
| 1883 |
|
| 1884 |
# Type 7: a complete tag for any other name, alone on its own line, |
| 1885 |
# starts an HTML block too, when not interrupting an open paragraph. |
| 1886 |
text = "<custom>\ncontent\n</custom>\n\nafter" |
| 1887 |
assert commonmark_module._commonmark_html_block_spans(text) == [ |
| 1888 |
(0, len("<custom>\ncontent\n</custom>\n")) |
| 1889 |
] |
| 1890 |
|
| 1891 |
# Type 7 cannot interrupt an already-open paragraph. |
| 1892 |
text = "some text\n<custom>\nmore text" |
| 1893 |
assert commonmark_module._commonmark_html_block_spans(text) == [] |
| 1894 |
|
| 1895 |
|
| 1896 |
def test_conversion_leaf_block_spans_mutual_exclusion(): |
| 1897 |
"""Keep fence-like HTML and HTML-like fenced text inside their opener.""" |
| 1898 |
# A fence-looking line inside a real (type 6) HTML block is not a |
| 1899 |
# fence -- the HTML block's own span covers it. |
| 1900 |
text = "<div>\n~~~\n</div>\n\nafter" |
| 1901 |
spans = commonmark_module._commonmark_leaf_block_spans(text) |
| 1902 |
assert spans == [(0, len("<div>\n~~~\n</div>\n"), "html")] |
| 1903 |
|
| 1904 |
# An HTML-looking line inside a real fence is not an HTML block -- |
| 1905 |
# the fence's own span covers it, and closes normally. |
| 1906 |
text = "~~~\n<script>\n~~~\nafter" |
| 1907 |
spans = commonmark_module._commonmark_leaf_block_spans(text) |
| 1908 |
assert spans == [(0, len("~~~\n<script>\n~~~\n"), "fence")] |
| 1909 |
|
| 1910 |
|
| 1911 |
def test_conversion_text_width_expands_tabs(): |
| 1912 |
"""_text_width: a tab expands to the next four-column stop.""" |
| 1913 |
assert commonmark_module._text_width("\t") == 4 |
| 1914 |
assert commonmark_module._text_width("\t", 1) == 3 |
| 1915 |
assert commonmark_module._text_width("a\tb") == 5 |
| 1916 |
|
| 1917 |
|
| 1918 |
def test_conversion_chars_for_width_boundaries(): |
| 1919 |
"""_chars_for_width: handle tabs and stop before ordinary text.""" |
| 1920 |
assert commonmark_module._chars_for_width("\ttext", 4) == 1 |
| 1921 |
assert commonmark_module._chars_for_width(" text", 2) == 1 |
| 1922 |
|
| 1923 |
|
| 1924 |
def test_conversion_missing_boundary_is_not_punctuation(): |
| 1925 |
"""_cm_is_punctuation: a missing boundary is not punctuation.""" |
| 1926 |
assert commonmark_module._cm_is_punctuation(None) is False |
| 1927 |
|
| 1928 |
|
| 1929 |
def test_conversion_html_block_end_bounded_by_quote_container(): |
| 1930 |
"""Stop fixed and blank-line HTML blocks when their blockquote ends.""" |
| 1931 |
# Type 2 (comment): the terminator search must not run past the |
| 1932 |
# blockquote's own end into unquoted text below it. |
| 1933 |
text = "> <!-- start\n\n# real" |
| 1934 |
spans = commonmark_module._commonmark_leaf_block_spans(text) |
| 1935 |
assert spans == [(0, len("> <!-- start\n"), "html")] |
| 1936 |
|
| 1937 |
# Type 6 (a named block tag): same boundary, via the blank-line rule. |
| 1938 |
text = "> <div>\n\n# real" |
| 1939 |
spans = commonmark_module._commonmark_leaf_block_spans(text) |
| 1940 |
assert spans == [(0, len("> <div>\n"), "html")] |
| 1941 |
|
| 1942 |
# A properly quoted continuation line still satisfies the container, |
| 1943 |
# so the terminator search continues through it and finds a closer |
| 1944 |
# on a later line, rather than stopping early. |
| 1945 |
text = "> <!-- comment\n> still comment -->\nafter" |
| 1946 |
spans = commonmark_module._commonmark_leaf_block_spans(text) |
| 1947 |
assert spans == [(0, len("> <!-- comment\n> still comment -->\n"), "html")] |
| 1948 |
|
| 1949 |
# When the quote holds all the way through and no terminator ever |
| 1950 |
# appears, the block runs to the end of the text. |
| 1951 |
text = "> <!-- never closes\n> more text" |
| 1952 |
spans = commonmark_module._commonmark_leaf_block_spans(text) |
| 1953 |
assert spans == [(0, len(text), "html")] |
| 1954 |
|
| 1955 |
|
| 1956 |
def test_conversion_html_block_end_blank_line_rule_differs_by_type(): |
| 1957 |
"""Keep fixed-terminator HTML open; end types 6/7 at a blank line. |
| 1958 |
|
| 1959 |
Lists may span blank lines, but that does not extend type-6/7 HTML. |
| 1960 |
""" |
| 1961 |
text = "- <!-- start\n\nafter" |
| 1962 |
spans = commonmark_module._commonmark_leaf_block_spans(text) |
| 1963 |
assert spans == [(0, len("- <!-- start\n\n"), "html")] |
| 1964 |
|
| 1965 |
text = "- <div>\n\nafter" |
| 1966 |
spans = commonmark_module._commonmark_leaf_block_spans(text) |
| 1967 |
assert spans == [(0, len("- <div>\n"), "html")] |
| 1968 |
|
| 1969 |
|
| 1970 |
def test_conversion_fenced_code_spans_stay_within_text_bounds(): |
| 1971 |
"""A fence with no trailing newline must not report an out-of-range end.""" |
| 1972 |
|
| 1973 |
text = "```\nx\n```" |
| 1974 |
spans = commonmark_module._commonmark_fenced_code_spans(text) |
| 1975 |
assert spans == [(0, len(text))] |
| 1976 |
for start, end in spans: |
| 1977 |
assert 0 <= start <= len(text) |
| 1978 |
assert 0 <= end <= len(text) |
| 1979 |
|
| 1980 |
|
| 1981 |
def test_conversion_code_spans_do_not_cross_block_boundaries(): |
| 1982 |
"""Backtick pairing must not cross a block boundary between the runs. |
| 1983 |
|
| 1984 |
CommonMark resolves block structure before parsing inlines, so a |
| 1985 |
heading (or any other block) sitting between two same-length |
| 1986 |
backtick runs must not make them look like one matched code span. |
| 1987 |
""" |
| 1988 |
# A heading between two double-backtick runs ends the paragraph, so |
| 1989 |
# neither run may pair with the other. |
| 1990 |
text = "before ``\n# heading\nafter ``" |
| 1991 |
assert commonmark_module._commonmark_code_spans(text) == [] |
| 1992 |
|
| 1993 |
# A blank line has the same effect. |
| 1994 |
text = "before ``\n\nafter ``" |
| 1995 |
assert commonmark_module._commonmark_code_spans(text) == [] |
| 1996 |
|
| 1997 |
# Without a boundary in between, pairing within one paragraph's |
| 1998 |
# continuous lines still works as before. |
| 1999 |
text = "before ``\nstill one paragraph`` after" |
| 2000 |
assert commonmark_module._commonmark_code_spans(text) == [ |
| 2001 |
(7, len(text) - len(" after")) |
| 2002 |
] |
| 2003 |
|
| 2004 |
|
| 2005 |
def test_conversion_headings_to_bold_repeated_fences_linear_time(): |
| 2006 |
"""Keep repeated, lightly indented fence checks near linear time. |
| 2007 |
|
| 2008 |
Every line remains a possible list continuation, exercising the full |
| 2009 |
ambiguous-fence path instead of ending a lookup early. |
| 2010 |
""" |
| 2011 |
|
| 2012 |
small = " ~~~\n text\n ~~~\n" * 2000 |
| 2013 |
large = " ~~~\n text\n ~~~\n" * 4000 |
| 2014 |
|
| 2015 |
# Create and reuse one scanner for the entire conversion. |
| 2016 |
with mock.patch( |
| 2017 |
"apprise.conversion.commonmark._ContainerScanner", |
| 2018 |
wraps=commonmark_module._ContainerScanner, |
| 2019 |
) as spy: |
| 2020 |
commonmark_headings_to_bold(large) |
| 2021 |
assert spy.call_count == 1 |
| 2022 |
|
| 2023 |
start = default_timer() |
| 2024 |
commonmark_headings_to_bold(small) |
| 2025 |
small_time = default_timer() - start |
| 2026 |
|
| 2027 |
start = default_timer() |
| 2028 |
commonmark_headings_to_bold(large) |
| 2029 |
large_time = default_timer() - start |
| 2030 |
|
| 2031 |
# Allow timing noise while rejecting clear quadratic growth. |
| 2032 |
assert large_time < small_time * 2.5 + 0.5 |
| 2033 |
|
| 2034 |
|
| 2035 |
def test_conversion_headings_to_bold_repeated_fences_bounded_memory(): |
| 2036 |
"""Avoid storing one list-width entry for every preceding line.""" |
| 2037 |
tracemalloc = pytest.importorskip("tracemalloc") |
| 2038 |
|
| 2039 |
baseline = "\n" * 800_000 + "# heading\n" |
| 2040 |
ambiguous = "\n" * 800_000 + " ~~~\n" |
| 2041 |
|
| 2042 |
tracemalloc.start() |
| 2043 |
commonmark_headings_to_bold(baseline) |
| 2044 |
_, baseline_peak = tracemalloc.get_traced_memory() |
| 2045 |
tracemalloc.stop() |
| 2046 |
|
| 2047 |
tracemalloc.start() |
| 2048 |
commonmark_headings_to_bold(ambiguous) |
| 2049 |
_, ambiguous_peak = tracemalloc.get_traced_memory() |
| 2050 |
tracemalloc.stop() |
| 2051 |
|
| 2052 |
# Allow allocator overhead while rejecting a document-sized index. |
| 2053 |
assert ambiguous_peak < baseline_peak * 5 + 1024 * 1024 |
| 2054 |
|
| 2055 |
|
| 2056 |
def test_conversion_decode_backslash_escapes(): |
| 2057 |
"""Only decode backslashes used for CommonMark punctuation escapes.""" |
| 2058 |
|
| 2059 |
# A backslash before ASCII punctuation is a real CommonMark escape. |
| 2060 |
assert commonmark_decode_backslash_escapes(r"a\*b") == "a*b" |
| 2061 |
assert commonmark_decode_backslash_escapes(r"a\_b") == "a_b" |
| 2062 |
assert commonmark_decode_backslash_escapes(r"a\\b") == "a\\b" |
| 2063 |
|
| 2064 |
# Preserve backslashes before letters so paths and URLs are not corrupted. |
| 2065 |
assert commonmark_decode_backslash_escapes(r"a\qb") == r"a\qb" |
| 2066 |
assert commonmark_decode_backslash_escapes(r"C:\Users") == r"C:\Users" |
| 2067 |
|
| 2068 |
# A trailing, unescaped backslash has nothing to escape and is kept. |
| 2069 |
assert commonmark_decode_backslash_escapes("a\\") == "a\\" |
| 2070 |
|
| 2071 |
|
| 2072 |
def test_conversion_html_to_markdown_blockquotes(): |
| 2073 |
"""Test blockquote conversion.""" |
| 2074 |
|
| 2075 |
def to_md(body): |
| 2076 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 2077 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 2078 |
|
| 2079 |
# Single paragraph -- marker and content share the first line |
| 2080 |
assert to_md("<blockquote><p>line1</p></blockquote>") == "> line1" |
| 2081 |
|
| 2082 |
# Multiple paragraphs |
| 2083 |
assert ( |
| 2084 |
to_md("<blockquote><p>line1</p><p>line2</p></blockquote>") |
| 2085 |
== "> line1\n>\n> line2" |
| 2086 |
) |
| 2087 |
assert ( |
| 2088 |
to_md("<blockquote><p>a</p><p>b</p><p>c</p></blockquote>") |
| 2089 |
== "> a\n>\n> b\n>\n> c" |
| 2090 |
) |
| 2091 |
|
| 2092 |
# A heading doesn't need that same blank-line treatment. |
| 2093 |
assert ( |
| 2094 |
to_md("<blockquote><h2>Title</h2><p>body</p></blockquote>") |
| 2095 |
== "> ## Title\n> body" |
| 2096 |
) |
| 2097 |
|
| 2098 |
# Inline-only content needs no internal prefixing -- it never hits a |
| 2099 |
# boundary inside the quote in the first place |
| 2100 |
assert ( |
| 2101 |
to_md("<blockquote>To be or not to be.</blockquote>") |
| 2102 |
== "> To be or not to be." |
| 2103 |
) |
| 2104 |
|
| 2105 |
# Nested blockquotes accumulate one "> " per level, not per ancestor's full |
| 2106 |
# cumulative prefix, which would double-count outer quote levels. |
| 2107 |
assert ( |
| 2108 |
to_md("<blockquote><blockquote>nested</blockquote></blockquote>") |
| 2109 |
== "> > nested" |
| 2110 |
) |
| 2111 |
assert to_md( |
| 2112 |
"<blockquote><blockquote><p>a</p><p>b</p></blockquote></blockquote>" |
| 2113 |
) == ("> > a\n> >\n> > b") |
| 2114 |
|
| 2115 |
# Bare text follows the same one-prefix-per-level rule. |
| 2116 |
assert ( |
| 2117 |
to_md("<blockquote>outer<blockquote>inner</blockquote></blockquote>") |
| 2118 |
== "> outer\n>\n> > inner" |
| 2119 |
) |
| 2120 |
assert to_md( |
| 2121 |
"<blockquote>a<blockquote>b<blockquote>c</blockquote>" |
| 2122 |
"</blockquote></blockquote>" |
| 2123 |
) == ("> a\n>\n> > b\n> >\n> > > c") |
| 2124 |
|
| 2125 |
# The same text-then-nested-blockquote transition, once depth is already |
| 2126 |
# clamped at BLOCKQUOTE_DEPTH_MAX, must not add yet another level. |
| 2127 |
assert BLOCKQUOTE_DEPTH_MAX == 4 |
| 2128 |
capped = ( |
| 2129 |
"<blockquote>" * 4 |
| 2130 |
+ "x<blockquote>y</blockquote>" |
| 2131 |
+ ("</blockquote>" * 4) |
| 2132 |
) |
| 2133 |
out = to_md(capped) |
| 2134 |
assert "> > > > x" in out |
| 2135 |
assert "> > > > > y" not in out |
| 2136 |
assert "> > > > y" in out |
| 2137 |
|
| 2138 |
# Content after a blockquote needs a full boundary without the quote |
| 2139 |
# prefix. |
| 2140 |
assert ( |
| 2141 |
to_md("<blockquote><p>line1</p></blockquote><p>after</p>") |
| 2142 |
== "> line1\n\nafter" |
| 2143 |
) |
| 2144 |
assert ( |
| 2145 |
to_md("<p>before</p><blockquote><p>line1</p></blockquote>") |
| 2146 |
== "before\n\n> line1" |
| 2147 |
) |
| 2148 |
|
| 2149 |
# An entirely empty blockquote (no children at all, nested or not) produces |
| 2150 |
# no output. |
| 2151 |
assert to_md("<blockquote></blockquote>") == "" |
| 2152 |
assert to_md("<blockquote><blockquote></blockquote></blockquote>") == "" |
| 2153 |
|
| 2154 |
# A blockquote entirely inside a suppressed context contributes nothing, |
| 2155 |
# and does not disturb sibling content outside it |
| 2156 |
assert ( |
| 2157 |
to_md( |
| 2158 |
"<head><blockquote><p>hidden</p></blockquote></head>" |
| 2159 |
"<body>text</body>" |
| 2160 |
) |
| 2161 |
== "text" |
| 2162 |
) |
| 2163 |
|
| 2164 |
# A blockquote following bare text still needs its own boundary. |
| 2165 |
assert to_md("text<blockquote>quoted</blockquote>") == ("text\n\n> quoted") |
| 2166 |
assert to_md("text<blockquote></blockquote>") == "text" |
| 2167 |
assert to_md("<p>text<blockquote></blockquote></p>") == "text" |
| 2168 |
|
| 2169 |
|
| 2170 |
def test_conversion_html_to_markdown_emphasis(): |
| 2171 |
"""Test emphasis edge cases.""" |
| 2172 |
|
| 2173 |
def to_md(body): |
| 2174 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 2175 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 2176 |
|
| 2177 |
# Leading/trailing whitespace inside the tag must end up outside the |
| 2178 |
# delimiters. |
| 2179 |
assert to_md("<em> text </em>") == "*text*" |
| 2180 |
assert to_md("<strong> bold </strong>") == "**bold**" |
| 2181 |
assert to_md("<em> multi space </em>") == "*multi space*" |
| 2182 |
|
| 2183 |
# Leading-only and trailing-only whitespace |
| 2184 |
assert to_md("<em> text</em>") == "*text*" |
| 2185 |
assert to_md("<em>text </em>") == "*text*" |
| 2186 |
|
| 2187 |
# Relocating emphasis whitespace must not disturb surrounding text. |
| 2188 |
assert ( |
| 2189 |
to_md("<p>Hello <strong> bold </strong> world</p>") |
| 2190 |
== "Hello **bold** world" |
| 2191 |
) |
| 2192 |
|
| 2193 |
# Relocate trailing whitespace even when empty tags split the text |
| 2194 |
# fragments. |
| 2195 |
assert to_md("<strong>text<span></span> </strong>x") == "**text** x" |
| 2196 |
|
| 2197 |
# Fully empty, or whitespace-only, spans contribute nothing at all -- not |
| 2198 |
# even an unpaired delimiter |
| 2199 |
assert to_md("<strong></strong>") == "" |
| 2200 |
assert to_md("<em> </em>") == "" |
| 2201 |
assert to_md("<strong><em></em></strong>") == "" |
| 2202 |
|
| 2203 |
# Adjacent tags, one empty -- the empty one's delimiters must not collide |
| 2204 |
# with the next tag's into an ambiguous run of asterisks |
| 2205 |
assert to_md("<strong></strong><strong>bold</strong>") == "**bold**" |
| 2206 |
assert to_md("<em></em><em>x</em>") == "*x*" |
| 2207 |
|
| 2208 |
# A stray close tag with no matching open is a no-op, the same as other |
| 2209 |
# malformed- HTML cases elsewhere in this parser. |
| 2210 |
assert to_md("</b>text") == "text" |
| 2211 |
assert to_md("<p>a</b>b</p>") == "ab" |
| 2212 |
|
| 2213 |
# Mismatched open/close tags ("<i>x</b>y"). |
| 2214 |
assert to_md("<i>x</b>y") == "*xy*" |
| 2215 |
|
| 2216 |
# A tag left open with no closing tag at all is auto-closed at end of |
| 2217 |
# document rather than leaving its opening delimiter unpaired |
| 2218 |
assert to_md("<b>text") == "**text**" |
| 2219 |
assert to_md("<p><em>a<strong>b") == "*a**b***" |
| 2220 |
|
| 2221 |
# Normal, well-formed cases are unaffected |
| 2222 |
assert to_md("<strong>bold</strong>") == "**bold**" |
| 2223 |
assert to_md("<em>italic</em>") == "*italic*" |
| 2224 |
assert to_md("<strong>A</strong><strong>B</strong>") == "**A****B**" |
| 2225 |
|
| 2226 |
# Empty block content inside emphasis must not leave an opening delimiter. |
| 2227 |
assert to_md("<em><ul><li></li></ul></em>x") == "x" |
| 2228 |
assert to_md("a<em><ul><li></li></ul></em>b") == "ab" |
| 2229 |
|
| 2230 |
# Empty trailing blocks must not hide whitespace from emphasis cleanup. |
| 2231 |
assert to_md("<em>text<blockquote></blockquote></em>") == ("*text\n\n> *") |
| 2232 |
|
| 2233 |
|
| 2234 |
def test_conversion_html_to_markdown_empty_blocks(): |
| 2235 |
"""Test empty block handling.""" |
| 2236 |
|
| 2237 |
def to_md(body): |
| 2238 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 2239 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 2240 |
|
| 2241 |
# Plain, marker-less block tags with nothing inside them already collapse |
| 2242 |
# to nothing extra -- no separate blank line is added for each one. |
| 2243 |
assert to_md("<div></div><div></div><p>text</p>") == "text" |
| 2244 |
assert to_md("<p>a</p><div></div><p>b</p>") == "a\n\nb" |
| 2245 |
assert ( |
| 2246 |
to_md("<p>a</p><div></div><div></div><div></div><p>b</p>") == "a\n\nb" |
| 2247 |
) |
| 2248 |
|
| 2249 |
# Empty blocks do not detach a marker from later content. |
| 2250 |
assert ( |
| 2251 |
to_md("<ul><li><div></div><div></div><p>text</p></li></ul>") |
| 2252 |
== "- text" |
| 2253 |
) |
| 2254 |
assert to_md("<blockquote><div></div><p>text</p></blockquote>") == "> text" |
| 2255 |
|
| 2256 |
# Drop markers that never receive content. |
| 2257 |
assert to_md("<ul><li></li></ul>") == "" |
| 2258 |
assert to_md("<ul><li><div></div></li></ul>") == "" |
| 2259 |
|
| 2260 |
# A sibling marker arriving after the first one's empty block tags replaces |
| 2261 |
# it rather than gluing onto it. |
| 2262 |
assert to_md("<ul><li><div></div></li><li>real</li></ul>") == "- real" |
| 2263 |
|
| 2264 |
# Empty blocks do not duplicate a blockquote prefix. |
| 2265 |
assert ( |
| 2266 |
to_md("<blockquote><p>line1</p><div></div><p>line2</p></blockquote>") |
| 2267 |
== "> line1\n>\n> line2" |
| 2268 |
) |
| 2269 |
|
| 2270 |
# Real text between two empty blocks still resets the suppression, so the |
| 2271 |
# block tag right after it starts a new line as normal. |
| 2272 |
assert to_md("<div></div>text<div></div><p>more</p>") == "text\n\nmore" |
| 2273 |
|
| 2274 |
# Plain whitespace between tags never counts as content |
| 2275 |
assert to_md("<p>a</p> <p>b</p>") == "a\n\nb" |
| 2276 |
|
| 2277 |
# A standalone is a deliberate space, not incidental formatting |
| 2278 |
# whitespace. |
| 2279 |
assert to_md("<p>a</p> <p>b</p>") == "a\n\n\xa0\n\nb" |
| 2280 |
|
| 2281 |
# used inline within real text is unaffected, and still collapses to |
| 2282 |
# a regular space like any other inline whitespace |
| 2283 |
assert ( |
| 2284 |
to_md("Let's handle special html encoding") |
| 2285 |
== "Let's handle special html encoding" |
| 2286 |
) |
| 2287 |
|
| 2288 |
# <hr> is a void element (its closing tag may never fire), but it still |
| 2289 |
# writes real, non-marker content ("---"). |
| 2290 |
assert to_md("<hr><hr>") == "---\n\n---" |
| 2291 |
assert to_md("<hr> <hr>") == "---\n\n---" |
| 2292 |
assert to_md("<hr/><hr/><hr/>") == "---\n\n---\n\n---" |
| 2293 |
assert to_md("<p>a</p><hr><hr><p>b</p>") == "a\n\n---\n\n---\n\nb" |
| 2294 |
|
| 2295 |
# <hr> as the first thing in a blockquote/list item glues onto the marker; |
| 2296 |
# inside an open blockquote, its own opening boundary still applies. |
| 2297 |
assert to_md("<ul><li><hr></li></ul>") == "- ---" |
| 2298 |
assert to_md("<blockquote><p>a</p><hr></blockquote>") == "> a\n>\n> ---" |
| 2299 |
|
| 2300 |
# Real page text that happens to *look* like a generated marker (e.g. |
| 2301 |
assert to_md("<p>- </p><p>real</p>") == "\\-\n\nreal" |
| 2302 |
assert to_md("<p>- </p>") == "\\-" |
| 2303 |
assert ( |
| 2304 |
to_md("<p>- </p><div>real div content</div>") |
| 2305 |
== "\\-\n\nreal div content" |
| 2306 |
) |
| 2307 |
# Real text directly inside a real <li> that itself looks like a marker is |
| 2308 |
# escaped too. |
| 2309 |
assert to_md("<ul><li>- </li></ul>") == "- \\-" |
| 2310 |
|
| 2311 |
|
| 2312 |
def test_conversion_html_to_markdown_list_indentation(): |
| 2313 |
"""Test list continuation indentation.""" |
| 2314 |
|
| 2315 |
def to_md(body): |
| 2316 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 2317 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 2318 |
|
| 2319 |
# Baseline: a single <p> as an <li>'s only child still just glues onto the |
| 2320 |
# marker. |
| 2321 |
assert to_md("<li><p>text</p></li>") == "- text" |
| 2322 |
|
| 2323 |
# Later paragraphs use the current item's continuation indentation. |
| 2324 |
assert to_md("<ul><li><p>one</p><p>two</p></li></ul>") == "- one\n\n two" |
| 2325 |
|
| 2326 |
# Ordered lists need the indentation to match their own (wider) marker |
| 2327 |
# width, not the bullet list's fixed 2 spaces |
| 2328 |
assert ( |
| 2329 |
to_md("<ol><li><p>one</p><p>two</p></li></ol>") == "1. one\n\n two" |
| 2330 |
) |
| 2331 |
|
| 2332 |
# Sibling <li>s must NOT pick up any indentation from each other -- only a |
| 2333 |
# *continuation within the same item* should ever be indented |
| 2334 |
assert ( |
| 2335 |
to_md("<ul><li><p>alpha</p></li><li><p>beta</p></li></ul>") |
| 2336 |
== "- alpha\n\n- beta" |
| 2337 |
) |
| 2338 |
assert ( |
| 2339 |
to_md("<ol><li><p>a</p></li><li><p>b</p></li><li><p>c</p></li></ol>") |
| 2340 |
== "1. a\n\n2. b\n\n3. c" |
| 2341 |
) |
| 2342 |
|
| 2343 |
# A nested sublist's own marker (computed independently for its own depth) |
| 2344 |
# must not be *additionally* indented on top of that. |
| 2345 |
assert to_md("<ul><li>x<ul><li>x</li></ul></li></ul>") == "- x\n - x" |
| 2346 |
assert ( |
| 2347 |
to_md("<ul><li>L1<ul><li>L2<ul><li>L3</li></ul></li></ul></li></ul>") |
| 2348 |
== "- L1\n - L2\n - L3" |
| 2349 |
) |
| 2350 |
|
| 2351 |
# Nested quotes combine list indentation with quote prefixes. |
| 2352 |
assert to_md( |
| 2353 |
"<ul><li><blockquote><p>a</p><p>b</p></blockquote></li></ul>" |
| 2354 |
) == ("- > a\n >\n > b") |
| 2355 |
|
| 2356 |
# A first-child list inside a blockquote retains the quote prefix. |
| 2357 |
assert to_md("<blockquote><ul><li>text</li></ul></blockquote>") == ( |
| 2358 |
"> - text" |
| 2359 |
) |
| 2360 |
|
| 2361 |
# Multiple <li>s inside a <blockquote> each need "> " restated |
| 2362 |
assert to_md("<blockquote><ul><li>a</li><li>b</li></ul></blockquote>") == ( |
| 2363 |
"> - a\n> - b" |
| 2364 |
) |
| 2365 |
|
| 2366 |
# Chained blockquotes retain nesting after a paragraph boundary. |
| 2367 |
assert to_md( |
| 2368 |
"<blockquote><p>a</p><blockquote>nested</blockquote></blockquote>" |
| 2369 |
) == ("> a\n>\n> > nested") |
| 2370 |
|
| 2371 |
# <pre>/<samp> inside an <li>: every line of the fence. |
| 2372 |
assert to_md("<ul><li>code:<pre> indented\n here</pre></li></ul>") == ( |
| 2373 |
"- code:\n ```\n indented\n here\n ```" |
| 2374 |
) |
| 2375 |
|
| 2376 |
# A deeper list adds another indentation level to the fence. |
| 2377 |
assert to_md( |
| 2378 |
"<ul><li>outer<ul><li>inner:<pre> x = 1</pre></li></ul></li></ul>" |
| 2379 |
) == ("- outer\n - inner:\n ```\n x = 1\n ```") |
| 2380 |
|
| 2381 |
|
| 2382 |
def test_conversion_html_to_markdown_br(): |
| 2383 |
"""Test CommonMark hard breaks.""" |
| 2384 |
|
| 2385 |
def to_md(body): |
| 2386 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 2387 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 2388 |
|
| 2389 |
# Two trailing spaces then a newline -- a bare "\n" is only a soft break |
| 2390 |
# under CommonMark (most renderers collapse it to a single space rather. |
| 2391 |
assert to_md("line1<br>line2") == "line1 \nline2" |
| 2392 |
assert to_md("line1<br/>line2") == "line1 \nline2" |
| 2393 |
assert to_md("line1<br />line2") == "line1 \nline2" |
| 2394 |
|
| 2395 |
# Verified against an actual renderer, not just the raw Markdown shape. |
| 2396 |
rendered = convert_between( |
| 2397 |
NotifyFormat.MARKDOWN, NotifyFormat.HTML, to_md("line1<br>line2") |
| 2398 |
) |
| 2399 |
assert "<br" in rendered |
| 2400 |
assert "\\" not in rendered |
| 2401 |
|
| 2402 |
# Consecutive <br> tags each contribute their own hard break |
| 2403 |
assert to_md("a<br><br>b") == "a \n \nb" |
| 2404 |
|
| 2405 |
# A trailing <br> with nothing after it doesn't leave a dangling hard break |
| 2406 |
# at the very end of the output |
| 2407 |
assert to_md("<p>line1<br></p>") == "line1" |
| 2408 |
|
| 2409 |
# A hard break inside a blockquote must restate the "> " prefix on its |
| 2410 |
# continuation line. |
| 2411 |
assert to_md("<blockquote>line1<br>line2</blockquote>") == ( |
| 2412 |
"> line1 \n> line2" |
| 2413 |
) |
| 2414 |
|
| 2415 |
# Same, but inside a list item -- the continuation line must keep the |
| 2416 |
# marker's indentation so it stays part of the same item. |
| 2417 |
assert to_md("<ul><li>line1<br>line2</li></ul>") == ("- line1 \n line2") |
| 2418 |
|
| 2419 |
# Both nested together -- a blockquote containing a list item. |
| 2420 |
assert to_md( |
| 2421 |
"<blockquote><ul><li>line1<br>line2</li></ul></blockquote>" |
| 2422 |
) == ("> - line1 \n > line2") |
| 2423 |
|
| 2424 |
|
| 2425 |
def test_conversion_html_to_markdown_tables(): |
| 2426 |
"""Test GFM table conversion.""" |
| 2427 |
|
| 2428 |
def to_md(body): |
| 2429 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 2430 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 2431 |
|
| 2432 |
# Basic table -- first row becomes the header, a "---" separator row is |
| 2433 |
# inserted right after it |
| 2434 |
assert to_md( |
| 2435 |
"<table><tr><td>A</td><td>B</td></tr>" |
| 2436 |
"<tr><td>1</td><td>2</td></tr></table>" |
| 2437 |
) == ("| A | B |\n| --- | --- |\n| 1 | 2 |") |
| 2438 |
|
| 2439 |
# <thead>/<tbody>/<th> are fully transparent -- header-vs-body is decided |
| 2440 |
# purely by row order, the same as <thead>-less markup |
| 2441 |
assert to_md( |
| 2442 |
"<table><thead><tr><th>Name</th><th>Age</th></tr></thead>" |
| 2443 |
"<tbody><tr><td>Bob</td><td>42</td></tr></tbody></table>" |
| 2444 |
) == ("| Name | Age |\n| --- | --- |\n| Bob | 42 |") |
| 2445 |
|
| 2446 |
# A single-row table still gets its separator row |
| 2447 |
assert to_md("<table><tr><td>only</td></tr></table>") == ( |
| 2448 |
"| only |\n| --- |" |
| 2449 |
) |
| 2450 |
|
| 2451 |
# Inline formatting inside cells is preserved |
| 2452 |
assert to_md( |
| 2453 |
"<table><tr><td><b>bold</b></td>" |
| 2454 |
'<td><a href="https://x.com">link</a></td></tr></table>' |
| 2455 |
) == ("| **bold** | [link](<https://x.com>) |\n| --- | --- |") |
| 2456 |
|
| 2457 |
# A literal '|' inside a cell is escaped -- it's the cell delimiter itself, |
| 2458 |
# and would otherwise be misread as starting a new column |
| 2459 |
assert to_md("<table><tr><td>a | b</td></tr></table>") == ( |
| 2460 |
"| a \\| b |\n| --- |" |
| 2461 |
) |
| 2462 |
|
| 2463 |
# A newline a cell's own content produced (here, a <br>) is flattened to a |
| 2464 |
# single space. |
| 2465 |
assert to_md("<table><tr><td>a<br>b</td></tr></table>") == ( |
| 2466 |
"| a b |\n| --- |" |
| 2467 |
) |
| 2468 |
|
| 2469 |
# Surrounding content gets ordinary paragraph separation from the table, |
| 2470 |
# the same as a list or blockquote would |
| 2471 |
assert to_md("<p>before</p><table><tr><td>A</td></tr></table>") == ( |
| 2472 |
"before\n\n| A |\n| --- |" |
| 2473 |
) |
| 2474 |
assert to_md("<table><tr><td>A</td></tr></table><p>after</p>") == ( |
| 2475 |
"| A |\n| --- |\n\nafter" |
| 2476 |
) |
| 2477 |
|
| 2478 |
# An entirely empty table, or a table whose only row has no cells at all, |
| 2479 |
# produces nothing |
| 2480 |
assert to_md("<table></table>") == "" |
| 2481 |
assert to_md("<table><tr></tr></table>") == "" |
| 2482 |
|
| 2483 |
# A table fully inside a suppressed container (e.g. <head>) contributes |
| 2484 |
# nothing -- not even an empty "| |" row |
| 2485 |
assert ( |
| 2486 |
to_md( |
| 2487 |
"<head><table><tr><td>x</td></tr></table></head><body>text</body>" |
| 2488 |
) |
| 2489 |
== "text" |
| 2490 |
) |
| 2491 |
|
| 2492 |
# Suppress text outside table cells. |
| 2493 |
assert to_md("<table>stray<tr><td>A</td></tr></table>") == ( |
| 2494 |
"| A |\n| --- |" |
| 2495 |
) |
| 2496 |
assert to_md("<table><tr>stray<td>A</td></tr></table>") == ( |
| 2497 |
"| A |\n| --- |" |
| 2498 |
) |
| 2499 |
assert to_md("<table>\n <tr>\n <td>A</td>\n </tr>\n</table>") == ( |
| 2500 |
"| A |\n| --- |" |
| 2501 |
) |
| 2502 |
|
| 2503 |
# A stray <td> with no enclosing <tr> at all falls back to ordinary |
| 2504 |
# paragraph-like treatment -- the same as before table support existed |
| 2505 |
assert to_md("<td>standalone</td>") == "standalone" |
| 2506 |
|
| 2507 |
# A stray <tr> with no enclosing <table> is treated as a one-row table of |
| 2508 |
# its own |
| 2509 |
assert to_md("<tr><td>a</td><td>b</td></tr>") == ( |
| 2510 |
"| a | b |\n| --- | --- |" |
| 2511 |
) |
| 2512 |
|
| 2513 |
|
| 2514 |
def test_conversion_html_to_markdown_tables_indentation(): |
| 2515 |
"""Test nested table indentation.""" |
| 2516 |
|
| 2517 |
def to_md(body): |
| 2518 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 2519 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 2520 |
|
| 2521 |
assert to_md( |
| 2522 |
"<ul><li>before<table><tr><td>A</td></tr></table></li></ul>" |
| 2523 |
) == ("- before\n\n | A |\n | --- |") |
| 2524 |
|
| 2525 |
assert to_md( |
| 2526 |
"<ul><li>before<table><tr><td>A</td><td>B</td></tr>" |
| 2527 |
"<tr><td>1</td><td>2</td></tr></table></li></ul>" |
| 2528 |
) == ("- before\n\n | A | B |\n | --- | --- |\n | 1 | 2 |") |
| 2529 |
|
| 2530 |
assert to_md( |
| 2531 |
"<blockquote><table><tr><td>A</td><td>B</td></tr>" |
| 2532 |
"<tr><td>1</td><td>2</td></tr></table></blockquote>" |
| 2533 |
) == ("> | A | B |\n> | --- | --- |\n> | 1 | 2 |") |
| 2534 |
|
| 2535 |
|
| 2536 |
def test_conversion_html_to_markdown_tables_hardening(): |
| 2537 |
"""Test malformed table input.""" |
| 2538 |
|
| 2539 |
def to_md(body): |
| 2540 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 2541 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 2542 |
|
| 2543 |
# Neither <td> nor <tr> ever closed -- extremely common in real- |
| 2544 |
# world/legacy table markup |
| 2545 |
assert to_md("<table><tr><td>A<td>B<tr><td>1<td>2</table>") == ( |
| 2546 |
"| A | B |\n| --- | --- |\n| 1 | 2 |" |
| 2547 |
) |
| 2548 |
|
| 2549 |
# Same, but the enclosing </table> is missing too -- the last row and cell |
| 2550 |
# are recovered at end of document |
| 2551 |
assert to_md("<table><tr><td>A<td>B<tr><td>1<td>2") == ( |
| 2552 |
"| A | B |\n| --- | --- |\n| 1 | 2 |" |
| 2553 |
) |
| 2554 |
|
| 2555 |
# A stray </tr> or </table> with nothing matching open at all (no enclosing |
| 2556 |
# structure whatsoever, not even an open cell) is a no-op. |
| 2557 |
assert to_md("</tr>text") == "text" |
| 2558 |
assert to_md("</table>text") == "text" |
| 2559 |
assert to_md("<p>a</tr>b</p>") == "ab" |
| 2560 |
assert to_md("<p>a</table>b</p>") == "ab" |
| 2561 |
|
| 2562 |
# A stray <tr> with no enclosing <table> renders as a one-row table of its |
| 2563 |
# own and remains separated from following content. |
| 2564 |
assert to_md("<tr><td>cell</td></tr>after") == ( |
| 2565 |
"| cell |\n| --- |\n\nafter" |
| 2566 |
) |
| 2567 |
|
| 2568 |
# A <table> nested inside another table's cell has no Markdown |
| 2569 |
# representation. |
| 2570 |
assert to_md( |
| 2571 |
"<table><tr><td>outer<table><tr><td>inner</td></tr></table>" |
| 2572 |
"</td></tr></table>" |
| 2573 |
) == ("| outer |\n| --- |") |
| 2574 |
|
| 2575 |
# Same, with content both before and after the nested table, and the |
| 2576 |
# nested table itself containing more than one row. |
| 2577 |
assert to_md( |
| 2578 |
"<table><tr><td>a<table><tr><td>b</td></tr><tr><td>c</td></tr>" |
| 2579 |
"</table>d</td></tr></table>" |
| 2580 |
) == ("| a d |\n| --- |") |
| 2581 |
|
| 2582 |
# Three levels deep -- only the outermost table survives. |
| 2583 |
assert to_md( |
| 2584 |
"<table><tr><td>L1<table><tr><td>L2<table><tr><td>L3</td></tr>" |
| 2585 |
"</table></td></tr></table></td></tr></table>" |
| 2586 |
) == ("| L1 |\n| --- |") |
| 2587 |
|
| 2588 |
# A literal '|' alongside a nested table in the same cell -- the '|' is |
| 2589 |
# still escaped normally; the nested table still contributes nothing. |
| 2590 |
assert to_md( |
| 2591 |
"<table><tr><td>a|b<table><tr><td>c</td></tr></table></td></tr>" |
| 2592 |
"</table>" |
| 2593 |
) == ("| a\\|b |\n| --- |") |
| 2594 |
|
| 2595 |
# Only the very first <tr> is ever closed |
| 2596 |
assert to_md("<table><tr><td>A</td></tr><tr><td>B<tr><td>C</table>") == ( |
| 2597 |
"| A |\n| --- |\n| B |\n| C |" |
| 2598 |
) |
| 2599 |
|
| 2600 |
# An unclosed inline element (<em>) inside a <td> is silently discarded |
| 2601 |
# when a sibling <td> opens; the cell's text is still captured. |
| 2602 |
assert ( |
| 2603 |
to_md( |
| 2604 |
"<table><tr><td><em>unclosed text<td>second cell</td></tr></table>" |
| 2605 |
) |
| 2606 |
== "| *unclosed text | second cell |\n| --- | --- |" |
| 2607 |
) |
| 2608 |
|
| 2609 |
# Performance: many rows, each with unclosed <td>/<tr> tags (the legacy- |
| 2610 |
# markup shape), large enough to expose quadratic recovery. |
| 2611 |
n = 20000 |
| 2612 |
html = "<table>" + "<tr><td>a<td>b" * n + "</table>" |
| 2613 |
start = default_timer() |
| 2614 |
out = to_md(html) |
| 2615 |
elapsed = default_timer() - start |
| 2616 |
assert out.count("\n") == n # one line per row, output stays linear |
| 2617 |
# Generous bound -- see the note on the equivalent check above. |
| 2618 |
assert elapsed < 40.0 |
| 2619 |
|
| 2620 |
|
| 2621 |
def test_conversion_html_to_markdown_pre_code_whitespace(): |
| 2622 |
"""Test preformatted whitespace.""" |
| 2623 |
|
| 2624 |
def to_md(body): |
| 2625 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 2626 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 2627 |
|
| 2628 |
# Internal leading whitespace and blank-looking indentation differences |
| 2629 |
# between lines are preserved exactly |
| 2630 |
assert ( |
| 2631 |
to_md("<pre> leading\n more leading\nback to zero</pre>") |
| 2632 |
== "```\n leading\n more leading\nback to zero\n```" |
| 2633 |
) |
| 2634 |
|
| 2635 |
# Leading/trailing spaces inside inline <code> survive too |
| 2636 |
assert to_md("<code> leading spaces </code>") == "` leading spaces `" |
| 2637 |
|
| 2638 |
# Whitespace is preserved the same way even when nested inside a list item |
| 2639 |
# (which now adds its own 2-space indentation in front. |
| 2640 |
assert to_md("<ul><li><pre> a\n b\nc</pre></li></ul>") == ( |
| 2641 |
"- ```\n a\n b\n c\n ```" |
| 2642 |
) |
| 2643 |
|
| 2644 |
|
| 2645 |
def test_conversion_html_to_markdown_unterminated_pre_code(): |
| 2646 |
"""Test <pre>/<code>/<samp> left open at end of document.""" |
| 2647 |
|
| 2648 |
def to_md(body): |
| 2649 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 2650 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 2651 |
|
| 2652 |
# A <pre>/<code>/<samp> with no closing tag at all is auto-closed and |
| 2653 |
# rendered at end of document. |
| 2654 |
assert to_md("<pre>unterminated code") == "```\nunterminated code\n```" |
| 2655 |
assert to_md("<code>inline unterminated") == "`inline unterminated`" |
| 2656 |
assert to_md("<samp>unterminated output") == ( |
| 2657 |
"```\nunterminated output\n```" |
| 2658 |
) |
| 2659 |
|
| 2660 |
# Still works with real content before the unterminated block. |
| 2661 |
assert to_md("text<pre>code") == "text\n```\ncode\n```" |
| 2662 |
|
| 2663 |
# A suppressed (non-storing) unterminated frame contributes nothing. |
| 2664 |
assert to_md("<head><pre>hidden") == "" |
| 2665 |
|
| 2666 |
|
| 2667 |
def test_conversion_html_to_markdown_table_code_pipe(): |
| 2668 |
"""Test '|' inside an inline code span within a table cell.""" |
| 2669 |
|
| 2670 |
def to_md(body): |
| 2671 |
"""Wrapper to simplify html-to-markdown conversion tests.""" |
| 2672 |
return convert_between(NotifyFormat.HTML, NotifyFormat.MARKDOWN, body) |
| 2673 |
|
| 2674 |
# A '|' inside a code span is already literal there. |
| 2675 |
assert to_md("<table><tr><td><code>a|b</code></td></tr></table>") == ( |
| 2676 |
"| `a|b` |\n| --- |" |
| 2677 |
) |
| 2678 |
|
| 2679 |
# A '|' outside any code span in the same cell is still escaped. |
| 2680 |
assert to_md("<table><tr><td>x|<code>a|b</code>|y</td></tr></table>") == ( |
| 2681 |
"| x\\|`a|b`\\|y |\n| --- |" |
| 2682 |
) |
| 2683 |
|
| 2684 |
# Literal backtick CHARACTERS typed as ordinary text (not an actual <code> |
| 2685 |
# element) get backslash-escaped by MARKDOWN_ESCAPE like any other. |
| 2686 |
assert to_md("<table><tr><td>`a|b`</td></tr></table>") == ( |
| 2687 |
"| \\`a\\|b\\` |\n| --- |" |
| 2688 |
) |
| 2689 |
|
| 2690 |
# A real code span and escaped literal backticks can coexist in the same |
| 2691 |
# cell -- only the real one's '|' stays unescaped. |
| 2692 |
assert to_md( |
| 2693 |
"<table><tr><td><code>x|y</code> and `lit|eral`</td></tr></table>" |
| 2694 |
) == ("| `x|y` and \\`lit\\|eral\\` |\n| --- |") |
| 2695 |
|
| 2696 |
# A real code span immediately preceded by an ESCAPED literal backslash (an |
| 2697 |
# even number of '\' characters, i.e. |
| 2698 |
assert to_md( |
| 2699 |
"<table><tr><td>text\\<code>a|b</code></td></tr></table>" |
| 2700 |
) == ("| text\\\\`a|b` |\n| --- |") |
| 2701 |
assert to_md( |
| 2702 |
"<table><tr><td>text\\\\<code>a|b</code></td></tr></table>" |
| 2703 |
) == ("| text\\\\\\\\`a|b` |\n| --- |") |
| 2704 |
|
| 2705 |
# An unmatched (unbalanced) bare backtick run inside a cell. |
| 2706 |
conv = HTMLMarkdownConverter() |
| 2707 |
assert conv._escape_cell_pipes("a`b|c") == "a`b\\|c" |
| 2708 |
|
| 2709 |
# The shared index skips escape pairs and groups runs by exact width. |
| 2710 |
# A lookup returns None when the requested width does not exist. |
| 2711 |
assert ( |
| 2712 |
commonmark_find_backtick_run( |
| 2713 |
commonmark_index_backtick_runs("\\` `"), 0, 1 |
| 2714 |
) |
| 2715 |
== 3 |
| 2716 |
) |
| 2717 |
assert ( |
| 2718 |
commonmark_find_backtick_run( |
| 2719 |
commonmark_index_backtick_runs("no backticks here"), 0, 1 |
| 2720 |
) |
| 2721 |
is None |
| 2722 |
) |
| 2723 |
assert ( |
| 2724 |
commonmark_find_backtick_run( |
| 2725 |
commonmark_index_backtick_runs("``too short"), 0, 3 |
| 2726 |
) |
| 2727 |
is None |
| 2728 |
) |
| 2729 |
|
| 2730 |
# Runs of different widths are indexed separately. |
| 2731 |
assert ( |
| 2732 |
commonmark_find_backtick_run( |
| 2733 |
commonmark_index_backtick_runs("`` `"), 0, 1 |
| 2734 |
) |
| 2735 |
== 3 |
| 2736 |
) |
| 2737 |
|
| 2738 |
# Skip an escaped single backtick before matching a width-two run. |
| 2739 |
assert ( |
| 2740 |
commonmark_find_backtick_run( |
| 2741 |
commonmark_index_backtick_runs("\\` ``x"), 0, 2 |
| 2742 |
) |
| 2743 |
== 3 |
| 2744 |
) |
| 2745 |
|
| 2746 |
# Skip an unescaped run of the wrong width before matching width two. |
| 2747 |
assert ( |
| 2748 |
commonmark_find_backtick_run( |
| 2749 |
commonmark_index_backtick_runs("` ``x"), 0, 2 |
| 2750 |
) |
| 2751 |
== 2 |
| 2752 |
) |
| 2753 |
|
| 2754 |
# A genuine match arbitrarily far from `start` is still found. |
| 2755 |
far = "a" * 200_000 + "`" |
| 2756 |
assert ( |
| 2757 |
commonmark_find_backtick_run(commonmark_index_backtick_runs(far), 0, 1) |
| 2758 |
== 200_000 |
| 2759 |
) |
| 2760 |
|
| 2761 |
# A cell containing many distinct, non-matching backtick-run lengths must |
| 2762 |
# still resolve in roughly linear time, not quadratic. |
| 2763 |
def adversarial_cell(width_count): |
| 2764 |
body = ["`" * w + "x" for w in range(1, width_count + 1)] |
| 2765 |
body.append("`") |
| 2766 |
return "".join(body) |
| 2767 |
|
| 2768 |
small = adversarial_cell(400) |
| 2769 |
large = adversarial_cell(800) |
| 2770 |
|
| 2771 |
start = default_timer() |
| 2772 |
conv._escape_cell_pipes(small) |
| 2773 |
small_time = default_timer() - start |
| 2774 |
|
| 2775 |
start = default_timer() |
| 2776 |
conv._escape_cell_pipes(large) |
| 2777 |
large_time = default_timer() - start |
| 2778 |
|
| 2779 |
# Double the adversarial width count. The additive term absorbs |
| 2780 |
# scheduler/measurement noise -- generous so a busy or throttled |
| 2781 |
# build machine (where even trivial calls can take longer) does not |
| 2782 |
# trip this on noise alone; the multiplier is what actually catches |
| 2783 |
# a real return to quadratic behavior. |
| 2784 |
assert large_time < small_time * 6 + 0.5 |
| 2785 |
|
| 2786 |
|
| 2787 |
def test_conversion_text_to(): |
| 2788 |
"""conversion: Test Text to all types""" |
| 2789 |
|
| 2790 |
response = convert_between( |
| 2791 |
NotifyFormat.TEXT, |
| 2792 |
NotifyFormat.HTML, |
| 2793 |
"<title>Test Message</title><body>Body</body>", |
| 2794 |
) |
| 2795 |
|
| 2796 |
assert ( |
| 2797 |
response |
| 2798 |
== "<title>Test Message</title><body>Body<" |
| 2799 |
"/body>" |
| 2800 |
) |
| 2801 |
|
| 2802 |
|
| 2803 |
def test_conversion_text_to_markdown(): |
| 2804 |
"""conversion: Test Text to Markdown""" |
| 2805 |
|
| 2806 |
def to_markdown(body): |
| 2807 |
"""Convert plain text through the public dispatcher.""" |
| 2808 |
return convert_between(NotifyFormat.TEXT, NotifyFormat.MARKDOWN, body) |
| 2809 |
|
| 2810 |
# CommonMark-significant characters are escaped so they read as |
| 2811 |
# literal text instead of being misread as formatting. |
| 2812 |
response = to_markdown("Some *text* with _markdown_ looking chars.") |
| 2813 |
assert response == "Some \\*text\\* with \\_markdown\\_ looking chars\\." |
| 2814 |
|
| 2815 |
# Text without Markdown-significant characters is unchanged. |
| 2816 |
assert to_markdown("hello world") == "hello world" |
| 2817 |
|
| 2818 |
# Every Markdown-significant punctuation character gets escaped. |
| 2819 |
response = to_markdown("_*[]()~`>#+=|{}.!-") |
| 2820 |
assert response == "\\_\\*\\[\\]\\(\\)\\~\\`\\>\\#\\+\\=\\|\\{\\}\\.\\!\\-" |
| 2821 |
|
| 2822 |
# Plain text has no escape state, so a literal backslash is escaped. |
| 2823 |
response = to_markdown("already \\* escaped") |
| 2824 |
assert response == "already \\\\\\* escaped" |
| 2825 |
assert markdown_to_html(response) == "<p>already \\* escaped</p>" |
| 2826 |
|
| 2827 |
# Windows-style paths survive CommonMark rendering unchanged. |
| 2828 |
response = to_markdown("C:\\Users\\foo") |
| 2829 |
assert response == "C:\\\\Users\\\\foo" |
| 2830 |
assert markdown_to_html(response) == "<p>C:\\Users\\foo</p>" |
| 2831 |
|
| 2832 |
# Backslash-plus-syntax is still literal plain text. |
| 2833 |
response = to_markdown("\\# heading") |
| 2834 |
assert response == "\\\\\\# heading" |
| 2835 |
assert markdown_to_html(response) == "<p>\\# heading</p>" |
| 2836 |
|
| 2837 |
# The generic dispatcher resolves the same conversion pair. |
| 2838 |
assert ( |
| 2839 |
convert_between(NotifyFormat.TEXT, NotifyFormat.MARKDOWN, "hello") |
| 2840 |
== "hello" |
| 2841 |
) |
| 2842 |
|
| 2843 |
|
| 2844 |
def test_conversion_markdown_to_html(): |
| 2845 |
"""conversion: Test markdown to html""" |
| 2846 |
|
| 2847 |
# While this uses the underlining markdown library |
| 2848 |
# what we're testing for are the edge cases we know it doesn't support |
| 2849 |
# hence, `-` (a dash) with the markdown library must be a `*` to work |
| 2850 |
# correctly |
| 2851 |
response = convert_between( |
| 2852 |
NotifyFormat.MARKDOWN, |
| 2853 |
NotifyFormat.HTML, |
| 2854 |
cleandoc(""" |
| 2855 |
## Some Heading |
| 2856 |
|
| 2857 |
With Data: |
| 2858 |
|
| 2859 |
- Foo |
| 2860 |
- Bar |
| 2861 |
"""), |
| 2862 |
) |
| 2863 |
|
| 2864 |
assert "<li>Foo</li>" in response |
| 2865 |
assert "<li>Bar</li>" in response |
| 2866 |
assert "<h2>Some Heading</h2>" in response |
| 2867 |
assert "<br />" not in response |
| 2868 |
|
| 2869 |
# if the - follows With Data on the very next line, it's consider to not |
| 2870 |
# requiring indentation |
| 2871 |
response = convert_between( |
| 2872 |
NotifyFormat.MARKDOWN, |
| 2873 |
NotifyFormat.HTML, |
| 2874 |
cleandoc(""" |
| 2875 |
## Some Heading |
| 2876 |
|
| 2877 |
With Data: |
| 2878 |
- Foo |
| 2879 |
- Bar |
| 2880 |
"""), |
| 2881 |
) |
| 2882 |
|
| 2883 |
# Breaks are added: |
| 2884 |
assert "<br />" in response |
| 2885 |
assert "- Foo" in response |
| 2886 |
assert "- Bar" in response |
| 2887 |
|
| 2888 |
# Table formatting |
| 2889 |
response = convert_between( |
| 2890 |
NotifyFormat.MARKDOWN, |
| 2891 |
NotifyFormat.HTML, |
| 2892 |
cleandoc(""" |
| 2893 |
First Header | Second Header |
| 2894 |
-------------- | ------------- |
| 2895 |
Content Cell1 | Content Cell3 |
| 2896 |
Content Cell2 | Content Cell4 |
| 2897 |
"""), |
| 2898 |
) |
| 2899 |
|
| 2900 |
assert "<table>" in response |
| 2901 |
assert "<th>First Header</th>" in response |
| 2902 |
assert "<th>Second Header</th>" in response |
| 2903 |
assert "<td>Content Cell1</td>" in response |
| 2904 |
assert "<td>Content Cell2</td>" in response |
| 2905 |
assert "<td>Content Cell3</td>" in response |
| 2906 |
assert "<td>Content Cell4</td>" in response |
| 2907 |
|
| 2908 |
|
| 2909 |
def test_conversion_commonmark_repair_chunk(): |
| 2910 |
"""Test dialect-neutral repair of split or truncated CommonMark.""" |
| 2911 |
|
| 2912 |
# No cut at all: input passes through unchanged. |
| 2913 |
assert commonmark_repair_chunk("**bold** and *italic*", {}) == ( |
| 2914 |
"**bold** and *italic*", |
| 2915 |
{}, |
| 2916 |
) |
| 2917 |
|
| 2918 |
# A complete, uncut code span within a single chunk is untouched. |
| 2919 |
assert commonmark_repair_chunk("before ```code``` after", {}) == ( |
| 2920 |
"before ```code``` after", |
| 2921 |
{}, |
| 2922 |
) |
| 2923 |
|
| 2924 |
# A complete, uncut link within a single chunk is untouched. |
| 2925 |
assert commonmark_repair_chunk( |
| 2926 |
"[label](<https://example.com>) tail", {} |
| 2927 |
) == ("[label](<https://example.com>) tail", {}) |
| 2928 |
|
| 2929 |
# Escape a non-opening run so dialect adapters preserve it literally. |
| 2930 |
assert commonmark_repair_chunk("a**** b", {}) == ("a\\*\\*\\*\\* b", {}) |
| 2931 |
|
| 2932 |
# Preserve existing escapes rather than treating them as delimiters. |
| 2933 |
assert commonmark_repair_chunk("a\\*b\\*c", {}) == ("a\\*b\\*c", {}) |
| 2934 |
|
| 2935 |
# A message split exactly between a backslash and the character it |
| 2936 |
# escapes must not double the backslash or free that character to |
| 2937 |
# act as a fresh delimiter -- the escape is carried across the split. |
| 2938 |
first, pending = commonmark_repair_chunk("aaaaa\\", {}) |
| 2939 |
assert (first, pending) == ("aaaaa\\", {"in_escape": True}) |
| 2940 |
assert commonmark_repair_chunk("*literal", pending) == ( |
| 2941 |
"*literal", |
| 2942 |
{}, |
| 2943 |
) |
| 2944 |
# An empty continuation chunk keeps waiting rather than losing track. |
| 2945 |
assert commonmark_repair_chunk("", pending) == ("", {"in_escape": True}) |
| 2946 |
|
| 2947 |
# Close split bold early, then discard its original closing marker. |
| 2948 |
# Lookahead containing the delimiter justifies carrying the open span. |
| 2949 |
assert commonmark_repair_chunk("**xxxxx", {}, next_chunk="xxxx**TAIL") == ( |
| 2950 |
"**xxxxx**", |
| 2951 |
{"**": 1}, |
| 2952 |
) |
| 2953 |
assert commonmark_repair_chunk("xxxx**TAIL", {"**": 1}) == ( |
| 2954 |
"xxxxTAIL", |
| 2955 |
{"**": 0}, |
| 2956 |
) |
| 2957 |
|
| 2958 |
# Same for an italic span. |
| 2959 |
assert commonmark_repair_chunk("*hello wor", {}, next_chunk="ld*end") == ( |
| 2960 |
"*hello wor*", |
| 2961 |
{"*": 1}, |
| 2962 |
) |
| 2963 |
assert commonmark_repair_chunk("ld*end", {"*": 1}) == ("ldend", {"*": 0}) |
| 2964 |
|
| 2965 |
# A triple-asterisk run (bold+italic combined) cut mid-content. |
| 2966 |
assert commonmark_repair_chunk( |
| 2967 |
"***strong italic", {}, next_chunk="text***tail" |
| 2968 |
) == ("***strong italic***", {"**": 1, "*": 1}) |
| 2969 |
assert commonmark_repair_chunk("text***tail", {"**": 1, "*": 1}) == ( |
| 2970 |
"texttail", |
| 2971 |
{"**": 0, "*": 0}, |
| 2972 |
) |
| 2973 |
|
| 2974 |
# Carry each span only when lookahead provides enough closing width. |
| 2975 |
assert commonmark_repair_chunk( |
| 2976 |
"**bold _italic", {}, next_chunk="a_ and b** more" |
| 2977 |
) == ("**bold _italic_**", {"_": 1, "**": 1}) |
| 2978 |
|
| 2979 |
# Repair underscore emphasis when the later run can genuinely close. |
| 2980 |
assert commonmark_repair_chunk("_hello wor", {}, next_chunk="ld_ end") == ( |
| 2981 |
"_hello wor_", |
| 2982 |
{"_": 1}, |
| 2983 |
) |
| 2984 |
assert commonmark_repair_chunk("ld_ end", {"_": 1}) == ( |
| 2985 |
"ld end", |
| 2986 |
{"_": 0}, |
| 2987 |
) |
| 2988 |
|
| 2989 |
# Underscore-based CommonMark bold ("__") behaves the same way. |
| 2990 |
assert commonmark_repair_chunk( |
| 2991 |
"__strong wor", {}, next_chunk="ld__ end" |
| 2992 |
) == ("__strong wor__", {"__": 1}) |
| 2993 |
assert commonmark_repair_chunk("ld__ end", {"__": 1}) == ( |
| 2994 |
"ld end", |
| 2995 |
{"__": 0}, |
| 2996 |
) |
| 2997 |
|
| 2998 |
# Ignore an intraword underscore that cannot close CommonMark emphasis. |
| 2999 |
# The opener never gets to pair with anything, so it is escaped too. |
| 3000 |
assert commonmark_repair_chunk("_hello wor", {}, next_chunk="ld_end") == ( |
| 3001 |
"\\_hello wor", |
| 3002 |
{}, |
| 3003 |
) |
| 3004 |
|
| 3005 |
# Preserve complete underscore spans. A run that fails the |
| 3006 |
# flanking rule (here, followed by whitespace) stays literal. |
| 3007 |
assert commonmark_repair_chunk("_italic text_ done", {}) == ( |
| 3008 |
"_italic text_ done", |
| 3009 |
{}, |
| 3010 |
) |
| 3011 |
# Same for underscore-based strong emphasis -- never matches anything, |
| 3012 |
# so it is escaped too. |
| 3013 |
assert commonmark_repair_chunk("a____ b", {}) == ("a\\_\\_\\_\\_ b", {}) |
| 3014 |
|
| 3015 |
# A trailing run after whitespace cannot open or close either, so it |
| 3016 |
# is also escaped rather than left as a bare, ambiguous-looking pair. |
| 3017 |
assert commonmark_repair_chunk("text **", {}) == ("text \\*\\*", {}) |
| 3018 |
|
| 3019 |
# A lone trailing run that can theoretically open (the lookahead's |
| 3020 |
# first character is a real letter) but finds no actual "*"/"_" in |
| 3021 |
# that lookahead is still just literal text here -- escaped, since |
| 3022 |
# this occurrence is never going to be carried forward either. |
| 3023 |
assert commonmark_repair_chunk("a" * 5 + "*", {}, next_chunk="b" * 5) == ( |
| 3024 |
"a" * 5 + "\\*", |
| 3025 |
{}, |
| 3026 |
) |
| 3027 |
assert commonmark_repair_chunk("(_", {}, next_chunk="y") == ("(\\_", {}) |
| 3028 |
|
| 3029 |
# Without a possible closer in lookahead, preserve the trailing run -- |
| 3030 |
# escaped, since this occurrence will never be carried forward. |
| 3031 |
assert commonmark_repair_chunk("a**", {}, next_chunk="b") == ( |
| 3032 |
"a\\*\\*", |
| 3033 |
{}, |
| 3034 |
) |
| 3035 |
|
| 3036 |
# With a possible closer, discard the trailing empty pair as noise. |
| 3037 |
assert commonmark_repair_chunk("a**", {}, next_chunk="more*text") == ( |
| 3038 |
"a", |
| 3039 |
{}, |
| 3040 |
) |
| 3041 |
|
| 3042 |
# Preserve a literal asterisk before valid underscore emphasis. |
| 3043 |
assert commonmark_repair_chunk("*_a_", {}, next_chunk=" " + "x" * 99) == ( |
| 3044 |
"\\*_a_", |
| 3045 |
{}, |
| 3046 |
) |
| 3047 |
|
| 3048 |
# A possible closer makes the same opener eligible for continuation. |
| 3049 |
assert commonmark_repair_chunk("*_a_", {}, next_chunk=" x*x") == ( |
| 3050 |
"*_a_*", |
| 3051 |
{"*": 1}, |
| 3052 |
) |
| 3053 |
|
| 3054 |
# Ignore a whitespace-boxed delimiter that cannot close the earlier span. |
| 3055 |
assert commonmark_repair_chunk( |
| 3056 |
"*_a_", {}, next_chunk=" literal * end" |
| 3057 |
) == ("\\*_a_", {}) |
| 3058 |
|
| 3059 |
# Ignore a later opener-only run when repairing an earlier span. |
| 3060 |
assert commonmark_repair_chunk("*_a_", {}, next_chunk=" *end") == ( |
| 3061 |
"\\*_a_", |
| 3062 |
{}, |
| 3063 |
) |
| 3064 |
|
| 3065 |
# A delimiter-like character sitting inside a code span in the |
| 3066 |
# lookahead is literal code content, not a real closer -- it must be |
| 3067 |
# skipped the same way it would be if it were in this same chunk. |
| 3068 |
assert commonmark_repair_chunk("*abc", {}, next_chunk="`x* y` tail") == ( |
| 3069 |
"\\*abc", |
| 3070 |
{}, |
| 3071 |
) |
| 3072 |
# Same idea for a delimiter-like character inside a link destination. |
| 3073 |
assert commonmark_repair_chunk( |
| 3074 |
"*abc", {}, next_chunk="](<http://x.com/a*b>) tail" |
| 3075 |
) == ("\\*abc", {}) |
| 3076 |
|
| 3077 |
# Following text can make a boundary underscore intraword and literal. |
| 3078 |
assert commonmark_repair_chunk("*_a_", {}, next_chunk="x" * 100) == ( |
| 3079 |
"\\*\\_a\\_", |
| 3080 |
{}, |
| 3081 |
) |
| 3082 |
|
| 3083 |
# Use the current chunk's final character to classify a boundary closer. |
| 3084 |
assert commonmark_repair_chunk("*hello", {}, next_chunk="* world") == ( |
| 3085 |
"*hello*", |
| 3086 |
{"*": 1}, |
| 3087 |
) |
| 3088 |
# Splitting the same source keeps the resulting markers balanced. |
| 3089 |
pieces = split_dialect_chunk("*hello* world", 6, lambda body: body) |
| 3090 |
joined = "".join(pieces) |
| 3091 |
assert joined.count("*") % 2 == 0 |
| 3092 |
|
| 3093 |
# Adjacent delimiters use source characters rather than placeholders. |
| 3094 |
assert commonmark_repair_chunk("*_a_", {}) == ("\\*_a_", {}) |
| 3095 |
assert commonmark_repair_chunk("**_a_", {}) == ("\\*\\*_a_", {}) |
| 3096 |
|
| 3097 |
# The character after bounded lookahead classifies its trailing delimiter |
| 3098 |
# without becoming part of the scanned content. |
| 3099 |
assert commonmark_repair_chunk( |
| 3100 |
"_abc", {}, next_chunk="xxxx_", next_chunk_boundary_ch="w" |
| 3101 |
) == ("\\_abc", {}) |
| 3102 |
assert commonmark_repair_chunk( |
| 3103 |
"_abc", {}, next_chunk="xxxx_", next_chunk_boundary_ch=" " |
| 3104 |
) == ("_abc_", {"_": 1}) |
| 3105 |
assert commonmark_repair_chunk("_abc", {}, next_chunk="xxxx_") == ( |
| 3106 |
"_abc_", |
| 3107 |
{"_": 1}, |
| 3108 |
) |
| 3109 |
|
| 3110 |
# A delimiter just beyond bounded lookahead must not validate an earlier |
| 3111 |
# opener as though it were inside the scanned slice. |
| 3112 |
body = "_abc" + ("x" * 32) + "_word" |
| 3113 |
lookahead_span = 4 * 8 |
| 3114 |
lookahead = body[4 : 4 + lookahead_span] |
| 3115 |
boundary_next_ch = body[4 + lookahead_span : 4 + lookahead_span + 1] |
| 3116 |
assert commonmark_repair_chunk( |
| 3117 |
body[:4], |
| 3118 |
{}, |
| 3119 |
next_chunk=lookahead, |
| 3120 |
next_chunk_boundary_ch=boundary_next_ch or None, |
| 3121 |
) == ("\\_abc", {}) |
| 3122 |
|
| 3123 |
# A single closer carries regular emphasis and escapes the excess marker. |
| 3124 |
assert commonmark_repair_chunk("**bold", {}, next_chunk="x* end") == ( |
| 3125 |
"\\**bold*", |
| 3126 |
{"*": 1}, |
| 3127 |
) |
| 3128 |
# Consuming the pending single marker preserves an unrelated bold pair. |
| 3129 |
assert commonmark_repair_chunk( |
| 3130 |
"x* end unrelated **bold** later", {"*": 1} |
| 3131 |
) == ("x end unrelated **bold** later", {"*": 0}) |
| 3132 |
|
| 3133 |
# Carry one verified regular closer and escape remaining local width. |
| 3134 |
assert commonmark_repair_chunk("a****b", {}, next_chunk="more *text*") == ( |
| 3135 |
"a\\*\\*\\**b*", |
| 3136 |
{"*": 1}, |
| 3137 |
) |
| 3138 |
assert commonmark_repair_chunk("(____x", {}, next_chunk="more _text_") == ( |
| 3139 |
"(\\_\\_\\__x_", |
| 3140 |
{"_": 1}, |
| 3141 |
) |
| 3142 |
|
| 3143 |
# Drop a split code fence while carrying its width to the next chunk. |
| 3144 |
assert commonmark_repair_chunk("text ```code sti", {}) == ( |
| 3145 |
"text code sti", |
| 3146 |
{"in_code": 3}, |
| 3147 |
) |
| 3148 |
|
| 3149 |
# Render a cross-message code continuation as plain text. |
| 3150 |
assert commonmark_repair_chunk("ll going```code done", {"in_code": 3}) == ( |
| 3151 |
"ll goingcode done", |
| 3152 |
{}, |
| 3153 |
) |
| 3154 |
|
| 3155 |
# Carry an unclosed code span into another chunk. |
| 3156 |
assert commonmark_repair_chunk("more code", {"in_code": 3}) == ( |
| 3157 |
"more code", |
| 3158 |
{"in_code": 3}, |
| 3159 |
) |
| 3160 |
|
| 3161 |
# Drop and carry a newly opened single-backtick span. |
| 3162 |
assert commonmark_repair_chunk("`code no close", {}) == ( |
| 3163 |
"code no close", |
| 3164 |
{"in_code": 1}, |
| 3165 |
) |
| 3166 |
|
| 3167 |
# Escape a link label cut across the chunk boundary. |
| 3168 |
assert commonmark_repair_chunk("[click", {}) == ("\\[click", {}) |
| 3169 |
|
| 3170 |
# Render the unmatched destination side as literal text. |
| 3171 |
assert commonmark_repair_chunk( |
| 3172 |
"here](<https://example.com/path>) rest", {} |
| 3173 |
) == ("here\\]\\(https://example.com/path\\>\\) rest", {}) |
| 3174 |
|
| 3175 |
# Carry a closing marker split after its trailing ">". |
| 3176 |
c1, pending = commonmark_repair_chunk("[label](<https://x.com>", {}) |
| 3177 |
assert (c1, pending) == ( |
| 3178 |
"[label\\]\\(https://x.com\\>", |
| 3179 |
{"in_link_dest": True, "dest_gt": True}, |
| 3180 |
) |
| 3181 |
c2, pending = commonmark_repair_chunk(") tail", pending) |
| 3182 |
assert (c2, pending) == ("\\) tail", {}) |
| 3183 |
|
| 3184 |
# Ignore a mid-destination ">" and continue to the real terminator. |
| 3185 |
assert commonmark_repair_chunk("a>b>) tail", {"in_link_dest": True}) == ( |
| 3186 |
"a\\>b\\>\\) tail", |
| 3187 |
{}, |
| 3188 |
) |
| 3189 |
|
| 3190 |
# Carry a link destination cut across chunks. |
| 3191 |
assert commonmark_repair_chunk("[label](<https://example.com/", {}) == ( |
| 3192 |
"[label\\]\\(https://example.com/", |
| 3193 |
{"in_link_dest": True}, |
| 3194 |
) |
| 3195 |
|
| 3196 |
# Render a carried destination's closing fragment as literal text. |
| 3197 |
assert commonmark_repair_chunk( |
| 3198 |
"more-path>) tail", {"in_link_dest": True} |
| 3199 |
) == ("more-path\\>\\) tail", {}) |
| 3200 |
|
| 3201 |
# Ignore escaped characters while finding a destination terminator. |
| 3202 |
assert commonmark_repair_chunk("a\\)b>) tail", {"in_link_dest": True}) == ( |
| 3203 |
"a\\\\\\)b\\>\\) tail", |
| 3204 |
{}, |
| 3205 |
) |
| 3206 |
|
| 3207 |
# Carry a destination that remains unclosed. |
| 3208 |
assert commonmark_repair_chunk( |
| 3209 |
"still not done", {"in_link_dest": True} |
| 3210 |
) == ("still not done", {"in_link_dest": True}) |
| 3211 |
|
| 3212 |
# Complete a destination terminator spread across three chunks. |
| 3213 |
c1, pending = commonmark_repair_chunk( |
| 3214 |
"[label](<https://example.com/path", {} |
| 3215 |
) |
| 3216 |
assert (c1, pending) == ( |
| 3217 |
"[label\\]\\(https://example.com/path", |
| 3218 |
{"in_link_dest": True}, |
| 3219 |
) |
| 3220 |
c2, pending = commonmark_repair_chunk("/more>", pending) |
| 3221 |
assert (c2, pending) == ( |
| 3222 |
"/more\\>", |
| 3223 |
{"in_link_dest": True, "dest_gt": True}, |
| 3224 |
) |
| 3225 |
c3, pending = commonmark_repair_chunk(") tail text", pending) |
| 3226 |
assert (c3, pending) == ("\\) tail text", {}) |
| 3227 |
|
| 3228 |
# Treat a trailing ">" as literal when the next chunk lacks ")". |
| 3229 |
c2b, pending = commonmark_repair_chunk("more>", {"in_link_dest": True}) |
| 3230 |
assert (c2b, pending) == ( |
| 3231 |
"more\\>", |
| 3232 |
{"in_link_dest": True, "dest_gt": True}, |
| 3233 |
) |
| 3234 |
c3b, pending = commonmark_repair_chunk("no closing paren here", pending) |
| 3235 |
assert (c3b, pending) == ( |
| 3236 |
"no closing paren here", |
| 3237 |
{"in_link_dest": True}, |
| 3238 |
) |
| 3239 |
|
| 3240 |
# User-provided Private Use text must not collide with internal emphasis |
| 3241 |
# placeholders, with or without real emphasis in the same chunk. |
| 3242 |
marker = chr(0xE000) |
| 3243 |
attack = f"before {marker}0{marker} after" |
| 3244 |
assert commonmark_repair_chunk(attack, {}) == (attack, {}) |
| 3245 |
assert commonmark_repair_chunk(f"*bold* {attack}", {}) == ( |
| 3246 |
f"*bold* {attack}", |
| 3247 |
{}, |
| 3248 |
) |
| 3249 |
|
| 3250 |
# Preserve an opener-only chunk when lookahead verifies its closer. |
| 3251 |
assert commonmark_repair_chunk("**", {}, next_chunk="abc**") == ( |
| 3252 |
"****", |
| 3253 |
{"**": 1}, |
| 3254 |
) |
| 3255 |
|
| 3256 |
|
| 3257 |
def test_conversion_commonmark_scan_autolink_dest(): |
| 3258 |
"""commonmark_scan_autolink_dest: scheme validation and termination.""" |
| 3259 |
|
| 3260 |
# A complete autolink -- "*" inside it is not a delimiter. |
| 3261 |
body = "<https://a*b>" |
| 3262 |
assert commonmark_scan_autolink_dest(body, 0, len(body)) == (12, True) |
| 3263 |
|
| 3264 |
# No scheme colon at all -- never a genuine autolink. |
| 3265 |
body = "<hello world>" |
| 3266 |
assert commonmark_scan_autolink_dest(body, 0, len(body)) == (None, False) |
| 3267 |
|
| 3268 |
# A nested "<" disqualifies it outright. |
| 3269 |
body = "<http:<x>" |
| 3270 |
assert commonmark_scan_autolink_dest(body, 0, len(body)) == (None, False) |
| 3271 |
|
| 3272 |
# Whitespace inside the destination disqualifies it too. |
| 3273 |
body = "<http: x>" |
| 3274 |
assert commonmark_scan_autolink_dest(body, 0, len(body)) == (None, False) |
| 3275 |
|
| 3276 |
# A control character disqualifies it the same way. |
| 3277 |
body = "<http:\x01x>" |
| 3278 |
assert commonmark_scan_autolink_dest(body, 0, len(body)) == (None, False) |
| 3279 |
|
| 3280 |
# Valid so far but no ">" anywhere yet -- still could complete later. |
| 3281 |
body = "<https://example.com" |
| 3282 |
assert commonmark_scan_autolink_dest(body, 0, len(body)) == (None, True) |
| 3283 |
|
| 3284 |
|
| 3285 |
def test_conversion_commonmark_scan_paren_dest(): |
| 3286 |
"""commonmark_scan_paren_dest: balanced parens and disqualifiers.""" |
| 3287 |
|
| 3288 |
# A complete, simple bare destination. |
| 3289 |
body = "](abc)" |
| 3290 |
assert commonmark_scan_paren_dest(body, 1, len(body)) == 5 |
| 3291 |
|
| 3292 |
# An escaped ")" does not close the destination early. |
| 3293 |
body = "](a\\)b)" |
| 3294 |
assert commonmark_scan_paren_dest(body, 1, len(body)) == 6 |
| 3295 |
|
| 3296 |
# One level of balanced, unescaped parens is allowed. |
| 3297 |
body = "](a(b)c)" |
| 3298 |
assert commonmark_scan_paren_dest(body, 1, len(body)) == 7 |
| 3299 |
|
| 3300 |
# Whitespace disqualifies a bare destination entirely. |
| 3301 |
body = "](a b)" |
| 3302 |
assert commonmark_scan_paren_dest(body, 1, len(body)) is None |
| 3303 |
|
| 3304 |
# A control character disqualifies it the same way. |
| 3305 |
body = "](a\x01b)" |
| 3306 |
assert commonmark_scan_paren_dest(body, 1, len(body)) is None |
| 3307 |
|
| 3308 |
# An embedded "<" also disqualifies it. |
| 3309 |
body = "](a<b)" |
| 3310 |
assert commonmark_scan_paren_dest(body, 1, len(body)) is None |
| 3311 |
|
| 3312 |
# No closing ")" anywhere in the slice. |
| 3313 |
body = "](abc" |
| 3314 |
assert commonmark_scan_paren_dest(body, 1, len(body)) is None |
| 3315 |
|
| 3316 |
|
| 3317 |
def test_conversion_lookahead_with_unfinished_angle_url(): |
| 3318 |
"""An unterminated ``](<url`` in the lookahead stops the scan early. |
| 3319 |
|
| 3320 |
This covers the angle-bracket branch alongside the existing bare URL case. |
| 3321 |
""" |
| 3322 |
widths = commonmark_module.commonmark_lookahead_closer_widths( |
| 3323 |
"](<https://example.com" |
| 3324 |
) |
| 3325 |
assert widths == {} |
| 3326 |
|
| 3327 |
|
| 3328 |
def test_conversion_commonmark_repair_chunk_autolinks(): |
| 3329 |
"""Standalone autolinks keep markup-like URL characters as text.""" |
| 3330 |
|
| 3331 |
# URL punctuation must not close unrelated emphasis in the same chunk. |
| 3332 |
body = "Note *this is important, see <https://a*b> for details" |
| 3333 |
assert commonmark_repair_chunk(body, {}) == ( |
| 3334 |
"Note \\*this is important, see <https://a*b> for details", |
| 3335 |
{}, |
| 3336 |
) |
| 3337 |
|
| 3338 |
# Lookahead ignores false emphasis closers inside URLs. |
| 3339 |
c1, pending = commonmark_repair_chunk( |
| 3340 |
"hello *world", {}, next_chunk=" <https://a*b> end" |
| 3341 |
) |
| 3342 |
assert (c1, pending) == ("hello \\*world", {}) |
| 3343 |
c2, pending = commonmark_repair_chunk(" <https://a*b> end", pending) |
| 3344 |
assert (c2, pending) == (" <https://a*b> end", {}) |
| 3345 |
|
| 3346 |
# The same split, but the terminator itself lands in a third chunk. |
| 3347 |
c1, pending = commonmark_repair_chunk( |
| 3348 |
"see <https://a", {}, next_chunk="*b> end" |
| 3349 |
) |
| 3350 |
assert (c1, pending) == ("see \\<https://a", {"in_autolink": True}) |
| 3351 |
c2, pending = commonmark_repair_chunk("*b", pending) |
| 3352 |
assert (c2, pending) == ("\\*b", {"in_autolink": True}) |
| 3353 |
c3, pending = commonmark_repair_chunk("> end", pending) |
| 3354 |
assert (c3, pending) == ("\\> end", {}) |
| 3355 |
|
| 3356 |
# A "<" that never forms a valid scheme is left as ordinary text. |
| 3357 |
assert commonmark_repair_chunk("a < b", {}) == ("a < b", {}) |
| 3358 |
|
| 3359 |
|
| 3360 |
def test_conversion_commonmark_repair_chunk_bare_links(): |
| 3361 |
"""commonmark_repair_chunk: bare (non-angle-bracket) link destinations.""" |
| 3362 |
|
| 3363 |
# Preserve labeled bare links without scanning their URLs as emphasis. |
| 3364 |
assert commonmark_repair_chunk("[x](https://a*b)", {}) == ( |
| 3365 |
"[x](https://a*b)", |
| 3366 |
{}, |
| 3367 |
) |
| 3368 |
|
| 3369 |
# Escape an orphan destination and keep its contents literal. |
| 3370 |
assert commonmark_repair_chunk("see ](a*b) now", {}) == ( |
| 3371 |
"see \\]\\(a\\*b\\) now", |
| 3372 |
{}, |
| 3373 |
) |
| 3374 |
|
| 3375 |
# Leave an unfinished bare URL untouched without carrying state. |
| 3376 |
assert commonmark_repair_chunk("[x](https://a*b", {}) == ( |
| 3377 |
"[x](https://a*b", |
| 3378 |
{}, |
| 3379 |
) |
| 3380 |
|
| 3381 |
|
| 3382 |
def test_conversion_commonmark_lookahead_ignores_link_markup(): |
| 3383 |
"""Lookahead ignores markup-like characters inside links.""" |
| 3384 |
|
| 3385 |
# A complete bare link cannot close earlier emphasis. |
| 3386 |
assert commonmark_repair_chunk( |
| 3387 |
"*word", {}, next_chunk=" see ](a*b) now" |
| 3388 |
) == ("\\*word", {}) |
| 3389 |
|
| 3390 |
# An unfinished bare URL cannot close earlier emphasis either. |
| 3391 |
assert commonmark_repair_chunk("*word", {}, next_chunk=" see ](a*b") == ( |
| 3392 |
"\\*word", |
| 3393 |
{}, |
| 3394 |
) |
| 3395 |
|
| 3396 |
# A complete autolink cannot close earlier emphasis. |
| 3397 |
assert commonmark_repair_chunk( |
| 3398 |
"*word", {}, next_chunk=" see <https://a*b> now" |
| 3399 |
) == ("\\*word", {}) |
| 3400 |
|
| 3401 |
# An autolink that never closes within the lookahead span. |
| 3402 |
assert commonmark_repair_chunk( |
| 3403 |
"*word", {}, next_chunk=" see <https://a*b" |
| 3404 |
) == ("\\*word", {}) |
| 3405 |
|
| 3406 |
# An invalid autolink falls back to ordinary delimiter scanning. |
| 3407 |
assert commonmark_repair_chunk("*word", {}, next_chunk=" a < b* end") == ( |
| 3408 |
"*word*", |
| 3409 |
{"*": 1}, |
| 3410 |
) |
| 3411 |
|
| 3412 |
|
| 3413 |
def test_conversion_commonmark_materialize_repair(): |
| 3414 |
"""Reusable scans must match direct repair for every requested prefix.""" |
| 3415 |
|
| 3416 |
lookahead_span = 64 |
| 3417 |
|
| 3418 |
def _direct(body, offset, cut, pending, lookahead_span=lookahead_span): |
| 3419 |
# The behavior commonmark_materialize_repair() must reproduce: |
| 3420 |
# an ordinary, independent repair of body[offset:offset + cut]. |
| 3421 |
abs_cut = offset + cut |
| 3422 |
lookahead = body[abs_cut : abs_cut + lookahead_span] |
| 3423 |
boundary = ( |
| 3424 |
body[abs_cut + lookahead_span : abs_cut + lookahead_span + 1] |
| 3425 |
or None |
| 3426 |
) |
| 3427 |
return commonmark_repair_chunk( |
| 3428 |
body[offset:abs_cut], |
| 3429 |
dict(pending), |
| 3430 |
next_chunk=lookahead or None, |
| 3431 |
next_chunk_boundary_ch=boundary, |
| 3432 |
) |
| 3433 |
|
| 3434 |
# A shared scan answers many different cut lengths from one pass, |
| 3435 |
# matching a direct repair of each individual prefix. |
| 3436 |
body = "**hello** world *and* more" |
| 3437 |
atoms, covered_end, sentinel = commonmark_scan_repair_region( |
| 3438 |
body, {}, lookahead_span |
| 3439 |
) |
| 3440 |
for cut in range(1, len(body) + 1): |
| 3441 |
assert commonmark_materialize_repair( |
| 3442 |
body, 0, cut, {}, atoms, covered_end, sentinel, lookahead_span |
| 3443 |
) == _direct(body, 0, cut, {}) |
| 3444 |
|
| 3445 |
# A cut inside a complete code span uses direct repair because the recorded |
| 3446 |
# section cannot be safely reused in part. |
| 3447 |
body = "text `code span` tail" |
| 3448 |
atoms, covered_end, sentinel = commonmark_scan_repair_region( |
| 3449 |
body, {}, lookahead_span |
| 3450 |
) |
| 3451 |
cut = body.index("code") + 2 # inside the backtick span |
| 3452 |
assert commonmark_materialize_repair( |
| 3453 |
body, 0, cut, {}, atoms, covered_end, sentinel, lookahead_span |
| 3454 |
) == _direct(body, 0, cut, {}) |
| 3455 |
|
| 3456 |
# An empty prefix can still clear carried state, so it uses direct repair. |
| 3457 |
body = ")rest of the body" |
| 3458 |
pending = {"in_link_dest": True, "dest_gt": True} |
| 3459 |
atoms, covered_end, sentinel = commonmark_scan_repair_region( |
| 3460 |
body, dict(pending), lookahead_span |
| 3461 |
) |
| 3462 |
assert commonmark_materialize_repair( |
| 3463 |
body, |
| 3464 |
0, |
| 3465 |
0, |
| 3466 |
dict(pending), |
| 3467 |
atoms, |
| 3468 |
covered_end, |
| 3469 |
sentinel, |
| 3470 |
lookahead_span, |
| 3471 |
) == commonmark_repair_chunk("", dict(pending)) |
| 3472 |
|
| 3473 |
# Reused scans must replay a run that only partly clears prior state. |
| 3474 |
body = "****tail" |
| 3475 |
pending = {"**": 1} |
| 3476 |
atoms, covered_end, sentinel = commonmark_scan_repair_region( |
| 3477 |
body, dict(pending), lookahead_span |
| 3478 |
) |
| 3479 |
assert commonmark_materialize_repair( |
| 3480 |
body, |
| 3481 |
0, |
| 3482 |
len(body), |
| 3483 |
dict(pending), |
| 3484 |
atoms, |
| 3485 |
covered_end, |
| 3486 |
sentinel, |
| 3487 |
lookahead_span, |
| 3488 |
) == commonmark_repair_chunk(body, dict(pending)) |
| 3489 |
|
| 3490 |
# A cut beyond the reusable range falls back to direct repair. |
| 3491 |
body = "plain text [link] tail" |
| 3492 |
atoms, covered_end, sentinel = commonmark_scan_repair_region( |
| 3493 |
body, {}, lookahead_span |
| 3494 |
) |
| 3495 |
assert covered_end < len(body) |
| 3496 |
cut = len(body) |
| 3497 |
assert commonmark_materialize_repair( |
| 3498 |
body, 0, cut, {}, atoms, covered_end, sentinel, lookahead_span |
| 3499 |
) == _direct(body, 0, cut, {}) |
| 3500 |
|
| 3501 |
# The shared closing-marker index must match direct lookahead scans. |
| 3502 |
body = "*word" + " " * 20 + "** end" |
| 3503 |
atoms, covered_end, sentinel = commonmark_scan_repair_region( |
| 3504 |
body, {}, lookahead_span |
| 3505 |
) |
| 3506 |
closer_index, closer_covered_end = commonmark_scan_closer_runs(body) |
| 3507 |
for cut in range(1, len(body) - lookahead_span + 1): |
| 3508 |
assert commonmark_materialize_repair( |
| 3509 |
body, |
| 3510 |
0, |
| 3511 |
cut, |
| 3512 |
{}, |
| 3513 |
atoms, |
| 3514 |
covered_end, |
| 3515 |
sentinel, |
| 3516 |
lookahead_span, |
| 3517 |
closer_index=closer_index, |
| 3518 |
closer_covered_end=closer_covered_end, |
| 3519 |
) == _direct(body, 0, cut, {}) |
| 3520 |
|
| 3521 |
# A lookahead boundary inside a marker run must use direct repair because |
| 3522 |
# the shortened run may be classified differently. Put it at the far edge |
| 3523 |
# to exercise the closing-marker index rather than the main section scan. |
| 3524 |
closer_lookahead_span = 8 |
| 3525 |
cut = 2 |
| 3526 |
body = "ab" + "c" * 7 + "***" + "d" * 60 |
| 3527 |
atoms, covered_end, sentinel = commonmark_scan_repair_region( |
| 3528 |
body, {}, closer_lookahead_span |
| 3529 |
) |
| 3530 |
closer_index, closer_covered_end = commonmark_scan_closer_runs(body) |
| 3531 |
assert commonmark_materialize_repair( |
| 3532 |
body, |
| 3533 |
0, |
| 3534 |
cut, |
| 3535 |
{}, |
| 3536 |
atoms, |
| 3537 |
covered_end, |
| 3538 |
sentinel, |
| 3539 |
closer_lookahead_span, |
| 3540 |
closer_index=closer_index, |
| 3541 |
closer_covered_end=closer_covered_end, |
| 3542 |
) == _direct(body, 0, cut, {}, lookahead_span=closer_lookahead_span) |
| 3543 |
|
| 3544 |
|
| 3545 |
def test_conversion_commonmark_repair_chunk_record_atoms_link_labels(): |
| 3546 |
"""record_atoms must cover a resolved "[" with no gap, in every way |
| 3547 |
a link label can be resolved within one chunk.""" |
| 3548 |
|
| 3549 |
def _assert_gapless(text, pending=None): |
| 3550 |
# Every recorded atom's start must equal the previous atom's end, |
| 3551 |
# beginning at 0 and reaching the end of the input text, so a |
| 3552 |
# caller replaying these atoms never has to guess at a skipped |
| 3553 |
# span (the exact invariant commonmark_materialize_repair() relies |
| 3554 |
# on for cutting a shorter prefix from reusable sections). |
| 3555 |
atoms = [] |
| 3556 |
commonmark_repair_chunk(text, dict(pending or {}), record_atoms=atoms) |
| 3557 |
assert atoms, "expected at least one recorded atom" |
| 3558 |
assert atoms[0][0] == 0 |
| 3559 |
for prev_atom, next_atom in zip(atoms, atoms[1:]): |
| 3560 |
assert prev_atom[1] == next_atom[0], (prev_atom, next_atom) |
| 3561 |
assert atoms[-1][1] == len(text) |
| 3562 |
return atoms |
| 3563 |
|
| 3564 |
# A link label that resolves successfully within the same chunk, via |
| 3565 |
# both the angle-bracket and bare-paren destination forms. |
| 3566 |
_assert_gapless("prefix [label](<https://example.com>) suffix") |
| 3567 |
_assert_gapless("prefix [label](https://example.com) suffix") |
| 3568 |
|
| 3569 |
# A label whose destination fails to parse (falls back to escaped |
| 3570 |
# literal text) still leaves the "[" itself covered. |
| 3571 |
_assert_gapless("prefix [label](has space) suffix") |
| 3572 |
|
| 3573 |
# A label that never reaches "](" at all in this chunk -- resolved |
| 3574 |
# only by the end-of-scan force-escape cleanup. |
| 3575 |
_assert_gapless("prefix [never closes") |
| 3576 |
|
| 3577 |
# Multiple pending labels, only some of which ever see a "](" attempt, |
| 3578 |
# so both the mid-scan and end-of-scan resolution paths fire together. |
| 3579 |
_assert_gapless("[outer [inner](<bad text](https://example.com)") |
| 3580 |
|
| 3581 |
# A label carried in from a previous chunk plus a fresh one that |
| 3582 |
# resolves normally. |
| 3583 |
_assert_gapless( |
| 3584 |
"dest>) more [fresh](https://example.com)", |
| 3585 |
pending={"in_link_dest": True}, |
| 3586 |
) |
| 3587 |
|
| 3588 |
# The atoms replay to the same text commonmark_repair_chunk() produces |
| 3589 |
# directly, for a body whose sole link resolves within the chunk (so |
| 3590 |
# the recorded region spans the whole body, matching what a caller |
| 3591 |
# bypassing commonmark_scan_repair_region()'s conservative |
| 3592 |
# before-the-first-"[" truncation would now be able to reuse). |
| 3593 |
body = "[label](https://example.com) tail" |
| 3594 |
atoms = [] |
| 3595 |
direct_result, _ = commonmark_repair_chunk(body, {}, record_atoms=atoms) |
| 3596 |
sentinel = commonmark_pick_emphasis_sentinel(body) |
| 3597 |
materialized_result, _ = commonmark_materialize_repair( |
| 3598 |
body, 0, len(body), {}, atoms, len(body), sentinel, 64 |
| 3599 |
) |
| 3600 |
assert materialized_result == direct_result |
| 3601 |
|
| 3602 |
|
| 3603 |
def test_conversion_split_dialect_chunk(): |
| 3604 |
"""conversion: Test split_dialect_chunk()""" |
| 3605 |
|
| 3606 |
def identity(body): |
| 3607 |
# Nothing to escape, so a single piece is returned untouched |
| 3608 |
# whenever it already fits. |
| 3609 |
return body |
| 3610 |
|
| 3611 |
assert split_dialect_chunk("", 10, identity) == [""] |
| 3612 |
assert split_dialect_chunk("hello", 10, identity) == ["hello"] |
| 3613 |
|
| 3614 |
def double(body): |
| 3615 |
# Doubles every character (worst-case backslash escaping). |
| 3616 |
return "".join(f"{c}{c}" for c in body) |
| 3617 |
|
| 3618 |
# Conversion growth splits the source without dropping content. |
| 3619 |
pieces = split_dialect_chunk("." * 10, 8, double) |
| 3620 |
assert len(pieces) > 1 |
| 3621 |
for piece in pieces: |
| 3622 |
assert len(piece) <= 8 |
| 3623 |
# Reversing the test conversion reconstructs the original source. |
| 3624 |
assert "".join(piece[::2] for piece in pieces) == "." * 10 |
| 3625 |
|
| 3626 |
# Emit one oversized character when necessary to guarantee progress. |
| 3627 |
pieces = split_dialect_chunk("ab", 1, double) |
| 3628 |
assert pieces == ["aa", "bb"] |
| 3629 |
|
| 3630 |
def escape_dots(body): |
| 3631 |
# Mimic a dialect whose escaping requires a second split. |
| 3632 |
return body.replace(".", "\\.") |
| 3633 |
|
| 3634 |
# Carry forced-closed bold state so the later real closer is consumed. |
| 3635 |
body = "**" + "a.b.c." * 6 + "**" + " tail" |
| 3636 |
pieces = split_dialect_chunk(body, 20, escape_dots) |
| 3637 |
assert len(pieces) > 1 |
| 3638 |
joined = "".join(pieces) |
| 3639 |
assert joined.count("**") == 2 |
| 3640 |
|
| 3641 |
def strip_x(body): |
| 3642 |
# Make every ten source characters produce one output character. |
| 3643 |
return body.replace("x", "") |
| 3644 |
|
| 3645 |
body = "xxxxxxxxxa" * 100 |
| 3646 |
pieces = split_dialect_chunk(body, 10, strip_x) |
| 3647 |
assert len(pieces) == 10 |
| 3648 |
assert all(piece == "a" * 10 for piece in pieces) |
| 3649 |
|
| 3650 |
# A large body with a small limit should remain linear and preserve text. |
| 3651 |
n = 200000 |
| 3652 |
body = "hello world " * (n // 12) |
| 3653 |
start = default_timer() |
| 3654 |
pieces = split_dialect_chunk(body, 100, identity) |
| 3655 |
elapsed = default_timer() - start |
| 3656 |
assert "".join(pieces) == body |
| 3657 |
# Generous bound -- see the note on the equivalent check above. |
| 3658 |
assert elapsed < 90.0 |
| 3659 |
|
| 3660 |
# Many dangling openers share one scan and remain escaped literals. |
| 3661 |
many_openers = " *a" * 5000 |
| 3662 |
huge_tail = "x" * 2000000 |
| 3663 |
start = default_timer() |
| 3664 |
text, pending = commonmark_repair_chunk( |
| 3665 |
many_openers, {}, next_chunk=huge_tail |
| 3666 |
) |
| 3667 |
elapsed = default_timer() - start |
| 3668 |
assert text == " \\*a" * 5000 |
| 3669 |
assert pending == {} |
| 3670 |
# Generous bound -- see the note on the equivalent check above. |
| 3671 |
assert elapsed < 40.0 |
| 3672 |
|
| 3673 |
# Ignore a closer beyond bounded lookahead, matching a full repair pass. |
| 3674 |
body = "_abc" + ("x" * 32) + "_word" |
| 3675 |
pieces = split_dialect_chunk(body, 4, identity) |
| 3676 |
assert "".join(pieces) == "\\_abc" + ("x" * 32) + "\\_word" |
| 3677 |
|
| 3678 |
# A tiny limit must preserve opening bold markers without blank pieces. |
| 3679 |
pieces = split_dialect_chunk("**abc**", 4, identity) |
| 3680 |
assert "" not in pieces |
| 3681 |
assert pieces == ["****", "abc"] |
| 3682 |
|
| 3683 |
# Repeat dangling openers to verify bounded correction remains accurate |
| 3684 |
# and fast across many pieces. |
| 3685 |
unit = "_abc" + ("x" * 32) + "_word " |
| 3686 |
body = unit * 2000 |
| 3687 |
start = default_timer() |
| 3688 |
pieces = split_dialect_chunk(body, 50, identity) |
| 3689 |
elapsed = default_timer() - start |
| 3690 |
assert "".join(pieces) == body.replace("_", "\\_") |
| 3691 |
# Generous bound -- see the note on the equivalent check above. |
| 3692 |
assert elapsed < 90.0 |
| 3693 |
|
| 3694 |
# A longer repaired prefix can fit after an earlier one overflows. |
| 3695 |
# Verify the discarded bisection range with a real dialect conversion. |
| 3696 |
body = ( |
| 3697 |
"|\t-(|::+<_\ta(*&__][]:\t>{)] =#= \t.(\\-[){~]+-]{{#=_\\>)-{\t#>[*_" |
| 3698 |
) |
| 3699 |
pieces = split_dialect_chunk( |
| 3700 |
body, 22, NotifyGoogleChat._commonmark_to_google_chat |
| 3701 |
) |
| 3702 |
assert pieces[0] == "|\t-(|::+<\\_\ta(_&_" |
| 3703 |
assert len(pieces[0]) == 21 |
| 3704 |
|
| 3705 |
# A repaired prefix may fit just above the result found by bisection. |
| 3706 |
# Checking upward catches it without crossing the entire failed range. |
| 3707 |
body = "*)\\\\`<*(>([*] \\>_]`\\>(]*`))_`_ \\]`[.<*_*<*<]>.>\\a)], _ <a" |
| 3708 |
pieces = split_dialect_chunk(body, 29, NotifySlack._commonmark_to_slack) |
| 3709 |
assert len(pieces[0]) <= 29 |
| 3710 |
reconstructed_len = 19 # confirmed via exhaustive brute-force search |
| 3711 |
repaired, _ = commonmark_repair_chunk( |
| 3712 |
body[:reconstructed_len], {}, next_chunk=body[reconstructed_len:] |
| 3713 |
) |
| 3714 |
assert pieces[0] == NotifySlack._commonmark_to_slack(repaired) |
| 3715 |
|
| 3716 |
# A repaired prefix may also fit near the far end of the checked range. |
| 3717 |
body = "*(`<]<[xxxxxxxxxxxx`<xxxxxxxxxx_]" |
| 3718 |
|
| 3719 |
def strip_x(text): |
| 3720 |
# Simulate a converter that removes a long run so the result fits. |
| 3721 |
return text.replace("x", "") |
| 3722 |
|
| 3723 |
pieces = split_dialect_chunk(body, 10, strip_x) |
| 3724 |
assert pieces == ["\\*(`<]<[`<", "\\_]"] |
| 3725 |
assert "".join(pieces).replace("x", "") == "".join(pieces) |
| 3726 |
|
| 3727 |
# Many unmatched ``*`` markers must scale with input size. The generous |
| 3728 |
# limit allows slow test hosts while still catching severe regressions. |
| 3729 |
n = 20000 |
| 3730 |
body = ("*a " * (n // 3))[:n] |
| 3731 |
start = default_timer() |
| 3732 |
pieces = split_dialect_chunk(body, 160, identity) |
| 3733 |
elapsed = default_timer() - start |
| 3734 |
assert "".join(pieces) == body.replace("*", "\\*") |
| 3735 |
assert elapsed < 45.0 |
| 3736 |
|
| 3737 |
# Exercise one real Slack-sized split and the shared repair path. |
| 3738 |
slack_body = ("*a " * ((80000 + 2) // 3))[:80000] |
| 3739 |
start = default_timer() |
| 3740 |
split_dialect_chunk(slack_body, 35000, NotifySlack._commonmark_to_slack) |
| 3741 |
elapsed = default_timer() - start |
| 3742 |
|
| 3743 |
# Generous bound -- see the note on the equivalent check above. |
| 3744 |
assert elapsed < 90.0 |
| 3745 |
|
| 3746 |
# Confirm the cost does not grow with the square of the body. |
| 3747 |
small_n = 4000 |
| 3748 |
large_n = 16000 |
| 3749 |
small_body = ("*a " * ((small_n + 2) // 3))[:small_n] |
| 3750 |
large_body = ("*a " * ((large_n + 2) // 3))[:large_n] |
| 3751 |
|
| 3752 |
# Interleave two rounds and keep each size's fastest result to reduce |
| 3753 |
# timing noise. |
| 3754 |
small_time = large_time = None |
| 3755 |
for _ in range(2): |
| 3756 |
start = default_timer() |
| 3757 |
split_dialect_chunk(small_body, 200, NotifySlack._commonmark_to_slack) |
| 3758 |
elapsed = default_timer() - start |
| 3759 |
small_time = ( |
| 3760 |
elapsed if small_time is None else min(small_time, elapsed) |
| 3761 |
) |
| 3762 |
|
| 3763 |
start = default_timer() |
| 3764 |
split_dialect_chunk(large_body, 200, NotifySlack._commonmark_to_slack) |
| 3765 |
elapsed = default_timer() - start |
| 3766 |
large_time = ( |
| 3767 |
elapsed if large_time is None else min(large_time, elapsed) |
| 3768 |
) |
| 3769 |
|
| 3770 |
# Quadrupling the body must stay far below the square of the cost. |
| 3771 |
assert large_time < small_time * 8.0 + 1.0 |
| 3772 |
|
| 3773 |
|
| 3774 |
def test_conversion_split_keeps_only_first_empty_piece(): |
| 3775 |
"""conversion: retain one empty piece but skip later empty pieces""" |
| 3776 |
|
| 3777 |
with mock.patch( |
| 3778 |
"apprise.conversion.dialect._longest_fitting_prefix", |
| 3779 |
side_effect=[("", 1, {}), ("", 1, {})], |
| 3780 |
): |
| 3781 |
pieces = split_dialect_chunk("ab", 1, lambda text: text) |
| 3782 |
|
| 3783 |
assert pieces == [""] |
| 3784 |
|
| 3785 |
|
| 3786 |
def test_conversion_truncate_dialect_chunk(): |
| 3787 |
"""conversion: Test truncate_dialect_chunk()""" |
| 3788 |
|
| 3789 |
def identity(body): |
| 3790 |
return body |
| 3791 |
|
| 3792 |
# An empty body has nothing to convert or truncate. |
| 3793 |
assert truncate_dialect_chunk("", 10, identity) == "" |
| 3794 |
|
| 3795 |
# A body that already fits after conversion is returned whole. |
| 3796 |
assert truncate_dialect_chunk("hello", 10, identity) == "hello" |
| 3797 |
|
| 3798 |
def double(body): |
| 3799 |
# Doubles every character (worst-case backslash escaping). |
| 3800 |
return "".join(f"{c}{c}" for c in body) |
| 3801 |
|
| 3802 |
# Truncation keeps only the longest converted prefix that fits. |
| 3803 |
piece = truncate_dialect_chunk("." * 10, 8, double) |
| 3804 |
assert len(piece) <= 8 |
| 3805 |
assert piece == ".." * 4 |
| 3806 |
|
| 3807 |
# Return one oversized character rather than making no progress. |
| 3808 |
assert truncate_dialect_chunk("ab", 1, double) == "aa" |
| 3809 |
|
| 3810 |
def strip_x(body): |
| 3811 |
# Make every source block contribute one output character. |
| 3812 |
return body.replace("x", "") |
| 3813 |
|
| 3814 |
# Continue searching beyond a fixed limit-derived window. |
| 3815 |
body = "xxxxxxxxxa" * 100 |
| 3816 |
piece = truncate_dialect_chunk(body, 10, strip_x) |
| 3817 |
assert piece == "a" * 10 |
| 3818 |
|
| 3819 |
|
| 3820 |
def test_conversion_commonmark_scan_delimiter_run(): |
| 3821 |
"""conversion: Test commonmark_scan_delimiter_run()""" |
| 3822 |
|
| 3823 |
# Middle runs read both neighbors directly. |
| 3824 |
assert commonmark_scan_delimiter_run("a**b", 1) == (3, "a", "b") |
| 3825 |
|
| 3826 |
# A starting run uses the optional preceding boundary. |
| 3827 |
assert commonmark_scan_delimiter_run("*a", 0) == (1, None, "a") |
| 3828 |
assert commonmark_scan_delimiter_run("*a", 0, boundary_prev_ch="x") == ( |
| 3829 |
1, |
| 3830 |
"x", |
| 3831 |
"a", |
| 3832 |
) |
| 3833 |
|
| 3834 |
# An ending run uses the optional following boundary. |
| 3835 |
assert commonmark_scan_delimiter_run("a*", 1) == (2, "a", None) |
| 3836 |
assert commonmark_scan_delimiter_run("a*", 1, boundary_next_ch="y") == ( |
| 3837 |
2, |
| 3838 |
"a", |
| 3839 |
"y", |
| 3840 |
) |
| 3841 |
|
| 3842 |
# Both boundaries can apply at once to a run that is the entire text. |
| 3843 |
assert commonmark_scan_delimiter_run( |
| 3844 |
"**", 0, boundary_prev_ch="x", boundary_next_ch="y" |
| 3845 |
) == (2, "x", "y") |
| 3846 |
|
| 3847 |
# Underscore runs measure the same way as asterisk runs. |
| 3848 |
assert commonmark_scan_delimiter_run("a___b", 1) == (4, "a", "b") |
| 3849 |
|
| 3850 |
|
| 3851 |
def test_conversion_commonmark_can_open_close_emphasis(): |
| 3852 |
"""conversion: Test commonmark_can_open_emphasis()/ |
| 3853 |
commonmark_can_close_emphasis()""" |
| 3854 |
|
| 3855 |
# A run at the very start of the text, followed by real content, |
| 3856 |
# is left-flanking only: it can open but not close. |
| 3857 |
assert commonmark_can_open_emphasis("*", None, "f") is True |
| 3858 |
assert commonmark_can_close_emphasis("*", None, "f") is False |
| 3859 |
|
| 3860 |
# A run at the very end, preceded by real content, is |
| 3861 |
# right-flanking only: it can close but not open. |
| 3862 |
assert commonmark_can_open_emphasis("*", "o", None) is False |
| 3863 |
assert commonmark_can_close_emphasis("*", "o", None) is True |
| 3864 |
|
| 3865 |
# A run with real content on both sides can do either, for "*". |
| 3866 |
assert commonmark_can_open_emphasis("*", "o", "b") is True |
| 3867 |
assert commonmark_can_close_emphasis("*", "o", "b") is True |
| 3868 |
|
| 3869 |
# "_" carries an extra intraword restriction "*" does not: a run |
| 3870 |
# flanked by real content on both sides is both left- and |
| 3871 |
# right-flanking at once, which underscore is never allowed to |
| 3872 |
# open or close with, so it is left as literal text instead. |
| 3873 |
assert commonmark_can_open_emphasis("_", "o", "b") is False |
| 3874 |
assert commonmark_can_close_emphasis("_", "o", "b") is False |
| 3875 |
|
| 3876 |
|
| 3877 |
def test_conversion_commonmark_pick_emphasis_sentinel(): |
| 3878 |
"""conversion: Test commonmark_pick_emphasis_sentinel()""" |
| 3879 |
|
| 3880 |
# An ordinary body with no Private Use Area characters at all |
| 3881 |
# picks a single one, the narrowest candidate available. |
| 3882 |
assert commonmark_pick_emphasis_sentinel("hello world") == chr(0xE000) |
| 3883 |
|
| 3884 |
# Existing candidates make the sentinel double until it is unique. |
| 3885 |
assert commonmark_pick_emphasis_sentinel(chr(0xE000)) == chr(0xE000) * 2 |
| 3886 |
assert commonmark_pick_emphasis_sentinel(chr(0xE000) * 3) == ( |
| 3887 |
chr(0xE000) * 4 |
| 3888 |
) |
| 3889 |
|
| 3890 |
# Doubling also handles long collision runs efficiently. |
| 3891 |
picked = commonmark_pick_emphasis_sentinel(chr(0xE000) * 100000) |
| 3892 |
assert picked not in chr(0xE000) * 100000 |
| 3893 |
assert len(picked) == 131072 |
| 3894 |
|
| 3895 |
# Sentinel selection remains deterministic for the same input. |
| 3896 |
assert commonmark_pick_emphasis_sentinel( |
| 3897 |
"hello world" |
| 3898 |
) == commonmark_pick_emphasis_sentinel("hello world") |
| 3899 |
|
| 3900 |
|
| 3901 |
def test_conversion_commonmark_emphasis_sentinel_collision(): |
| 3902 |
"""Preserve user text shaped like an internal emphasis placeholder.""" |
| 3903 |
# Build the former hard-coded placeholder without embedding invisible text. |
| 3904 |
marker = chr(0xE000) |
| 3905 |
attack = f"before {marker}0{marker} after" |
| 3906 |
|
| 3907 |
out = [] |
| 3908 |
delimiters = [] |
| 3909 |
i = 0 |
| 3910 |
n = len(attack) |
| 3911 |
sentinel = commonmark_pick_emphasis_sentinel(attack) |
| 3912 |
while i < n: |
| 3913 |
if attack[i] == "*": |
| 3914 |
i = commonmark_emphasis_run( |
| 3915 |
attack, i, n, delimiters, out, sentinel |
| 3916 |
) |
| 3917 |
continue |
| 3918 |
out.append(attack[i]) |
| 3919 |
i += 1 |
| 3920 |
rendered = commonmark_render_emphasis_markers( |
| 3921 |
"".join(out), delimiters, ("*", "*"), ("_", "_"), sentinel |
| 3922 |
) |
| 3923 |
|
| 3924 |
# No real emphasis was present, so the attempted collision passes |
| 3925 |
# straight through untouched rather than raising or corrupting. |
| 3926 |
assert rendered == attack |
| 3927 |
|
| 3928 |
|
| 3929 |
def test_conversion_commonmark_emphasis_run(): |
| 3930 |
"""conversion: Test commonmark_emphasis_run()""" |
| 3931 |
|
| 3932 |
def convert(body): |
| 3933 |
# Collect, resolve, and render runs like the dialect adapters. |
| 3934 |
out = [] |
| 3935 |
delimiters = [] |
| 3936 |
i = 0 |
| 3937 |
n = len(body) |
| 3938 |
sentinel = commonmark_pick_emphasis_sentinel(body) |
| 3939 |
while i < n: |
| 3940 |
if body[i] == "*": |
| 3941 |
i = commonmark_emphasis_run( |
| 3942 |
body, i, n, delimiters, out, sentinel |
| 3943 |
) |
| 3944 |
continue |
| 3945 |
out.append(body[i]) |
| 3946 |
i += 1 |
| 3947 |
return commonmark_render_emphasis_markers( |
| 3948 |
"".join(out), delimiters, ("*", "*"), ("_", "_"), sentinel |
| 3949 |
) |
| 3950 |
|
| 3951 |
# Preserve an opener with no closer. |
| 3952 |
assert convert("****a") == "****a" |
| 3953 |
|
| 3954 |
# Keep the ambiguous middle run literal under the modulo-three rule. |
| 3955 |
assert convert("*foo**bar*") == "_foo**bar_" |
| 3956 |
|
| 3957 |
# Split one closing run across two nested regular spans. |
| 3958 |
assert convert("*foo *bar**") == "_foo _bar__" |
| 3959 |
|
| 3960 |
# Split a width-three opener between regular and strong emphasis. |
| 3961 |
assert convert("***foo* bar**") == "*_foo_ bar*" |
| 3962 |
|
| 3963 |
assert convert("*a*") == "_a_" |
| 3964 |
assert convert("**a**") == "*a*" |
| 3965 |
|
| 3966 |
# A single run wide enough to supply both kinds of emphasis nests |
| 3967 |
# regular emphasis outermost and bold innermost. |
| 3968 |
assert convert("***a***") == "_*a*_" |
| 3969 |
|
| 3970 |
|
| 3971 |
def test_conversion_commonmark_match_emphasis(): |
| 3972 |
"""conversion: Test commonmark_match_emphasis()""" |
| 3973 |
|
| 3974 |
def descriptor(char, numdelims, can_open, can_close): |
| 3975 |
return { |
| 3976 |
"char": char, |
| 3977 |
"numdelims": numdelims, |
| 3978 |
"origdelims": numdelims, |
| 3979 |
"can_open": can_open, |
| 3980 |
"can_close": can_close, |
| 3981 |
"events": [], |
| 3982 |
} |
| 3983 |
|
| 3984 |
# Match the outer pair while leaving an ambiguous middle run literal. |
| 3985 |
delimiters = [ |
| 3986 |
descriptor("*", 1, True, False), |
| 3987 |
descriptor("*", 2, True, True), |
| 3988 |
descriptor("*", 1, False, True), |
| 3989 |
] |
| 3990 |
commonmark_match_emphasis(delimiters) |
| 3991 |
assert delimiters[0]["numdelims"] == 0 |
| 3992 |
assert delimiters[0]["events"] == [("open", False)] |
| 3993 |
assert delimiters[1]["numdelims"] == 2 |
| 3994 |
assert delimiters[1]["events"] == [] |
| 3995 |
assert delimiters[2]["numdelims"] == 0 |
| 3996 |
assert delimiters[2]["events"] == [("close", False)] |
| 3997 |
|
| 3998 |
# A run wide enough to open both regular and strong emphasis |
| 3999 |
# records both events against a matching closer run, strong first. |
| 4000 |
delimiters = [ |
| 4001 |
descriptor("*", 3, True, False), |
| 4002 |
descriptor("*", 3, False, True), |
| 4003 |
] |
| 4004 |
commonmark_match_emphasis(delimiters) |
| 4005 |
assert delimiters[0]["numdelims"] == 0 |
| 4006 |
assert delimiters[0]["events"] == [("open", True), ("open", False)] |
| 4007 |
assert delimiters[1]["numdelims"] == 0 |
| 4008 |
assert delimiters[1]["events"] == [("close", True), ("close", False)] |
| 4009 |
|
| 4010 |
# Different characters never close each other, even with matching |
| 4011 |
# widths and flanking on both sides. |
| 4012 |
delimiters = [ |
| 4013 |
descriptor("*", 1, True, False), |
| 4014 |
descriptor("_", 1, False, True), |
| 4015 |
] |
| 4016 |
commonmark_match_emphasis(delimiters) |
| 4017 |
assert delimiters[0]["numdelims"] == 1 |
| 4018 |
assert delimiters[0]["events"] == [] |
| 4019 |
assert delimiters[1]["numdelims"] == 1 |
| 4020 |
assert delimiters[1]["events"] == [] |
| 4021 |
|
| 4022 |
# Compare two adversarial sizes so quadratic matching approaches 4x |
| 4023 |
# growth. The ratio also tolerates slower test hosts. |
| 4024 |
small_n = 6000 |
| 4025 |
large_n = 12000 |
| 4026 |
small_body = ("*a " * small_n) + ("b* " * small_n) |
| 4027 |
large_body = ("*a " * large_n) + ("b* " * large_n) |
| 4028 |
|
| 4029 |
# Interleave several rounds and keep each size's fastest result. This |
| 4030 |
# reduces noise from scheduling, garbage collection, and background load. |
| 4031 |
small_time = large_time = None |
| 4032 |
for _ in range(5): |
| 4033 |
start = default_timer() |
| 4034 |
text, pending = commonmark_repair_chunk(small_body, {}) |
| 4035 |
elapsed = default_timer() - start |
| 4036 |
small_time = ( |
| 4037 |
elapsed if small_time is None else min(small_time, elapsed) |
| 4038 |
) |
| 4039 |
# Every opener has a closer, so the complete message stays unchanged. |
| 4040 |
assert text == small_body |
| 4041 |
assert pending == {} |
| 4042 |
|
| 4043 |
start = default_timer() |
| 4044 |
text, pending = commonmark_repair_chunk(large_body, {}) |
| 4045 |
elapsed = default_timer() - start |
| 4046 |
large_time = ( |
| 4047 |
elapsed if large_time is None else min(large_time, elapsed) |
| 4048 |
) |
| 4049 |
assert text == large_body |
| 4050 |
assert pending == {} |
| 4051 |
|
| 4052 |
# Doubling input should remain near linear; the additive margin covers |
| 4053 |
# timer noise at these short runtimes. |
| 4054 |
assert large_time < small_time * 3.0 + 0.1 |
| 4055 |
|
| 4056 |
|
| 4057 |
def test_conversion_commonmark_render_emphasis_events(): |
| 4058 |
"""conversion: Test commonmark_render_emphasis_events()""" |
| 4059 |
|
| 4060 |
strong = ("<b>", "</b>") |
| 4061 |
regular = ("<i>", "</i>") |
| 4062 |
|
| 4063 |
# No events at all: nothing renders around the leftover text. |
| 4064 |
assert commonmark_render_emphasis_events([], strong, regular) == ( |
| 4065 |
"", |
| 4066 |
"", |
| 4067 |
) |
| 4068 |
|
| 4069 |
# A single open renders on the open side only. |
| 4070 |
assert commonmark_render_emphasis_events( |
| 4071 |
[("open", False)], strong, regular |
| 4072 |
) == ("", "<i>") |
| 4073 |
|
| 4074 |
# A single close renders on the close side only. |
| 4075 |
assert commonmark_render_emphasis_events( |
| 4076 |
[("close", True)], strong, regular |
| 4077 |
) == ("</b>", "") |
| 4078 |
|
| 4079 |
# Two opens render outermost first, since the last one recorded is |
| 4080 |
# the outermost span. |
| 4081 |
assert commonmark_render_emphasis_events( |
| 4082 |
[("open", True), ("open", False)], strong, regular |
| 4083 |
) == ("", "<i><b>") |
| 4084 |
|
| 4085 |
# Two closes render innermost first, in the order they were |
| 4086 |
# recorded. |
| 4087 |
assert commonmark_render_emphasis_events( |
| 4088 |
[("close", True), ("close", False)], strong, regular |
| 4089 |
) == ("</b></i>", "") |