Debian Codegraph @

tests/test_apis.py

raw
1 """
2 Python Markdown
3
4 A Python implementation of John Gruber's Markdown.
5
6 Documentation: https://python-markdown.github.io/
7 GitHub: https://github.com/Python-Markdown/markdown/
8 PyPI: https://pypi.org/project/Markdown/
9
10 Started by Manfred Stienstra (http://www.dwerg.net/).
11 Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
12 Currently maintained by Waylan Limberg (https://github.com/waylan),
13 Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
14
15 Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
16 Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
17 Copyright 2004 Manfred Stienstra (the original version)
18
19 License: BSD (see LICENSE.md for details).
20
21 Python-Markdown Regression Tests
22 ================================
23
24 Tests of the various APIs with the Python Markdown library.
25 """
26
27 import unittest
28 import sys
29 import os
30 import markdown
31 import warnings
32 from markdown.__main__ import parse_options
33 from markdown import inlinepatterns
34 from logging import DEBUG, WARNING, CRITICAL
35 import yaml
36 import tempfile
37 from io import BytesIO, StringIO, TextIOWrapper
38 import xml.etree.ElementTree as etree
39 from xml.etree.ElementTree import ProcessingInstruction
40
41
42 class TestMarkdownBasics(unittest.TestCase):
43 """ Tests basics of the Markdown class. """
44
45 def setUp(self):
46 """ Create instance of Markdown. """
47 self.md = markdown.Markdown()
48
49 def testBlankInput(self):
50 """ Test blank input. """
51 self.assertEqual(self.md.convert(''), '')
52
53 def testWhitespaceOnly(self):
54 """ Test input of only whitespace. """
55 self.assertEqual(self.md.convert(' '), '')
56
57 def testSimpleInput(self):
58 """ Test simple input. """
59 self.assertEqual(self.md.convert('foo'), '<p>foo</p>')
60
61 def testInstanceExtension(self):
62 """ Test Extension loading with a class instance. """
63 from markdown.extensions.footnotes import FootnoteExtension
64 markdown.Markdown(extensions=[FootnoteExtension()])
65
66 def testEntryPointExtension(self):
67 """ Test Extension loading with an entry point. """
68 markdown.Markdown(extensions=['footnotes'])
69
70 def testDotNotationExtension(self):
71 """ Test Extension loading with Name (`path.to.module`). """
72 markdown.Markdown(extensions=['markdown.extensions.footnotes'])
73
74 def testDotNotationExtensionWithClass(self):
75 """ Test Extension loading with class name (`path.to.module:Class`). """
76 markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension'])
77
78
79 class TestConvertFile(unittest.TestCase):
80 """ Tests of ConvertFile. """
81
82 def setUp(self):
83 self.saved = sys.stdin, sys.stdout
84 sys.stdin = StringIO('foo')
85 sys.stdout = TextIOWrapper(BytesIO())
86
87 def tearDown(self):
88 sys.stdin, sys.stdout = self.saved
89
90 def getTempFiles(self, src):
91 """ Return the file names for two temp files. """
92 infd, infile = tempfile.mkstemp(suffix='.txt')
93 with os.fdopen(infd, 'w') as fp:
94 fp.write(src)
95 outfd, outfile = tempfile.mkstemp(suffix='.html')
96 return infile, outfile, outfd
97
98 def testFileNames(self):
99 infile, outfile, outfd = self.getTempFiles('foo')
100 markdown.markdownFromFile(input=infile, output=outfile)
101 with os.fdopen(outfd, 'r') as fp:
102 output = fp.read()
103 self.assertEqual(output, '<p>foo</p>')
104
105 def testFileObjects(self):
106 infile = BytesIO(bytes('foo', encoding='utf-8'))
107 outfile = BytesIO()
108 markdown.markdownFromFile(input=infile, output=outfile)
109 outfile.seek(0)
110 self.assertEqual(outfile.read().decode('utf-8'), '<p>foo</p>')
111
112 def testStdinStdout(self):
113 markdown.markdownFromFile()
114 sys.stdout.seek(0)
115 self.assertEqual(sys.stdout.read(), '<p>foo</p>')
116
117
118 class TestBlockParser(unittest.TestCase):
119 """ Tests of the BlockParser class. """
120
121 def setUp(self):
122 """ Create instance of BlockParser. """
123 self.parser = markdown.Markdown().parser
124
125 def testParseChunk(self):
126 """ Test `BlockParser.parseChunk`. """
127 root = etree.Element("div")
128 text = 'foo'
129 self.parser.parseChunk(root, text)
130 self.assertEqual(
131 markdown.serializers.to_xhtml_string(root),
132 "<div><p>foo</p></div>"
133 )
134
135 def testParseDocument(self):
136 """ Test `BlockParser.parseDocument`. """
137 lines = ['#foo', '', 'bar', '', ' baz']
138 tree = self.parser.parseDocument(lines)
139 self.assertIsInstance(tree, etree.ElementTree)
140 self.assertIs(etree.iselement(tree.getroot()), True)
141 self.assertEqual(
142 markdown.serializers.to_xhtml_string(tree.getroot()),
143 "<div><h1>foo</h1><p>bar</p><pre><code>baz\n</code></pre></div>"
144 )
145
146
147 class TestBlockParserState(unittest.TestCase):
148 """ Tests of the State class for `BlockParser`. """
149
150 def setUp(self):
151 self.state = markdown.blockparser.State()
152
153 def testBlankState(self):
154 """ Test State when empty. """
155 self.assertEqual(self.state, [])
156
157 def testSetSate(self):
158 """ Test State.set(). """
159 self.state.set('a_state')
160 self.assertEqual(self.state, ['a_state'])
161 self.state.set('state2')
162 self.assertEqual(self.state, ['a_state', 'state2'])
163
164 def testIsSate(self):
165 """ Test `State.isstate()`. """
166 self.assertEqual(self.state.isstate('anything'), False)
167 self.state.set('a_state')
168 self.assertEqual(self.state.isstate('a_state'), True)
169 self.state.set('state2')
170 self.assertEqual(self.state.isstate('state2'), True)
171 self.assertEqual(self.state.isstate('a_state'), False)
172 self.assertEqual(self.state.isstate('missing'), False)
173
174 def testReset(self):
175 """ Test `State.reset()`. """
176 self.state.set('a_state')
177 self.state.reset()
178 self.assertEqual(self.state, [])
179 self.state.set('state1')
180 self.state.set('state2')
181 self.state.reset()
182 self.assertEqual(self.state, ['state1'])
183
184
185 class TestHtmlStash(unittest.TestCase):
186 """ Test Markdown's `HtmlStash`. """
187
188 def setUp(self):
189 self.stash = markdown.util.HtmlStash()
190 self.placeholder = self.stash.store('foo')
191
192 def testSimpleStore(self):
193 """ Test `HtmlStash.store`. """
194 self.assertEqual(self.placeholder, self.stash.get_placeholder(0))
195 self.assertEqual(self.stash.html_counter, 1)
196 self.assertEqual(self.stash.rawHtmlBlocks, ['foo'])
197
198 def testStoreMore(self):
199 """ Test `HtmlStash.store` with additional blocks. """
200 placeholder = self.stash.store('bar')
201 self.assertEqual(placeholder, self.stash.get_placeholder(1))
202 self.assertEqual(self.stash.html_counter, 2)
203 self.assertEqual(
204 self.stash.rawHtmlBlocks,
205 ['foo', 'bar']
206 )
207
208 def testReset(self):
209 """ Test `HtmlStash.reset`. """
210 self.stash.reset()
211 self.assertEqual(self.stash.html_counter, 0)
212 self.assertEqual(self.stash.rawHtmlBlocks, [])
213
214
215 class Item:
216 """ A dummy `Registry` item object for testing. """
217 def __init__(self, data):
218 self.data = data
219
220 def __repr__(self):
221 return repr(self.data)
222
223 def __eq__(self, other):
224 return self.data == other
225
226
227 class RegistryTests(unittest.TestCase):
228 """ Test the processor registry. """
229
230 def testCreateRegistry(self):
231 r = markdown.util.Registry()
232 r.register(Item('a'), 'a', 20)
233 self.assertEqual(len(r), 1)
234 self.assertIsInstance(r, markdown.util.Registry)
235
236 def testRegisterWithoutPriority(self):
237 r = markdown.util.Registry()
238 with self.assertRaises(TypeError):
239 r.register(Item('a'))
240
241 def testSortRegistry(self):
242 r = markdown.util.Registry()
243 r.register(Item('a'), 'a', 20)
244 r.register(Item('b'), 'b', 21)
245 r.register(Item('c'), 'c', 20.5)
246 self.assertEqual(len(r), 3)
247 self.assertEqual(list(r), ['b', 'c', 'a'])
248
249 def testIsSorted(self):
250 r = markdown.util.Registry()
251 self.assertIs(r._is_sorted, False)
252 r.register(Item('a'), 'a', 20)
253 list(r)
254 self.assertIs(r._is_sorted, True)
255 r.register(Item('b'), 'b', 21)
256 self.assertIs(r._is_sorted, False)
257 r['a']
258 self.assertIs(r._is_sorted, True)
259 r._is_sorted = False
260 r.get_index_for_name('a')
261 self.assertIs(r._is_sorted, True)
262 r._is_sorted = False
263 repr(r)
264 self.assertIs(r._is_sorted, True)
265
266 def testDeregister(self):
267 r = markdown.util.Registry()
268 r.register(Item('a'), 'a', 20)
269 r.register(Item('b'), 'b', 30)
270 r.register(Item('c'), 'c', 40)
271 self.assertEqual(len(r), 3)
272 r.deregister('b')
273 self.assertEqual(len(r), 2)
274 r.deregister('c', strict=False)
275 self.assertEqual(len(r), 1)
276 # deregister non-existent item with `strict=False`
277 r.deregister('d', strict=False)
278 self.assertEqual(len(r), 1)
279 with self.assertRaises(ValueError):
280 # deregister non-existent item with `strict=True`
281 r.deregister('e')
282 self.assertEqual(list(r), ['a'])
283
284 def testRegistryContains(self):
285 r = markdown.util.Registry()
286 item = Item('a')
287 r.register(item, 'a', 20)
288 self.assertIs('a' in r, True)
289 self.assertIn(item, r)
290 self.assertNotIn('b', r)
291
292 def testRegistryIter(self):
293 r = markdown.util.Registry()
294 r.register(Item('a'), 'a', 20)
295 r.register(Item('b'), 'b', 30)
296 self.assertEqual(list(r), ['b', 'a'])
297
298 def testRegistryGetItemByIndex(self):
299 r = markdown.util.Registry()
300 r.register(Item('a'), 'a', 20)
301 r.register(Item('b'), 'b', 30)
302 self.assertEqual(r[0], 'b')
303 self.assertEqual(r[1], 'a')
304 with self.assertRaises(IndexError):
305 r[3]
306
307 def testRegistryGetItemByItem(self):
308 r = markdown.util.Registry()
309 r.register(Item('a'), 'a', 20)
310 r.register(Item('b'), 'b', 30)
311 self.assertEqual(r['a'], 'a')
312 self.assertEqual(r['b'], 'b')
313 with self.assertRaises(KeyError):
314 r['c']
315
316 def testRegistrySetItem(self):
317 r = markdown.util.Registry()
318 with self.assertRaises(TypeError):
319 r[0] = 'a'
320 with self.assertRaises(TypeError):
321 r['a'] = 'a'
322
323 def testRegistryDelItem(self):
324 r = markdown.util.Registry()
325 r.register(Item('a'), 'a', 20)
326 with self.assertRaises(TypeError):
327 del r[0]
328 with self.assertRaises(TypeError):
329 del r['a']
330
331 def testRegistrySlice(self):
332 r = markdown.util.Registry()
333 r.register(Item('a'), 'a', 20)
334 r.register(Item('b'), 'b', 30)
335 r.register(Item('c'), 'c', 40)
336 slc = r[1:]
337 self.assertEqual(len(slc), 2)
338 self.assertIsInstance(slc, markdown.util.Registry)
339 self.assertEqual(list(slc), ['b', 'a'])
340
341 def testGetIndexForName(self):
342 r = markdown.util.Registry()
343 r.register(Item('a'), 'a', 20)
344 r.register(Item('b'), 'b', 30)
345 self.assertEqual(r.get_index_for_name('a'), 1)
346 self.assertEqual(r.get_index_for_name('b'), 0)
347 with self.assertRaises(ValueError):
348 r.get_index_for_name('c')
349
350 def testRegisterDupplicate(self):
351 r = markdown.util.Registry()
352 r.register(Item('a'), 'a', 20)
353 r.register(Item('b1'), 'b', 10)
354 self.assertEqual(list(r), ['a', 'b1'])
355 self.assertEqual(len(r), 2)
356 r.register(Item('b2'), 'b', 30)
357 self.assertEqual(len(r), 2)
358 self.assertEqual(list(r), ['b2', 'a'])
359
360
361 class TestErrors(unittest.TestCase):
362 """ Test Error Reporting. """
363
364 def setUp(self):
365 # Set warnings to be raised as errors
366 warnings.simplefilter('error')
367
368 def tearDown(self):
369 # Reset warning behavior back to default
370 warnings.simplefilter('default')
371
372 def testBadOutputFormat(self):
373 """ Test failure on bad output_format. """
374 self.assertRaises(KeyError, markdown.Markdown, output_format='invalid')
375
376 def testLoadExtensionFailure(self):
377 """ Test failure of an extension to load. """
378 self.assertRaises(
379 ImportError,
380 markdown.Markdown, extensions=['non_existant_ext']
381 )
382
383 def testLoadBadExtension(self):
384 """ Test loading of an Extension with no makeExtension function. """
385 self.assertRaises(AttributeError, markdown.Markdown, extensions=['markdown.util'])
386
387 def testNonExtension(self):
388 """ Test loading a non Extension object as an extension. """
389 self.assertRaises(TypeError, markdown.Markdown, extensions=[object])
390
391 def testDotNotationExtensionWithBadClass(self):
392 """ Test Extension loading with non-existent class name (`path.to.module:Class`). """
393 self.assertRaises(
394 AttributeError,
395 markdown.Markdown,
396 extensions=['markdown.extensions.footnotes:MissingExtension']
397 )
398
399 def testBaseExtention(self):
400 """ Test that the base Extension class will raise `NotImplemented`. """
401 self.assertRaises(
402 NotImplementedError,
403 markdown.Markdown, extensions=[markdown.extensions.Extension()]
404 )
405
406
407 class testETreeComments(unittest.TestCase):
408 """
409 Test that `ElementTree` Comments work.
410
411 These tests should only be a concern when using `cElementTree` with third
412 party serializers (including markdown's (x)html serializer). While markdown
413 doesn't use `ElementTree.Comment` itself, we should certainly support any
414 third party extensions which may. Therefore, these tests are included to
415 ensure such support is maintained.
416 """
417
418 def setUp(self):
419 # Create comment node
420 self.comment = etree.Comment('foo')
421
422 def testCommentIsComment(self):
423 """ Test that an `ElementTree` `Comment` passes the `is Comment` test. """
424 self.assertIs(self.comment.tag, etree.Comment)
425
426 def testCommentIsBlockLevel(self):
427 """ Test that an `ElementTree` `Comment` is recognized as `BlockLevel`. """
428 md = markdown.Markdown()
429 self.assertIs(md.is_block_level(self.comment.tag), False)
430
431 def testCommentSerialization(self):
432 """ Test that an `ElementTree` `Comment` serializes properly. """
433 self.assertEqual(
434 markdown.serializers.to_html_string(self.comment),
435 '<!--foo-->'
436 )
437
438 def testCommentPrettify(self):
439 """ Test that an `ElementTree` `Comment` is prettified properly. """
440 pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown())
441 pretty.run(self.comment)
442 self.assertEqual(
443 markdown.serializers.to_html_string(self.comment),
444 '<!--foo-->\n'
445 )
446
447
448 class testElementTailTests(unittest.TestCase):
449 """ Element Tail Tests """
450 def setUp(self):
451 self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown())
452
453 def testBrTailNoNewline(self):
454 """ Test that last `<br>` in tree has a new line tail """
455 root = etree.Element('root')
456 br = etree.SubElement(root, 'br')
457 self.assertEqual(br.tail, None)
458 self.pretty.run(root)
459 self.assertEqual(br.tail, "\n")
460
461
462 class testElementPreCodeTests(unittest.TestCase):
463 """ Element `PreCode` Tests """
464 def setUp(self):
465 md = markdown.Markdown()
466 self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(md)
467
468 def prettify(self, xml):
469 root = etree.fromstring(xml)
470 self.pretty.run(root)
471 return etree.tostring(root, encoding="unicode", short_empty_elements=False)
472
473 def testPreCodeEmpty(self):
474 xml = "<pre><code></code></pre>"
475 expected = "<pre><code></code></pre>\n"
476 self.assertEqual(expected, self.prettify(xml))
477
478 def testPreCodeWithChildren(self):
479 xml = "<pre><code> <span /></code></pre>"
480 expected = "<pre><code> <span></span></code></pre>\n"
481 self.assertEqual(expected, self.prettify(xml))
482
483 def testPreCodeWithSpaceOnly(self):
484 xml = "<pre><code> </code></pre>"
485 expected = "<pre><code>\n</code></pre>\n"
486 self.assertEqual(expected, self.prettify(xml))
487
488 def testPreCodeWithText(self):
489 xml = "<pre><code> hello</code></pre>"
490 expected = "<pre><code> hello\n</code></pre>\n"
491 self.assertEqual(expected, self.prettify(xml))
492
493 def testPreCodeWithTrailingSpace(self):
494 xml = "<pre><code> hello </code></pre>"
495 expected = "<pre><code> hello\n</code></pre>\n"
496 self.assertEqual(expected, self.prettify(xml))
497
498
499 class testSerializers(unittest.TestCase):
500 """ Test the html and xhtml serializers. """
501
502 def testHtml(self):
503 """ Test HTML serialization. """
504 el = etree.Element('div')
505 el.set('id', 'foo<&">')
506 p = etree.SubElement(el, 'p')
507 p.text = 'foo <&escaped>'
508 p.set('hidden', 'hidden')
509 etree.SubElement(el, 'hr')
510 non_element = etree.SubElement(el, None)
511 non_element.text = 'non-element text'
512 script = etree.SubElement(non_element, 'script')
513 script.text = '<&"test\nescaping">'
514 el.tail = "tail text"
515 self.assertEqual(
516 markdown.serializers.to_html_string(el),
517 '<div id="foo&lt;&amp;&quot;&gt;">'
518 '<p hidden>foo &lt;&amp;escaped&gt;</p>'
519 '<hr>'
520 'non-element text'
521 '<script><&"test\nescaping"></script>'
522 '</div>tail text'
523 )
524
525 def testXhtml(self):
526 """" Test XHTML serialization. """
527 el = etree.Element('div')
528 el.set('id', 'foo<&">')
529 p = etree.SubElement(el, 'p')
530 p.text = 'foo<&escaped>'
531 p.set('hidden', 'hidden')
532 etree.SubElement(el, 'hr')
533 non_element = etree.SubElement(el, None)
534 non_element.text = 'non-element text'
535 script = etree.SubElement(non_element, 'script')
536 script.text = '<&"test\nescaping">'
537 el.tail = "tail text"
538 self.assertEqual(
539 markdown.serializers.to_xhtml_string(el),
540 '<div id="foo&lt;&amp;&quot;&gt;">'
541 '<p hidden="hidden">foo&lt;&amp;escaped&gt;</p>'
542 '<hr />'
543 'non-element text'
544 '<script><&"test\nescaping"></script>'
545 '</div>tail text'
546 )
547
548 def testMixedCaseTags(self):
549 """" Test preservation of tag case. """
550 el = etree.Element('MixedCase')
551 el.text = 'not valid '
552 em = etree.SubElement(el, 'EMPHASIS')
553 em.text = 'html'
554 etree.SubElement(el, 'HR')
555 self.assertEqual(
556 markdown.serializers.to_xhtml_string(el),
557 '<MixedCase>not valid <EMPHASIS>html</EMPHASIS><HR /></MixedCase>'
558 )
559
560 def testProsessingInstruction(self):
561 """ Test serialization of `ProcessignInstruction`. """
562 pi = ProcessingInstruction('foo', text='<&"test\nescaping">')
563 self.assertIs(pi.tag, ProcessingInstruction)
564 self.assertEqual(
565 markdown.serializers.to_xhtml_string(pi),
566 '<?foo &lt;&amp;"test\nescaping"&gt;?>'
567 )
568
569 def testQNameTag(self):
570 """ Test serialization of `QName` tag. """
571 div = etree.Element('div')
572 qname = etree.QName('http://www.w3.org/1998/Math/MathML', 'math')
573 math = etree.SubElement(div, qname)
574 math.set('display', 'block')
575 sem = etree.SubElement(math, 'semantics')
576 msup = etree.SubElement(sem, 'msup')
577 mi = etree.SubElement(msup, 'mi')
578 mi.text = 'x'
579 mn = etree.SubElement(msup, 'mn')
580 mn.text = '2'
581 ann = etree.SubElement(sem, 'annotations')
582 ann.text = 'x^2'
583 self.assertEqual(
584 markdown.serializers.to_xhtml_string(div),
585 '<div>'
586 '<math display="block" xmlns="http://www.w3.org/1998/Math/MathML">'
587 '<semantics>'
588 '<msup>'
589 '<mi>x</mi>'
590 '<mn>2</mn>'
591 '</msup>'
592 '<annotations>x^2</annotations>'
593 '</semantics>'
594 '</math>'
595 '</div>'
596 )
597
598 def testQNameAttribute(self):
599 """ Test serialization of `QName` attribute. """
600 div = etree.Element('div')
601 div.set(etree.QName('foo'), etree.QName('bar'))
602 self.assertEqual(
603 markdown.serializers.to_xhtml_string(div),
604 '<div foo="bar"></div>'
605 )
606
607 def testBadQNameTag(self):
608 """ Test serialization of `QName` with no tag. """
609 qname = etree.QName('http://www.w3.org/1998/Math/MathML')
610 el = etree.Element(qname)
611 self.assertRaises(ValueError, markdown.serializers.to_xhtml_string, el)
612
613 def testQNameEscaping(self):
614 """ Test `QName` escaping. """
615 qname = etree.QName('<&"test\nescaping">', 'div')
616 el = etree.Element(qname)
617 self.assertEqual(
618 markdown.serializers.to_xhtml_string(el),
619 '<div xmlns="&lt;&amp;&quot;test&#10;escaping&quot;&gt;"></div>'
620 )
621
622 def testQNamePreEscaping(self):
623 """ Test `QName` that is already partially escaped. """
624 qname = etree.QName('&lt;&amp;"test&#10;escaping"&gt;', 'div')
625 el = etree.Element(qname)
626 self.assertEqual(
627 markdown.serializers.to_xhtml_string(el),
628 '<div xmlns="&lt;&amp;&quot;test&#10;escaping&quot;&gt;"></div>'
629 )
630
631 def buildExtension(self):
632 """ Build an extension which registers `fakeSerializer`. """
633 def fakeSerializer(elem):
634 # Ignore input and return hard-coded output
635 return '<div><p>foo</p></div>'
636
637 class registerFakeSerializer(markdown.extensions.Extension):
638 def extendMarkdown(self, md):
639 md.output_formats['fake'] = fakeSerializer
640
641 return registerFakeSerializer()
642
643 def testRegisterSerializer(self):
644 self.assertEqual(
645 markdown.markdown(
646 'baz', extensions=[self.buildExtension()], output_format='fake'
647 ),
648 '<p>foo</p>'
649 )
650
651 def testXHTMLOutput(self):
652 self.assertEqual(
653 markdown.markdown('foo \nbar', output_format='xhtml'),
654 '<p>foo<br />\nbar</p>'
655 )
656
657 def testHTMLOutput(self):
658 self.assertEqual(
659 markdown.markdown('foo \nbar', output_format='html'),
660 '<p>foo<br>\nbar</p>'
661 )
662
663
664 class testAtomicString(unittest.TestCase):
665 """ Test that `AtomicStrings` are honored (not parsed). """
666
667 def setUp(self):
668 self.md = markdown.Markdown()
669 self.inlineprocessor = self.md.treeprocessors['inline']
670
671 def testString(self):
672 """ Test that a regular string is parsed. """
673 tree = etree.Element('div')
674 p = etree.SubElement(tree, 'p')
675 p.text = 'some *text*'
676 new = self.inlineprocessor.run(tree)
677 self.assertEqual(
678 markdown.serializers.to_html_string(new),
679 '<div><p>some <em>text</em></p></div>'
680 )
681
682 def testSimpleAtomicString(self):
683 """ Test that a simple `AtomicString` is not parsed. """
684 tree = etree.Element('div')
685 p = etree.SubElement(tree, 'p')
686 p.text = markdown.util.AtomicString('some *text*')
687 new = self.inlineprocessor.run(tree)
688 self.assertEqual(
689 markdown.serializers.to_html_string(new),
690 '<div><p>some *text*</p></div>'
691 )
692
693 def testNestedAtomicString(self):
694 """ Test that a nested `AtomicString` is not parsed. """
695 tree = etree.Element('div')
696 p = etree.SubElement(tree, 'p')
697 p.text = markdown.util.AtomicString('*some* ')
698 span1 = etree.SubElement(p, 'span')
699 span1.text = markdown.util.AtomicString('*more* ')
700 span2 = etree.SubElement(span1, 'span')
701 span2.text = markdown.util.AtomicString('*text* ')
702 span3 = etree.SubElement(span2, 'span')
703 span3.text = markdown.util.AtomicString('*here*')
704 span3.tail = markdown.util.AtomicString(' *to*')
705 span2.tail = markdown.util.AtomicString(' *test*')
706 span1.tail = markdown.util.AtomicString(' *with*')
707 new = self.inlineprocessor.run(tree)
708 self.assertEqual(
709 markdown.serializers.to_html_string(new),
710 '<div><p>*some* <span>*more* <span>*text* <span>*here*</span> '
711 '*to*</span> *test*</span> *with*</p></div>'
712 )
713
714 def testInlineProcessorDoesntCrashWithWrongAtomicString(self):
715 """ Test that an `AtomicString` returned from a Pattern doesn't cause a crash. """
716 tree = etree.Element('div')
717 p = etree.SubElement(tree, 'p')
718 p.text = 'a marker c'
719 self.md.inlinePatterns.register(
720 _InlineProcessorThatReturnsAtomicString(r'marker', self.md), 'test', 100
721 )
722 new = self.inlineprocessor.run(tree)
723 self.assertEqual(
724 markdown.serializers.to_html_string(new),
725 '<div><p>a &lt;b&gt;atomic&lt;/b&gt; c</p></div>'
726 )
727
728
729 class _InlineProcessorThatReturnsAtomicString(inlinepatterns.InlineProcessor):
730 """ Return a simple text of `group(1)` of a Pattern. """
731 def handleMatch(self, m, data):
732 return markdown.util.AtomicString('<b>atomic</b>'), m.start(0), m.end(0)
733
734
735 class TestConfigParsing(unittest.TestCase):
736 def assertParses(self, value, result):
737 self.assertIs(markdown.util.parseBoolValue(value, False), result)
738
739 def testBooleansParsing(self):
740 self.assertParses(True, True)
741 self.assertParses('novalue', None)
742 self.assertParses('yES', True)
743 self.assertParses('FALSE', False)
744 self.assertParses(0., False)
745 self.assertParses('none', False)
746
747 def testPreserveNone(self):
748 self.assertIsNone(markdown.util.parseBoolValue('None', preserve_none=True))
749 self.assertIsNone(markdown.util.parseBoolValue(None, preserve_none=True))
750
751 def testInvalidBooleansParsing(self):
752 self.assertRaises(ValueError, markdown.util.parseBoolValue, 'novalue')
753
754
755 class TestCliOptionParsing(unittest.TestCase):
756 """ Test parsing of Command Line Interface Options. """
757
758 def setUp(self):
759 self.default_options = {
760 'input': None,
761 'output': None,
762 'encoding': None,
763 'output_format': 'xhtml',
764 'lazy_ol': True,
765 'extensions': [],
766 'extension_configs': {},
767 }
768 self.tempfile = ''
769
770 def tearDown(self):
771 if os.path.isfile(self.tempfile):
772 os.remove(self.tempfile)
773
774 def testNoOptions(self):
775 options, logging_level = parse_options([])
776 self.assertEqual(options, self.default_options)
777 self.assertEqual(logging_level, CRITICAL)
778
779 def testQuietOption(self):
780 options, logging_level = parse_options(['-q'])
781 self.assertGreater(logging_level, CRITICAL)
782
783 def testVerboseOption(self):
784 options, logging_level = parse_options(['-v'])
785 self.assertEqual(logging_level, WARNING)
786
787 def testNoisyOption(self):
788 options, logging_level = parse_options(['--noisy'])
789 self.assertEqual(logging_level, DEBUG)
790
791 def testInputFileOption(self):
792 options, logging_level = parse_options(['foo.txt'])
793 self.default_options['input'] = 'foo.txt'
794 self.assertEqual(options, self.default_options)
795
796 def testOutputFileOption(self):
797 options, logging_level = parse_options(['-f', 'foo.html'])
798 self.default_options['output'] = 'foo.html'
799 self.assertEqual(options, self.default_options)
800
801 def testInputAndOutputFileOptions(self):
802 options, logging_level = parse_options(['-f', 'foo.html', 'foo.txt'])
803 self.default_options['output'] = 'foo.html'
804 self.default_options['input'] = 'foo.txt'
805 self.assertEqual(options, self.default_options)
806
807 def testEncodingOption(self):
808 options, logging_level = parse_options(['-e', 'utf-8'])
809 self.default_options['encoding'] = 'utf-8'
810 self.assertEqual(options, self.default_options)
811
812 def testOutputFormatOption(self):
813 options, logging_level = parse_options(['-o', 'html'])
814 self.default_options['output_format'] = 'html'
815 self.assertEqual(options, self.default_options)
816
817 def testNoLazyOlOption(self):
818 options, logging_level = parse_options(['-n'])
819 self.default_options['lazy_ol'] = False
820 self.assertEqual(options, self.default_options)
821
822 def testExtensionOption(self):
823 options, logging_level = parse_options(['-x', 'markdown.extensions.footnotes'])
824 self.default_options['extensions'] = ['markdown.extensions.footnotes']
825 self.assertEqual(options, self.default_options)
826
827 def testMultipleExtensionOptions(self):
828 options, logging_level = parse_options([
829 '-x', 'markdown.extensions.footnotes',
830 '-x', 'markdown.extensions.smarty'
831 ])
832 self.default_options['extensions'] = [
833 'markdown.extensions.footnotes',
834 'markdown.extensions.smarty'
835 ]
836 self.assertEqual(options, self.default_options)
837
838 def create_config_file(self, config):
839 """ Helper to create temporary configuration files. """
840 if not isinstance(config, str):
841 # convert to string
842 config = yaml.dump(config)
843 fd, self.tempfile = tempfile.mkstemp('.yml')
844 with os.fdopen(fd, 'w') as fp:
845 fp.write(config)
846
847 def testExtensionConfigOption(self):
848 config = {
849 'markdown.extensions.wikilinks': {
850 'base_url': 'http://example.com/',
851 'end_url': '.html',
852 'html_class': 'test',
853 },
854 'markdown.extensions.footnotes:FootnotesExtension': {
855 'PLACE_MARKER': '~~~footnotes~~~'
856 }
857 }
858 self.create_config_file(config)
859 options, logging_level = parse_options(['-c', self.tempfile])
860 self.default_options['extension_configs'] = config
861 self.assertEqual(options, self.default_options)
862
863 def textBoolExtensionConfigOption(self):
864 config = {
865 'markdown.extensions.toc': {
866 'title': 'Some Title',
867 'anchorlink': True,
868 'permalink': True
869 }
870 }
871 self.create_config_file(config)
872 options, logging_level = parse_options(['-c', self.tempfile])
873 self.default_options['extension_configs'] = config
874 self.assertEqual(options, self.default_options)
875
876 def testExtensionConfigOptionAsJSON(self):
877 config = {
878 'markdown.extensions.wikilinks': {
879 'base_url': 'http://example.com/',
880 'end_url': '.html',
881 'html_class': 'test',
882 },
883 'markdown.extensions.footnotes:FootnotesExtension': {
884 'PLACE_MARKER': '~~~footnotes~~~'
885 }
886 }
887 import json
888 self.create_config_file(json.dumps(config))
889 options, logging_level = parse_options(['-c', self.tempfile])
890 self.default_options['extension_configs'] = config
891 self.assertEqual(options, self.default_options)
892
893 def testExtensionConfigOptionMissingFile(self):
894 self.assertRaises(IOError, parse_options, ['-c', 'missing_file.yaml'])
895
896 def testExtensionConfigOptionBadFormat(self):
897 config = """
898 [footnotes]
899 PLACE_MARKER= ~~~footnotes~~~
900 """
901 self.create_config_file(config)
902 self.assertRaises(yaml.YAMLError, parse_options, ['-c', self.tempfile])
903
904
905 class TestEscapeAppend(unittest.TestCase):
906 """ Tests escape character append. """
907
908 def testAppend(self):
909 """ Test that appended escapes are only in the current instance. """
910 md = markdown.Markdown()
911 md.ESCAPED_CHARS.append('|')
912 self.assertEqual('|' in md.ESCAPED_CHARS, True)
913 md2 = markdown.Markdown()
914 self.assertEqual('|' not in md2.ESCAPED_CHARS, True)
915
916
917 class TestBlockAppend(unittest.TestCase):
918 """ Tests block `kHTML` append. """
919
920 def testBlockAppend(self):
921 """ Test that appended escapes are only in the current instance. """
922 md = markdown.Markdown()
923 md.block_level_elements.append('test')
924 self.assertEqual('test' in md.block_level_elements, True)
925 md2 = markdown.Markdown()
926 self.assertEqual('test' not in md2.block_level_elements, True)
927
928
929 class TestAncestorExclusion(unittest.TestCase):
930 """ Tests exclusion of tags in ancestor list. """
931
932 class AncestorExample(markdown.inlinepatterns.SimpleTagInlineProcessor):
933 """ Ancestor Test. """
934
935 ANCESTOR_EXCLUDES = ('a',)
936
937 def handleMatch(self, m, data):
938 """ Handle match. """
939 el = etree.Element(self.tag)
940 el.text = m.group(2)
941 return el, m.start(0), m.end(0)
942
943 class AncestorExtension(markdown.Extension):
944
945 def __init__(self, *args, **kwargs):
946 """Initialize."""
947
948 self.config = {}
949
950 def extendMarkdown(self, md):
951 """Modify inline patterns."""
952
953 pattern = r'(\+)([^\+]+)\1'
954 md.inlinePatterns.register(TestAncestorExclusion.AncestorExample(pattern, 'strong'), 'ancestor-test', 0)
955
956 def setUp(self):
957 """Setup markdown object."""
958 self.md = markdown.Markdown(extensions=[TestAncestorExclusion.AncestorExtension()])
959
960 def test_ancestors(self):
961 """ Test that an extension can exclude parent tags. """
962 test = """
963 Some +test+ and a [+link+](http://test.com)
964 """
965 result = """<p>Some <strong>test</strong> and a <a href="http://test.com">+link+</a></p>"""
966
967 self.md.reset()
968 self.assertEqual(self.md.convert(test), result)
969
970 def test_ancestors_tail(self):
971 """ Test that an extension can exclude parent tags when dealing with a tail. """
972 test = """
973 [***+em+*+strong+**](http://test.com)
974 """
975 result = """<p><a href="http://test.com"><strong><em>+em+</em>+strong+</strong></a></p>"""
976
977 self.md.reset()
978 self.assertEqual(self.md.convert(test), result)