From 61cc00eb93c36cf3140f4b7aa8edba2192548185 Mon Sep 17 00:00:00 2001 From: Waylan Limberg Date: Tue, 23 Feb 2016 20:02:10 -0500 Subject: [PATCH 1/3] Provide new testing framework. As a part of the Markdown lib, test tools can be used by third party extensions. Also keeps test dir clean as it only contains actual tests. More work in this vein to come as the need for Nose is removed. Tests are defined as Unittests rather than in text files allowing features to be more easily broken into units and run individually. Based completely on standard lib unittest with no external dependencies. Use `python -m unittest tests.test_syntax` to run. Pulled some tests from https://github.com/karlcow/markdown-testsuite. Many more test units to pull from that source. As we encounter the need to edit an existing textfile-based test, or add a new test, a new test should be created with this framework and the old test should be deleted. Also need to delete existing testfile-based tests which are covered in the new tests included here. --- markdown/test_tools.py | 44 ++ tests/test_syntax/__init__.py | 0 tests/test_syntax/blocks/__init__.py | 0 tests/test_syntax/blocks/test_code_blocks.py | 67 ++ tests/test_syntax/blocks/test_headers.py | 688 +++++++++++++++++++ tests/test_syntax/blocks/test_hr.py | 342 +++++++++ tests/test_syntax/blocks/test_paragraphs.py | 208 ++++++ 7 files changed, 1349 insertions(+) create mode 100644 markdown/test_tools.py create mode 100644 tests/test_syntax/__init__.py create mode 100644 tests/test_syntax/blocks/__init__.py create mode 100644 tests/test_syntax/blocks/test_code_blocks.py create mode 100644 tests/test_syntax/blocks/test_headers.py create mode 100644 tests/test_syntax/blocks/test_hr.py create mode 100644 tests/test_syntax/blocks/test_paragraphs.py diff --git a/markdown/test_tools.py b/markdown/test_tools.py new file mode 100644 index 000000000..cebb2bb7b --- /dev/null +++ b/markdown/test_tools.py @@ -0,0 +1,44 @@ +import unittest +import textwrap +from markdown import markdown + + +class TestCase(unittest.TestCase): + """ + A unittest.TestCase subclass with helpers for testing Markdown output. + + Define `default_kwargs` as a dict of keywords to pass to Markdown for each + test. The defaults can be overridden on individual tests. + + The `assertMarkdownRenders` method accepts the source text, the expected + output, and any keywords to pass to Markdown. The `default_kwargs` are used + except where overridden by `kwargs`. The ouput and expected ouput are passed + to `TestCase.assertMultiLineEqual`. An AssertionError is raised with a diff + if the actual output does not equal the expected output. + + The `dedent` method is available to dedent triple-quoted strings if + necessary. + + In all other respects, behaves as unittest.TestCase. + """ + + default_kwargs = {} + + def assertMarkdownRenders(self, source, expected, **kwargs): + """ + Test that source Markdown text renders to expected output with given keywords. + """ + + kws = self.default_kwargs.copy() + kws.update(kwargs) + output = markdown(source, **kws) + self.assertMultiLineEqual(output, expected) + + def dedent(self, text): + """ + Dedent text. + """ + + # TODO: If/when actual output ends with a newline, then use: + # return textwrap.dedent(text.strip('/n')) + return textwrap.dedent(text).strip() diff --git a/tests/test_syntax/__init__.py b/tests/test_syntax/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_syntax/blocks/__init__.py b/tests/test_syntax/blocks/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_syntax/blocks/test_code_blocks.py b/tests/test_syntax/blocks/test_code_blocks.py new file mode 100644 index 000000000..00e607099 --- /dev/null +++ b/tests/test_syntax/blocks/test_code_blocks.py @@ -0,0 +1,67 @@ +from markdown.test_tools import TestCase + + +class TestCodeBlocks(TestCase): + + def test_spaced_codeblock(self): + self.assertMarkdownRenders( + ' # A code block.', + + self.dedent( + """ +
# A code block.
+                
+ """ + ) + ) + + def test_tabbed_codeblock(self): + self.assertMarkdownRenders( + '\t# A code block.', + + self.dedent( + """ +
# A code block.
+                
+ """ + ) + ) + + def test_multiline_codeblock(self): + self.assertMarkdownRenders( + ' # Line 1\n # Line 2\n', + + self.dedent( + """ +
# Line 1
+                # Line 2
+                
+ """ + ) + ) + + def test_codeblock_with_blankline(self): + self.assertMarkdownRenders( + ' # Line 1\n\n # Line 2\n', + + self.dedent( + """ +
# Line 1
+
+                # Line 2
+                
+ """ + ) + ) + + def test_codeblock_escape(self): + self.assertMarkdownRenders( + ' ', + + self.dedent( + """ +
<foo & bar>
+                
+ """ + ) + ) diff --git a/tests/test_syntax/blocks/test_headers.py b/tests/test_syntax/blocks/test_headers.py new file mode 100644 index 000000000..63e3a7f18 --- /dev/null +++ b/tests/test_syntax/blocks/test_headers.py @@ -0,0 +1,688 @@ +import unittest +from markdown.test_tools import TestCase + + +class TestSetextHeaders(TestCase): + + def test_setext_h1(self): + self.assertMarkdownRenders( + self.dedent( + """ + This is an H1 + ============= + """ + ), + + '

This is an H1

' + ) + + def test_setext_h2(self): + self.assertMarkdownRenders( + self.dedent( + """ + This is an H2 + ------------- + """ + ), + + '

This is an H2

' + ) + + def test_setext_h1_mismatched_length(self): + self.assertMarkdownRenders( + self.dedent( + """ + This is an H1 + === + """ + ), + + '

This is an H1

' + ) + + def test_setext_h2_mismatched_length(self): + self.assertMarkdownRenders( + self.dedent( + """ + This is an H2 + --- + """ + ), + + '

This is an H2

' + ) + + def test_setext_h1_followed_by_p(self): + self.assertMarkdownRenders( + self.dedent( + """ + This is an H1 + ============= + Followed by a Paragraph with no blank line. + """ + ), + self.dedent( + """ +

This is an H1

+

Followed by a Paragraph with no blank line.

+ """ + ) + ) + + def test_setext_h2_followed_by_p(self): + self.assertMarkdownRenders( + self.dedent( + """ + This is an H2 + ------------- + Followed by a Paragraph with no blank line. + """ + ), + self.dedent( + """ +

This is an H2

+

Followed by a Paragraph with no blank line.

+ """ + ) + ) + + # TODO: fix this + # see http://johnmacfarlane.net/babelmark2/?normalize=1&text=Paragraph%0AAn+H1%0A%3D%3D%3D%3D%3D + @unittest.skip('This is broken in Python-Markdown') + def test_p_followed_by_setext_h1(self): + self.assertMarkdownRenders( + self.dedent( + """ + This is a Paragraph. + Followed by an H1 with no blank line. + ===================================== + """ + ), + self.dedent( + """ +

This is a Paragraph.

+

Followed by an H1 with no blank line.

+ """ + ) + ) + + # TODO: fix this + # see http://johnmacfarlane.net/babelmark2/?normalize=1&text=Paragraph%0AAn+H2%0A----- + @unittest.skip('This is broken in Python-Markdown') + def test_p_followed_by_setext_h2(self): + self.assertMarkdownRenders( + self.dedent( + """ + This is a Paragraph. + Followed by an H2 with no blank line. + ------------------------------------- + """ + ), + self.dedent( + """ +

This is a Paragraph.

+

Followed by an H2 with no blank line.

+ """ + ) + ) + + +class TestHashHeaders(TestCase): + + def test_hash_h1_open(self): + self.assertMarkdownRenders( + '# This is an H1', + + '

This is an H1

' + ) + + def test_hash_h2_open(self): + self.assertMarkdownRenders( + '## This is an H2', + + '

This is an H2

' + ) + + def test_hash_h3_open(self): + self.assertMarkdownRenders( + '### This is an H3', + + '

This is an H3

' + ) + + def test_hash_h4_open(self): + self.assertMarkdownRenders( + '#### This is an H4', + + '

This is an H4

' + ) + + def test_hash_h5_open(self): + self.assertMarkdownRenders( + '##### This is an H5', + + '
This is an H5
' + ) + + def test_hash_h6_open(self): + self.assertMarkdownRenders( + '###### This is an H6', + + '
This is an H6
' + ) + + def test_hash_gt6_open(self): + self.assertMarkdownRenders( + '####### This is an H6', + + '
# This is an H6
' + ) + + def test_hash_h1_open_missing_space(self): + self.assertMarkdownRenders( + '#This is an H1', + + '

This is an H1

' + ) + + def test_hash_h2_open_missing_space(self): + self.assertMarkdownRenders( + '##This is an H2', + + '

This is an H2

' + ) + + def test_hash_h3_open_missing_space(self): + self.assertMarkdownRenders( + '###This is an H3', + + '

This is an H3

' + ) + + def test_hash_h4_open_missing_space(self): + self.assertMarkdownRenders( + '####This is an H4', + + '

This is an H4

' + ) + + def test_hash_h5_open_missing_space(self): + self.assertMarkdownRenders( + '#####This is an H5', + + '
This is an H5
' + ) + + def test_hash_h6_open_missing_space(self): + self.assertMarkdownRenders( + '######This is an H6', + + '
This is an H6
' + ) + + def test_hash_gt6_open_missing_space(self): + self.assertMarkdownRenders( + '#######This is an H6', + + '
#This is an H6
' + ) + + def test_hash_h1_closed(self): + self.assertMarkdownRenders( + '# This is an H1 #', + + '

This is an H1

' + ) + + def test_hash_h2_closed(self): + self.assertMarkdownRenders( + '## This is an H2 ##', + + '

This is an H2

' + ) + + def test_hash_h3_closed(self): + self.assertMarkdownRenders( + '### This is an H3 ###', + + '

This is an H3

' + ) + + def test_hash_h4_closed(self): + self.assertMarkdownRenders( + '#### This is an H4 ####', + + '

This is an H4

' + ) + + def test_hash_h5_closed(self): + self.assertMarkdownRenders( + '##### This is an H5 #####', + + '
This is an H5
' + ) + + def test_hash_h6_closed(self): + self.assertMarkdownRenders( + '###### This is an H6 ######', + + '
This is an H6
' + ) + + def test_hash_gt6_closed(self): + self.assertMarkdownRenders( + '####### This is an H6 #######', + + '
# This is an H6
' + ) + + def test_hash_h1_closed_missing_space(self): + self.assertMarkdownRenders( + '#This is an H1#', + + '

This is an H1

' + ) + + def test_hash_h2_closed_missing_space(self): + self.assertMarkdownRenders( + '##This is an H2##', + + '

This is an H2

' + ) + + def test_hash_h3_closed_missing_space(self): + self.assertMarkdownRenders( + '###This is an H3###', + + '

This is an H3

' + ) + + def test_hash_h4_closed_missing_space(self): + self.assertMarkdownRenders( + '####This is an H4####', + + '

This is an H4

' + ) + + def test_hash_h5_closed_missing_space(self): + self.assertMarkdownRenders( + '#####This is an H5#####', + + '
This is an H5
' + ) + + def test_hash_h6_closed_missing_space(self): + self.assertMarkdownRenders( + '######This is an H6######', + + '
This is an H6
' + ) + + def test_hash_gt6_closed_missing_space(self): + self.assertMarkdownRenders( + '#######This is an H6#######', + + '
#This is an H6
' + ) + + def test_hash_h1_closed_mismatch(self): + self.assertMarkdownRenders( + '# This is an H1 ##', + + '

This is an H1

' + ) + + def test_hash_h2_closed_mismatch(self): + self.assertMarkdownRenders( + '## This is an H2 #', + + '

This is an H2

' + ) + + def test_hash_h3_closed_mismatch(self): + self.assertMarkdownRenders( + '### This is an H3 #', + + '

This is an H3

' + ) + + def test_hash_h4_closed_mismatch(self): + self.assertMarkdownRenders( + '#### This is an H4 #', + + '

This is an H4

' + ) + + def test_hash_h5_closed_mismatch(self): + self.assertMarkdownRenders( + '##### This is an H5 #', + + '
This is an H5
' + ) + + def test_hash_h6_closed_mismatch(self): + self.assertMarkdownRenders( + '###### This is an H6 #', + + '
This is an H6
' + ) + + def test_hash_gt6_closed_mismatch(self): + self.assertMarkdownRenders( + '####### This is an H6 ##################', + + '
# This is an H6
' + ) + + def test_hash_h1_followed_by_p(self): + self.assertMarkdownRenders( + self.dedent( + """ + # This is an H1 + Followed by a Paragraph with no blank line. + """ + ), + self.dedent( + """ +

This is an H1

+

Followed by a Paragraph with no blank line.

+ """ + ) + ) + + def test_hash_h2_followed_by_p(self): + self.assertMarkdownRenders( + self.dedent( + """ + ## This is an H2 + Followed by a Paragraph with no blank line. + """ + ), + self.dedent( + """ +

This is an H2

+

Followed by a Paragraph with no blank line.

+ """ + ) + ) + + def test_hash_h3_followed_by_p(self): + self.assertMarkdownRenders( + self.dedent( + """ + ### This is an H3 + Followed by a Paragraph with no blank line. + """ + ), + self.dedent( + """ +

This is an H3

+

Followed by a Paragraph with no blank line.

+ """ + ) + ) + + def test_hash_h4_followed_by_p(self): + self.assertMarkdownRenders( + self.dedent( + """ + #### This is an H4 + Followed by a Paragraph with no blank line. + """ + ), + self.dedent( + """ +

This is an H4

+

Followed by a Paragraph with no blank line.

+ """ + ) + ) + + def test_hash_h5_followed_by_p(self): + self.assertMarkdownRenders( + self.dedent( + """ + ##### This is an H5 + Followed by a Paragraph with no blank line. + """ + ), + self.dedent( + """ +
This is an H5
+

Followed by a Paragraph with no blank line.

+ """ + ) + ) + + def test_hash_h6_followed_by_p(self): + self.assertMarkdownRenders( + self.dedent( + """ + ###### This is an H6 + Followed by a Paragraph with no blank line. + """ + ), + self.dedent( + """ +
This is an H6
+

Followed by a Paragraph with no blank line.

+ """ + ) + ) + + def test_hash_h1_leading_space(self): + self.assertMarkdownRenders( + ' # This is an H1', + + '

# This is an H1

' + ) + + def test_hash_h2_leading_space(self): + self.assertMarkdownRenders( + ' ## This is an H2', + + '

## This is an H2

' + ) + + def test_hash_h3_leading_space(self): + self.assertMarkdownRenders( + ' ### This is an H3', + + '

### This is an H3

' + ) + + def test_hash_h4_leading_space(self): + self.assertMarkdownRenders( + ' #### This is an H4', + + '

#### This is an H4

' + ) + + def test_hash_h5_leading_space(self): + self.assertMarkdownRenders( + ' ##### This is an H5', + + '

##### This is an H5

' + ) + + def test_hash_h6_leading_space(self): + self.assertMarkdownRenders( + ' ###### This is an H6', + + '

###### This is an H6

' + ) + + def test_hash_h1_open_trailing_space(self): + self.assertMarkdownRenders( + '# This is an H1 ', + + '

This is an H1

' + ) + + def test_hash_h2_open_trailing_space(self): + self.assertMarkdownRenders( + '## This is an H2 ', + + '

This is an H2

' + ) + + def test_hash_h3_open_trailing_space(self): + self.assertMarkdownRenders( + '### This is an H3 ', + + '

This is an H3

' + ) + + def test_hash_h4_open_trailing_space(self): + self.assertMarkdownRenders( + '#### This is an H4 ', + + '

This is an H4

' + ) + + def test_hash_h5_open_trailing_space(self): + self.assertMarkdownRenders( + '##### This is an H5 ', + + '
This is an H5
' + ) + + def test_hash_h6_open_trailing_space(self): + self.assertMarkdownRenders( + '###### This is an H6 ', + + '
This is an H6
' + ) + + def test_hash_gt6_open_trailing_space(self): + self.assertMarkdownRenders( + '####### This is an H6 ', + + '
# This is an H6
' + ) + + # TODO: Possably change the following behavior. While this follows the behavior + # of markdown.pl, it is rather uncommon and not nessecarily intuitive. + # See: http://johnmacfarlane.net/babelmark2/?normalize=1&text=%23+This+is+an+H1+%23+ + def test_hash_h1_closed_trailing_space(self): + self.assertMarkdownRenders( + '# This is an H1 # ', + + '

This is an H1 #

' + ) + + def test_hash_h2_closed_trailing_space(self): + self.assertMarkdownRenders( + '## This is an H2 ## ', + + '

This is an H2 ##

' + ) + + def test_hash_h3_closed_trailing_space(self): + self.assertMarkdownRenders( + '### This is an H3 ### ', + + '

This is an H3 ###

' + ) + + def test_hash_h4_closed_trailing_space(self): + self.assertMarkdownRenders( + '#### This is an H4 #### ', + + '

This is an H4 ####

' + ) + + def test_hash_h5_closed_trailing_space(self): + self.assertMarkdownRenders( + '##### This is an H5 ##### ', + + '
This is an H5 #####
' + ) + + def test_hash_h6_closed_trailing_space(self): + self.assertMarkdownRenders( + '###### This is an H6 ###### ', + + '
This is an H6 ######
' + ) + + def test_hash_gt6_closed_trailing_space(self): + self.assertMarkdownRenders( + '####### This is an H6 ####### ', + + '
# This is an H6 #######
' + ) + + def test_no_blank_lines_between_hashs(self): + self.assertMarkdownRenders( + self.dedent( + """ + # This is an H1 + ## This is an H2 + """ + ), + self.dedent( + """ +

This is an H1

+

This is an H2

+ """ + ) + ) + + def test_random_hash_levels(self): + self.assertMarkdownRenders( + self.dedent( + """ + ### H3 + ###### H6 + # H1 + ##### H5 + #### H4 + ## H2 + ### H3 + """ + ), + self.dedent( + """ +

H3

+
H6
+

H1

+
H5
+

H4

+

H2

+

H3

+ """ + ) + ) + + def test_hash_followed_by_p(self): + self.assertMarkdownRenders( + self.dedent( + """ + # This is an H1 + Followed by a Paragraph with no blank line. + """ + ), + self.dedent( + """ +

This is an H1

+

Followed by a Paragraph with no blank line.

+ """ + ) + ) + + def test_p_followed_by_hash(self): + self.assertMarkdownRenders( + self.dedent( + """ + This is a Paragraph. + # Followed by an H1 with no blank line. + """ + ), + self.dedent( + """ +

This is a Paragraph.

+

Followed by an H1 with no blank line.

+ """ + ) + ) diff --git a/tests/test_syntax/blocks/test_hr.py b/tests/test_syntax/blocks/test_hr.py new file mode 100644 index 000000000..ffd082346 --- /dev/null +++ b/tests/test_syntax/blocks/test_hr.py @@ -0,0 +1,342 @@ +from markdown.test_tools import TestCase + + +class TestHorizontalRules(TestCase): + + def test_hr_asterisks(self): + self.assertMarkdownRenders( + '***', + + '
' + ) + + def test_hr_asterisks_spaces(self): + self.assertMarkdownRenders( + '* * *', + + '
' + ) + + def test_hr_asterisks_long(self): + self.assertMarkdownRenders( + '*******', + + '
' + ) + + def test_hr_asterisks_spaces_long(self): + self.assertMarkdownRenders( + '* * * * * * *', + + '
' + ) + + def test_hr_asterisks_1_indent(self): + self.assertMarkdownRenders( + ' ***', + + '
' + ) + + def test_hr_asterisks_spaces_1_indent(self): + self.assertMarkdownRenders( + ' * * *', + + '
' + ) + + def test_hr_asterisks_2_indent(self): + self.assertMarkdownRenders( + ' ***', + + '
' + ) + + def test_hr_asterisks_spaces_2_indent(self): + self.assertMarkdownRenders( + ' * * *', + + '
' + ) + + def test_hr_asterisks_3_indent(self): + self.assertMarkdownRenders( + ' ***', + + '
' + ) + + def test_hr_asterisks_spaces_3_indent(self): + self.assertMarkdownRenders( + ' * * *', + + '
' + ) + + def test_hr_asterisks_trailing_space(self): + self.assertMarkdownRenders( + '*** ', + + '
' + ) + + def test_hr_asterisks_spaces_trailing_space(self): + self.assertMarkdownRenders( + '* * * ', + + '
' + ) + + def test_hr_hyphens(self): + self.assertMarkdownRenders( + '---', + + '
' + ) + + def test_hr_hyphens_spaces(self): + self.assertMarkdownRenders( + '- - -', + + '
' + ) + + def test_hr_hyphens_long(self): + self.assertMarkdownRenders( + '-------', + + '
' + ) + + def test_hr_hyphens_spaces_long(self): + self.assertMarkdownRenders( + '- - - - - - -', + + '
' + ) + + def test_hr_hyphens_1_indent(self): + self.assertMarkdownRenders( + ' ---', + + '
' + ) + + def test_hr_hyphens_spaces_1_indent(self): + self.assertMarkdownRenders( + ' - - -', + + '
' + ) + + def test_hr_hyphens_2_indent(self): + self.assertMarkdownRenders( + ' ---', + + '
' + ) + + def test_hr_hyphens_spaces_2_indent(self): + self.assertMarkdownRenders( + ' - - -', + + '
' + ) + + def test_hr_hyphens_3_indent(self): + self.assertMarkdownRenders( + ' ---', + + '
' + ) + + def test_hr_hyphens_spaces_3_indent(self): + self.assertMarkdownRenders( + ' - - -', + + '
' + ) + + def test_hr_hyphens_trailing_space(self): + self.assertMarkdownRenders( + '--- ', + + '
' + ) + + def test_hr_hyphens_spaces_trailing_space(self): + self.assertMarkdownRenders( + '- - - ', + + '
' + ) + + def test_hr_underscores(self): + self.assertMarkdownRenders( + '___', + + '
' + ) + + def test_hr_underscores_spaces(self): + self.assertMarkdownRenders( + '_ _ _', + + '
' + ) + + def test_hr_underscores_long(self): + self.assertMarkdownRenders( + '_______', + + '
' + ) + + def test_hr_underscores_spaces_long(self): + self.assertMarkdownRenders( + '_ _ _ _ _ _ _', + + '
' + ) + + def test_hr_underscores_1_indent(self): + self.assertMarkdownRenders( + ' ___', + + '
' + ) + + def test_hr_underscores_spaces_1_indent(self): + self.assertMarkdownRenders( + ' _ _ _', + + '
' + ) + + def test_hr_underscores_2_indent(self): + self.assertMarkdownRenders( + ' ___', + + '
' + ) + + def test_hr_underscores_spaces_2_indent(self): + self.assertMarkdownRenders( + ' _ _ _', + + '
' + ) + + def test_hr_underscores_3_indent(self): + self.assertMarkdownRenders( + ' ___', + + '
' + ) + + def test_hr_underscores_spaces_3_indent(self): + self.assertMarkdownRenders( + ' _ _ _', + + '
' + ) + + def test_hr_underscores_trailing_space(self): + self.assertMarkdownRenders( + '___ ', + + '
' + ) + + def test_hr_underscores_spaces_trailing_space(self): + self.assertMarkdownRenders( + '_ _ _ ', + + '
' + ) + + def test_hr_before_paragraph(self): + self.assertMarkdownRenders( + self.dedent( + """ + *** + An HR followed by a paragraph with no blank line. + """ + ), + self.dedent( + """ +
+

An HR followed by a paragraph with no blank line.

+ """ + ) + ) + + def test_hr_after_paragraph(self): + self.assertMarkdownRenders( + self.dedent( + """ + A paragraph followed by an HR with no blank line. + *** + """ + ), + self.dedent( + """ +

A paragraph followed by an HR with no blank line.

+
+ """ + ) + ) + + def test_not_hr_2_asterisks(self): + self.assertMarkdownRenders( + '**', + + '

**

' + ) + + def test_not_hr_2_asterisks_spaces(self): + self.assertMarkdownRenders( + '* *', + + self.dedent( + """ + + """ + ) + ) + + def test_not_hr_2_hyphens(self): + self.assertMarkdownRenders( + '--', + + '

--

' + ) + + def test_not_hr_2_hyphens_spaces(self): + self.assertMarkdownRenders( + '- -', + + self.dedent( + """ + + """ + ) + ) + + def test_not_hr_2_underscores(self): + self.assertMarkdownRenders( + '__', + + '

__

' + ) + + def test_not_hr_2_underscores_spaces(self): + self.assertMarkdownRenders( + '_ _', + + '

_ _

' + ) diff --git a/tests/test_syntax/blocks/test_paragraphs.py b/tests/test_syntax/blocks/test_paragraphs.py new file mode 100644 index 000000000..b458fc1fe --- /dev/null +++ b/tests/test_syntax/blocks/test_paragraphs.py @@ -0,0 +1,208 @@ +from markdown.test_tools import TestCase + + +class TestParagraphBlocks(TestCase): + + def test_simple_paragraph(self): + self.assertMarkdownRenders( + 'A simple paragraph.', + + '

A simple paragraph.

' + ) + + def test_blank_line_before_paragraph(self): + self.assertMarkdownRenders( + '\nA paragraph preceded by a blank line.', + + '

A paragraph preceded by a blank line.

' + ) + + def test_multiline_paragraph(self): + self.assertMarkdownRenders( + self.dedent( + """ + This is a paragraph + on multiple lines + with hard returns. + """ + ), + self.dedent( + """ +

This is a paragraph + on multiple lines + with hard returns.

+ """ + ) + ) + + def test_paragraph_long_line(self): + self.assertMarkdownRenders( + 'A very long long long long long long long long long long long long long long long long long long long ' + 'long long long long long long long long long long long long long paragraph on 1 line.', + + '

A very long long long long long long long long long long long long long long long long long long ' + 'long long long long long long long long long long long long long long paragraph on 1 line.

' + ) + + def test_2_paragraphs_long_line(self): + self.assertMarkdownRenders( + 'A very long long long long long long long long long long long long long long long long long long long ' + 'long long long long long long long long long long long long long paragraph on 1 line.\n\n' + + 'A new long long long long long long long long long long long long long long long ' + 'long paragraph on 1 line.', + + '

A very long long long long long long long long long long long long long long long long long long ' + 'long long long long long long long long long long long long long long paragraph on 1 line.

\n' + '

A new long long long long long long long long long long long long long long long ' + 'long paragraph on 1 line.

' + ) + + def test_consecutive_paragraphs(self): + self.assertMarkdownRenders( + self.dedent( + """ + Paragraph 1. + + Paragraph 2. + """ + ), + self.dedent( + """ +

Paragraph 1.

+

Paragraph 2.

+ """ + ) + ) + + def test_consecutive_paragraphs_tab(self): + self.assertMarkdownRenders( + self.dedent( + """ + Paragraph followed by a line with a tab only. + \t + Paragraph after a line with a tab only. + """ + ), + self.dedent( + """ +

Paragraph followed by a line with a tab only.

+

Paragraph after a line with a tab only.

+ """ + ) + ) + + def test_consecutive_paragraphs_space(self): + self.assertMarkdownRenders( + self.dedent( + """ + Paragraph followed by a line with a space only. + + Paragraph after a line with a space only. + """ + ), + self.dedent( + """ +

Paragraph followed by a line with a space only.

+

Paragraph after a line with a space only.

+ """ + ) + ) + + def test_consecutive_multiline_paragraphs(self): + self.assertMarkdownRenders( + self.dedent( + """ + Paragraph 1, line 1. + Paragraph 1, line 2. + + Paragraph 2, line 1. + Paragraph 2, line 2. + """ + ), + self.dedent( + """ +

Paragraph 1, line 1. + Paragraph 1, line 2.

+

Paragraph 2, line 1. + Paragraph 2, line 2.

+ """ + ) + ) + + def test_paragraph_leading_space(self): + self.assertMarkdownRenders( + ' A paragraph with 1 leading space.', + + '

A paragraph with 1 leading space.

' + ) + + def test_paragraph_2_leading_spaces(self): + self.assertMarkdownRenders( + ' A paragraph with 2 leading spaces.', + + '

A paragraph with 2 leading spaces.

' + ) + + def test_paragraph_3_leading_spaces(self): + self.assertMarkdownRenders( + ' A paragraph with 3 leading spaces.', + + '

A paragraph with 3 leading spaces.

' + ) + + def test_paragraph_trailing_leading_space(self): + self.assertMarkdownRenders( + ' A paragraph with 1 trailing and 1 leading space. ', + + '

A paragraph with 1 trailing and 1 leading space.

' + ) + + def test_paragraph_trailing_tab(self): + self.assertMarkdownRenders( + 'A paragraph with 1 trailing tab.\t', + + '

A paragraph with 1 trailing tab.

' + ) + + def test_paragraphs_CR(self): + self.assertMarkdownRenders( + 'Paragraph 1, line 1.\rParagraph 1, line 2.\r\rParagraph 2, line 1.\rParagraph 2, line 2.\r', + + self.dedent( + """ +

Paragraph 1, line 1. + Paragraph 1, line 2.

+

Paragraph 2, line 1. + Paragraph 2, line 2.

+ """ + ) + ) + + def test_paragraphs_LF(self): + self.assertMarkdownRenders( + 'Paragraph 1, line 1.\nParagraph 1, line 2.\n\nParagraph 2, line 1.\nParagraph 2, line 2.\n', + + self.dedent( + """ +

Paragraph 1, line 1. + Paragraph 1, line 2.

+

Paragraph 2, line 1. + Paragraph 2, line 2.

+ """ + ) + ) + + def test_paragraphs_CR_LF(self): + self.assertMarkdownRenders( + 'Paragraph 1, line 1.\r\nParagraph 1, line 2.\r\n\r\nParagraph 2, line 1.\r\nParagraph 2, line 2.\r\n', + + self.dedent( + """ +

Paragraph 1, line 1. + Paragraph 1, line 2.

+

Paragraph 2, line 1. + Paragraph 2, line 2.

+ """ + ) + ) From 322bc5d2c8ac5d6e2743e3aa1d9362a37570db09 Mon Sep 17 00:00:00 2001 From: Waylan Limberg Date: Sat, 6 Jan 2018 01:04:11 -0500 Subject: [PATCH 2/3] Switch from nose to unittest All file-based tests are now defined as unittest test cases via a metaclass which walks a directory and builds a unittest for each pair of test files. To run the tests just run `python -m unittest discover tests`. Or use tox as the tox config has been updated to run the new tests and all nose specific code has been removed. The test generator tools have been removed as well. If any changes or additions need to be made to tests, they should be implemented using the new framework rather than with the file-based tests. Eventually, only the PHP and pl tests should remain as file-based tests. --- MANIFEST.in | 3 +- makefile | 8 +- markdown/test_tools.py | 125 ++++++++++++++++++- run-tests.py | 23 ---- setup.cfg | 2 - test-requirements.txt | 1 - tests/__init__.py | 189 ---------------------------- tests/basic/benchmark.dat | 20 --- tests/extensions/extra/test.cfg | 36 ------ tests/extensions/test.cfg | 73 ----------- tests/options/test.cfg | 11 -- tests/php/extra/test.cfg | 7 -- tests/php/test.cfg | 50 -------- tests/pl/Tests_2004/test.cfg | 10 -- tests/pl/Tests_2007/test.cfg | 25 ---- tests/plugins.py | 127 ------------------- tests/safe_mode/test.cfg | 8 -- tests/test_legacy.py | 213 ++++++++++++++++++++++++++++++++ tox.ini | 4 +- 19 files changed, 342 insertions(+), 593 deletions(-) delete mode 100755 run-tests.py delete mode 100644 tests/basic/benchmark.dat delete mode 100644 tests/extensions/extra/test.cfg delete mode 100644 tests/extensions/test.cfg delete mode 100644 tests/options/test.cfg delete mode 100644 tests/php/extra/test.cfg delete mode 100644 tests/php/test.cfg delete mode 100644 tests/pl/Tests_2004/test.cfg delete mode 100644 tests/pl/Tests_2007/test.cfg delete mode 100644 tests/plugins.py delete mode 100644 tests/safe_mode/test.cfg create mode 100644 tests/test_legacy.py diff --git a/MANIFEST.in b/MANIFEST.in index b60fb3bff..4fb63f4b6 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,9 +1,8 @@ recursive-include markdown *.py recursive-include docs * -recursive-include tests *.txt *.html *.cfg *.py +recursive-include tests *.txt *.html *.py include setup.py include setup.cfg -include run-tests.py include tox.ini include makefile include LICENSE.md diff --git a/makefile b/makefile index 8cfd0eaee..3eb7d4833 100644 --- a/makefile +++ b/makefile @@ -11,7 +11,6 @@ help: @echo ' build-win Build a Windows exe distribution' @echo ' docs Build documentation' @echo ' test Run all tests' - @echo ' update-tests Generate html files for updated text files in tests' @echo ' clean Clean up the source directories' .PHONY : install @@ -38,11 +37,8 @@ docs: .PHONY : test test: - tox - -.PHONY : update-tests -update-tests: - python run-tests.py update + coverage run --source=markdown -m unittest discover tests + coverage report --show-missing .PHONY : clean clean: diff --git a/markdown/test_tools.py b/markdown/test_tools.py index cebb2bb7b..9324bd4e2 100644 --- a/markdown/test_tools.py +++ b/markdown/test_tools.py @@ -1,6 +1,16 @@ +from __future__ import absolute_import +import os +import io import unittest import textwrap -from markdown import markdown +from . import markdown + +try: + import tidylib +except ImportError: + tidylib = None + +__all__ = ['TestCase', 'LegacyTestCase', 'Kwargs'] class TestCase(unittest.TestCase): @@ -42,3 +52,116 @@ def dedent(self, text): # TODO: If/when actual output ends with a newline, then use: # return textwrap.dedent(text.strip('/n')) return textwrap.dedent(text).strip() + + +######################### +# Legacy Test Framework # +######################### + + +class Kwargs(dict): + """ A dict like class for holding keyword arguments. """ + pass + + +def _normalize_whitespace(text): + """ Normalize whitespace for a string of html using tidylib. """ + output, errors = tidylib.tidy_fragment(text, options={ + 'drop_empty_paras': 0, + 'fix_backslash': 0, + 'fix_bad_comments': 0, + 'fix_uri': 0, + 'join_styles': 0, + 'lower_literals': 0, + 'merge_divs': 0, + 'output_xhtml': 1, + 'quote_ampersand': 0, + 'newline': 'LF' + }) + return output + + +class LegacyTestMeta(type): + def __new__(cls, name, bases, dct): + + def generate_test(infile, outfile, normalize, kwargs): + def test(self): + with io.open(infile, encoding="utf-8") as f: + input = f.read() + with io.open(outfile, encoding="utf-8") as f: + # Normalize line endings + # (on Windows, git may have altered line endings). + expected = f.read().replace("\r\n", "\n") + output = markdown(input, **kwargs) + if tidylib and normalize: + expected = _normalize_whitespace(expected) + output = _normalize_whitespace(output) + elif normalize: + self.skipTest('Tidylib not available.') + self.assertMultiLineEqual(output, expected) + return test + + location = dct.get('location', '') + exclude = dct.get('exclude', []) + normalize = dct.get('normalize', False) + input_ext = dct.get('input_ext', '.txt') + output_ext = dct.get('output_ext', '.html') + kwargs = dct.get('default_kwargs', Kwargs()) + + if os.path.isdir(location): + for file in os.listdir(location): + infile = os.path.join(location, file) + if os.path.isfile(infile): + tname, ext = os.path.splitext(file) + if ext == input_ext: + outfile = os.path.join(location, tname + output_ext) + tname = tname.replace(' ', '_').replace('-', '_') + kws = kwargs.copy() + if tname in dct: + kws.update(dct[tname]) + test_name = 'test_%s' % tname + if tname not in exclude: + dct[test_name] = generate_test(infile, outfile, normalize, kws) + else: + dct[test_name] = unittest.skip('Excluded')(lambda: None) + + return type.__new__(cls, name, bases, dct) + + +# Define LegacyTestCase class with metaclass in Py2 & Py3 compatable way. +# See https://stackoverflow.com/a/38668373/866026 +# TODO: If/when py2 support is dropped change to: +# class LegacyTestCase(unittest.Testcase, metaclass=LegacyTestMeta) + + +class LegacyTestCase(LegacyTestMeta('LegacyTestCase', (unittest.TestCase,), {'__slots__': ()})): + """ + A `unittest.TestCase` subclass for running Markdown's legacy file-based tests. + + A subclass should define various properties which point to a directory of + text-based test files and define various behaviors/defaults for those tests. + The following properties are supported: + + location: A path to the directory fo test files. An absolute path is prefered. + exclude: A list of tests to exclude. Each test name should comprise the filename + without an extension. + normalize: A boolean value indicating if the HTML should be normalized. + Default: `False`. + input_ext: A string containing the file extension of input files. Default: `.txt`. + ouput_ext: A string containing the file extension of expected output files. + Default: `html`. + default_kwargs: A `Kwargs` instance which stores the default set of keyword + arguments for all test files in the directory. + + In addition, properties can be defined for each individual set of test files within + the directory. The property should be given the name of the file wihtout the file + extension. Any spaces and dashes in the filename should be replaced with + underscores. The value of the property should be a `Kwargs` instance which + contains the keyword arguments that should be passed to `Markdown` for that + test file. The keyword arguments will "update" the `default_kwargs`. + + When the class instance is created, it will walk the given directory and create + a seperate unitttest for each set of test files using the naming scheme: + `test_filename`. One unittest will be run for each set of input and output files. + """ + pass diff --git a/run-tests.py b/run-tests.py deleted file mode 100755 index 574895377..000000000 --- a/run-tests.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python - -import tests -import os -import sys - -if len(sys.argv) > 1 and sys.argv[1] == "update": - if len(sys.argv) > 2: - config = tests.get_config(os.path.dirname(sys.argv[2])) - root, ext = os.path.splitext(sys.argv[2]) - if ext == config.get( - config.get_section(os.path.basename(root)), 'input_ext' - ): - tests.generate(root, config) - else: - print( - sys.argv[2], - 'does not have a valid file extension. Check config.' - ) - else: - tests.generate_all() -else: - tests.run() diff --git a/setup.cfg b/setup.cfg index 81482a994..5e17c83d1 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,5 +1,3 @@ -[nosetests] - [bdist_wheel] universal=1 diff --git a/test-requirements.txt b/test-requirements.txt index 65bfae034..12244ab41 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -1,4 +1,3 @@ -nose coverage<4.0 pyyaml pytidylib diff --git a/tests/__init__.py b/tests/__init__.py index 6826ff343..e69de29bb 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,189 +0,0 @@ -import os -import markdown -import codecs -import difflib -import warnings -try: - import nose -except ImportError as e: - msg = e.args[0] - msg = msg + ". The nose testing framework is required to run the Python-" \ - "Markdown tests. Run `pip install nose` to install the latest version." - e.args = (msg,) + e.args[1:] - raise -from .plugins import HtmlOutput, Markdown, MarkdownSyntaxError -try: - import tidylib -except ImportError: - tidylib = None -try: - import yaml -except ImportError as e: - msg = e.args[0] - msg = msg + ". A YAML library is required to run the Python-Markdown " \ - "tests. Run `pip install pyyaml` to install the latest version." - e.args = (msg,) + e.args[1:] - raise - -test_dir = os.path.abspath(os.path.dirname(__file__)) - - -class YamlConfig(): - def __init__(self, defaults, filename): - """ Set defaults and load config file if it exists. """ - self.DEFAULT_SECTION = 'DEFAULT' - self._defaults = defaults - self._config = {} - if os.path.exists(filename): - with codecs.open(filename, encoding="utf-8") as f: - self._config = yaml.load(f) - - def get(self, section, option): - """ Get config value for given section and option key. """ - if section in self._config and option in self._config[section]: - return self._config[section][option] - return self._defaults[option] - - def get_section(self, file): - """ Get name of config section for given file. """ - filename = os.path.basename(file) - if filename in self._config: - return filename - else: - return self.DEFAULT_SECTION - - def get_args(self, file): - """ Get args to pass to markdown from config for a given file. """ - args = {} - section = self.get_section(file) - if section in self._config: - for key in self._config[section].keys(): - # Filter out args unique to testing framework - if key not in self._defaults.keys(): - args[key] = self.get(section, key) - return args - - -def get_config(dir_name): - """ Get config for given directory name. """ - defaults = { - 'normalize': False, - 'skip': False, - 'input_ext': '.txt', - 'output_ext': '.html' - } - config = YamlConfig(defaults, os.path.join(dir_name, 'test.cfg')) - return config - - -def normalize(text): - """ Normalize whitespace for a string of html using tidylib. """ - output, errors = tidylib.tidy_fragment(text, options={ - 'drop_empty_paras': 0, - 'fix_backslash': 0, - 'fix_bad_comments': 0, - 'fix_uri': 0, - 'join_styles': 0, - 'lower_literals': 0, - 'merge_divs': 0, - 'output_xhtml': 1, - 'quote_ampersand': 0, - 'newline': 'LF' - }) - return output - - -class CheckSyntax(object): - def __init__(self, description=None): - if description: - self.description = 'TestSyntax: "%s"' % description - - def __call__(self, file, config): - """ Compare expected output to actual output and report result. """ - cfg_section = config.get_section(file) - if config.get(cfg_section, 'skip'): - raise nose.plugins.skip.SkipTest('Test skipped per config.') - input_file = file + config.get(cfg_section, 'input_ext') - with codecs.open(input_file, encoding="utf-8") as f: - input = f.read() - output_file = file + config.get(cfg_section, 'output_ext') - with codecs.open(output_file, encoding="utf-8") as f: - # Normalize line endings - # (on windows, git may have altered line endings). - expected_output = f.read().replace("\r\n", "\n") - output = markdown.markdown(input, **config.get_args(file)) - if tidylib and config.get(cfg_section, 'normalize'): - # Normalize whitespace with tidylib before comparing. - expected_output = normalize(expected_output) - output = normalize(output) - elif config.get(cfg_section, 'normalize'): - # Tidylib is not available. Skip this test. - raise nose.plugins.skip.SkipTest( - 'Test skipped. Tidylib not available on system.' - ) - diff = [l for l in difflib.unified_diff( - expected_output.splitlines(True), - output.splitlines(True), - output_file, - 'actual_output.html', - n=3 - )] - if diff: - raise MarkdownSyntaxError( - 'Output from "%s" failed to match expected ' - 'output.\n\n%s' % (input_file, ''.join(diff)) - ) - - -def TestSyntax(): - for dir_name, sub_dirs, files in os.walk(test_dir): - # Get dir specific config settings. - config = get_config(dir_name) - # Loop through files and generate tests. - for file in files: - root, ext = os.path.splitext(file) - if ext == config.get(config.get_section(file), 'input_ext'): - path = os.path.join(dir_name, root) - check_syntax = CheckSyntax( - description=os.path.relpath(path, test_dir) - ) - yield check_syntax, path, config - - -def generate(file, config): - """ Write expected output file for given input. """ - cfg_section = config.get_section(file) - if config.get(cfg_section, 'skip') or config.get(cfg_section, 'normalize'): - print('Skipping:', file) - return None - input_file = file + config.get(cfg_section, 'input_ext') - output_file = file + config.get(cfg_section, 'output_ext') - if not os.path.isfile(output_file) or \ - os.path.getmtime(output_file) < os.path.getmtime(input_file): - print('Generating:', file) - markdown.markdownFromFile(input=input_file, output=output_file, - encoding='utf-8', **config.get_args(file)) - else: - print('Already up-to-date:', file) - - -def generate_all(): - """ Generate expected output for all outdated tests. """ - for dir_name, sub_dirs, files in os.walk(test_dir): - # Get dir specific config settings. - config = get_config(dir_name) - # Loop through files and generate tests. - for file in files: - root, ext = os.path.splitext(file) - if ext == config.get(config.get_section(file), 'input_ext'): - generate(os.path.join(dir_name, root), config) - - -def run(): - # Warnings should cause tests to fail... - warnings.simplefilter('error') - # Except for the warnings that shouldn't - warnings.filterwarnings('default', category=PendingDeprecationWarning) - warnings.filterwarnings('default', category=DeprecationWarning, module='markdown') - - nose.main(addplugins=[HtmlOutput(), Markdown()]) diff --git a/tests/basic/benchmark.dat b/tests/basic/benchmark.dat deleted file mode 100644 index 3d549dde4..000000000 --- a/tests/basic/benchmark.dat +++ /dev/null @@ -1,20 +0,0 @@ -construction:0.000000:0.000000 -amps-and-angle-encoding:0.070000:131072.000000 -auto-links:0.080000:397312.000000 -backlash-escapes:0.270000:884736.000000 -blockquotes-with-dode-blocks:0.020000:0.000000 -hard-wrapped:0.020000:0.000000 -horizontal-rules:0.180000:135168.000000 -inline-html-advanced:0.070000:0.000000 -inline-html-comments:0.080000:0.000000 -inline-html-simple:0.210000:0.000000 -links-inline:0.140000:0.000000 -links-reference:0.170000:0.000000 -literal-quotes:0.090000:0.000000 -markdown-documentation-basics:0.690000:1806336.000000 -markdown-syntax:3.310000:6696960.000000 -nested-blockquotes:0.200000:0.000000 -ordered-and-unordered-list:0.530000:0.000000 -strong-and-em-together:0.200000:0.000000 -tabs:0.200000:0.000000 -tidyness:0.200000:0.000000 diff --git a/tests/extensions/extra/test.cfg b/tests/extensions/extra/test.cfg deleted file mode 100644 index d956e2a1f..000000000 --- a/tests/extensions/extra/test.cfg +++ /dev/null @@ -1,36 +0,0 @@ -DEFAULT: - extensions: - - markdown.extensions.extra - -loose_def_list: - extensions: - - markdown.extensions.def_list - -simple_def-lists: - extensions: - - markdown.extensions.def_list - -abbr: - extensions: - - markdown.extensions.abbr - -footnotes: - extensions: - - markdown.extensions.footnotes - -tables: - extensions: - - markdown.extensions.tables - -tables_and_attr_list: - extensions: - - markdown.extensions.tables - - markdown.extensions.attr_list - -extra_config: - extensions: - - markdown.extensions.extra - extension_configs: - markdown.extensions.extra: - markdown.extensions.footnotes: - PLACE_MARKER: ~~~placemarker~~~ diff --git a/tests/extensions/test.cfg b/tests/extensions/test.cfg deleted file mode 100644 index ce66cfc5f..000000000 --- a/tests/extensions/test.cfg +++ /dev/null @@ -1,73 +0,0 @@ -attr_list: - extensions: - - markdown.extensions.attr_list - - markdown.extensions.def_list - - markdown.extensions.smarty - -codehilite: - extensions: - - markdown.extensions.codehilite - # This passes or not based on version of pygments. - skip: True - -toc: - extensions: - - markdown.extensions.toc - -toc_invalid: - extensions: - - markdown.extensions.toc - -toc_out_of_order: - extensions: - - markdown.extensions.toc - -toc_nested: - extensions: - - markdown.extensions.toc - extension_configs: - markdown.extensions.toc: - permalink: True - -toc_nested2: - extensions: - - markdown.extensions.toc - extension_configs: - markdown.extensions.toc: - permalink: "[link]" - -toc_nested_list: - extensions: - - markdown.extensions.toc - -wikilinks: - extensions: - - markdown.extensions.wikilinks - -fenced_code: - extensions: - - markdown.extensions.fenced_code - -github_flavored: - extensions: - - markdown.extensions.fenced_code - -sane_lists: - extensions: - - markdown.extensions.sane_lists - -nl2br_w_attr_list: - extensions: - - markdown.extensions.nl2br - - markdown.extensions.attr_list - -admonition: - extensions: - - markdown.extensions.admonition - -smarty: - extensions: - - markdown.extensions.smarty - extension_configs: - markdown.extensions.smarty: - smart_angled_quotes: True \ No newline at end of file diff --git a/tests/options/test.cfg b/tests/options/test.cfg deleted file mode 100644 index 2e14f1f45..000000000 --- a/tests/options/test.cfg +++ /dev/null @@ -1,11 +0,0 @@ -lazy_ol_off: - lazy_ol: False - -html4: - output_format: html4 - -no-attributes: - enable_attributes: False - -no-smart-emphasis: - smart_emphasis: False \ No newline at end of file diff --git a/tests/php/extra/test.cfg b/tests/php/extra/test.cfg deleted file mode 100644 index c6011d61d..000000000 --- a/tests/php/extra/test.cfg +++ /dev/null @@ -1,7 +0,0 @@ -DEFAULT: - extensions: - - extra - normalize: True - input_ext: .text - output_ext: .xhtml - skip: True diff --git a/tests/php/test.cfg b/tests/php/test.cfg deleted file mode 100644 index 70c260105..000000000 --- a/tests/php/test.cfg +++ /dev/null @@ -1,50 +0,0 @@ -DEFAULT: - normalize: True - input_ext: .text - output_ext: .xhtml - #skip: True - -Quotes in attributes: - # attributes get output in differant order - skip: True - -Inline HTML (Span): - # Backtick in raw HTML attribute TODO: fixme - skip: True - -Backslash escapes: - # Weird whitespace issue in output - skip: True - -Ins & del: - # Our behavior follows markdown.pl I think PHP is wrong here - skip: True - -Auto Links: - # TODO: fix raw HTML so is doesn't match as a
. - skip: True - -Empty List Item: - # We match markdown.pl here. Maybe someday we'll support this - skip: True - -Headers: - # TODO: fix headers to not require blank line before - skip: True - -Mixed OLs and ULs: - # We match markdown.pl here. I think PHP is wrong here - skip: True - -Emphasis: - # We have various minor differances in combined & incorrect em markup. - # Maybe fix a few of them - but most aren't too important - skip: True - -Code block in a list item: - # We match markdown.pl - not sure how php gets that output?? - skip: True - -PHP-Specific Bugs: - # Not sure what to make of the escaping stuff here. Why is PHP not removing a blackslash? - skip: True diff --git a/tests/pl/Tests_2004/test.cfg b/tests/pl/Tests_2004/test.cfg deleted file mode 100644 index 80f48e525..000000000 --- a/tests/pl/Tests_2004/test.cfg +++ /dev/null @@ -1,10 +0,0 @@ -DEFAULT: - input_ext: .text - normalize: True - # comment out next line to run these tests - #skip: True - -Yuri-Footnotes: - extensions: footnotes - skip: True - diff --git a/tests/pl/Tests_2007/test.cfg b/tests/pl/Tests_2007/test.cfg deleted file mode 100644 index 097aa0de9..000000000 --- a/tests/pl/Tests_2007/test.cfg +++ /dev/null @@ -1,25 +0,0 @@ -DEFAULT: - input_ext: .text - normalize: True - # comment out next line to run these tests - #skip: True - -Images: - # the attributes don't get ordered the same so we skip this - skip: True - -Code Blocks: - # some weird whitespace issue - skip: True - -Links, reference style: - # weird issue with nested brackets TODO: fixme - skip: True - -Backslash escapes: - # backticks in raw html attributes TODO: fixme - skip: True - -Code Spans: - # more backticks in raw html attributes TODO: fixme - skip: True diff --git a/tests/plugins.py b/tests/plugins.py deleted file mode 100644 index 4e7af97ae..000000000 --- a/tests/plugins.py +++ /dev/null @@ -1,127 +0,0 @@ -import traceback -from nose.plugins import Plugin -from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin - - -class MarkdownSyntaxError(Exception): - pass - - -class Markdown(ErrorClassPlugin): - """ Add MarkdownSyntaxError and ensure proper formatting. """ - mdsyntax = ErrorClass( - MarkdownSyntaxError, - label='MarkdownSyntaxError', - isfailure=True - ) - enabled = True - - def configure(self, options, conf): - self.conf = conf - - def addError(self, test, err): - """ Ensure other plugins see the error by returning nothing here. """ - pass - - def formatError(self, test, err): - """ Remove unnessecary and unhelpful traceback from error report. """ - et, ev, tb = err - if et.__name__ == 'MarkdownSyntaxError': - return et, ev, '' - return err - - -def escape(html): - """ Escape HTML for display as source within HTML. """ - html = html.replace('&', '&') - html = html.replace('<', '<') - html = html.replace('>', '>') - return html - - -class HtmlOutput(Plugin): - """Output test results as ugly, unstyled html. """ - - name = 'html-output' - score = 2 # run late - enabled = True - - def __init__(self): - super(HtmlOutput, self).__init__() - self.html = [ - '', - 'Test output', - '' - ] - - def configure(self, options, conf): - self.conf = conf - - def addSuccess(self, test): - self.html.append('ok') - - def addError(self, test, err): - err = self.formatErr(err) - self.html.append('ERROR') - self.html.append('
%s
' % escape(err)) - - def addFailure(self, test, err): - err = self.formatErr(err) - self.html.append('FAIL') - self.html.append('
%s
' % escape(err)) - - def finalize(self, result): - self.html.append('
') - self.html.append( - "Ran %d test%s" % - (result.testsRun, result.testsRun != 1 and "s" or "") - ) - self.html.append('
') - self.html.append('
') - if not result.wasSuccessful(): - self.html.extend(['FAILED (', - 'failures=%d ' % len(result.failures), - 'errors=%d' % len(result.errors)]) - for cls in list(result.errorClasses.keys()): - storage, label, isfail = result.errorClasses[cls] - if len(storage): - self.html.append(' %ss=%d' % (label, len(storage))) - self.html.append(')') - else: - self.html.append('OK') - self.html.append('
') - f = open('test-output.html', 'w') - for l in self.html: - f.write(l) - f.close() - - def formatErr(self, err): - exctype, value, tb = err - if not isinstance(value, exctype): - value = exctype(value) - return ''.join(traceback.format_exception(exctype, value, tb)) - - def startContext(self, ctx): - try: - n = ctx.__name__ - except AttributeError: - n = str(ctx).replace('<', '').replace('>', '') - self.html.extend(['
', '', n, '']) - try: - path = ctx.__file__.replace('.pyc', '.py') - self.html.extend(['
', path, '
']) - except AttributeError: - pass - - def stopContext(self, ctx): - self.html.append('
') - - def startTest(self, test): - self.html.extend([ - '
', - test.shortDescription() or str(test), - '' - ]) - - def stopTest(self, test): - self.html.append('
') diff --git a/tests/safe_mode/test.cfg b/tests/safe_mode/test.cfg deleted file mode 100644 index 4e1720e87..000000000 --- a/tests/safe_mode/test.cfg +++ /dev/null @@ -1,8 +0,0 @@ -DEFAULT: - safe_mode: escape - -remove: - safe_mode: remove - -replace: - safe_mode: replace diff --git a/tests/test_legacy.py b/tests/test_legacy.py new file mode 100644 index 000000000..17c428209 --- /dev/null +++ b/tests/test_legacy.py @@ -0,0 +1,213 @@ +from markdown.test_tools import LegacyTestCase, Kwargs +import os +import warnings + +# Warnings should cause tests to fail... +warnings.simplefilter('error') +# Except for the warnings that shouldn't +warnings.filterwarnings('default', category=PendingDeprecationWarning) +warnings.filterwarnings('default', category=DeprecationWarning, module='markdown') + +parent_test_dir = os.path.abspath(os.path.dirname(__file__)) + + +class TestBasic(LegacyTestCase): + location = os.path.join(parent_test_dir, 'basic') + + +class TestMisc(LegacyTestCase): + location = os.path.join(parent_test_dir, 'misc') + + +class TestOptions(LegacyTestCase): + location = os.path.join(parent_test_dir, 'options') + + lazy_ol_off = Kwargs(lazy_ol=False) + + html4 = Kwargs(output_format='html4') + + no_attributes = Kwargs(enable_attributes=False) + + no_smart_emphasis = Kwargs(smart_emphasis=False) + + +class TestSafeMode(LegacyTestCase): + location = os.path.join(parent_test_dir, 'safe_mode') + default_kwargs = Kwargs(safe_mode='escape') + + remove = Kwargs(safe_mode='remove') + + replace = Kwargs(safe_mode='replace') + + +class TestPhp(LegacyTestCase): + """ + Notes on "excluded" tests: + + Quotes in attributes: attributes get output in differant order + + Inline HTML (Span): Backtick in raw HTML attribute TODO: fixme + + Backslash escapes: Weird whitespace issue in output + + Ins & del: Our behavior follows markdown.pl I think PHP is wrong here + + Auto Links: TODO: fix raw HTML so is doesn't match as a
. + + Empty List Item: We match markdown.pl here. Maybe someday we'll support this + + Headers: TODO: fix headers to not require blank line before + + Mixed OLs and ULs: We match markdown.pl here. I think PHP is wrong here + + Emphasis: We have various minor differances in combined & incorrect em markup. + Maybe fix a few of them - but most aren't too important + + Code block in a list item: We match markdown.pl - not sure how php gets that output?? + + PHP-Specific Bugs: Not sure what to make of the escaping stuff here. + Why is PHP not removing a blackslash? + """ + location = os.path.join(parent_test_dir, 'php') + normalize = True + input_ext = '.text' + output_ext = '.xhtml' + exclude = [ + 'Quotes_in_attributes', + 'Inline_HTML_(Span)', + 'Backslash_escapes', + 'Ins_&_del', + 'Auto_Links', + 'Empty_List_Item', + 'Headers', + 'Mixed_OLs_and_ULs', + 'Emphasis', + 'Code_block_in_a_list_item', + 'PHP_Specific_Bugs' + ] + + +# class TestPhpExtra(LegacyTestCase): +# location = os.path.join(parent_test_dir, 'php/extra') +# normalize = True +# input_ext = '.text' +# output_ext = '.xhtml' +# default_kwargs = Kwargs(extensions=['extra']) + + +class TestPl2004(LegacyTestCase): + location = os.path.join(parent_test_dir, 'pl/Tests_2004') + normalize = True + input_ext = '.text' + exclude = ['Yuri_Footnotes'] + + +class TestPl2007(LegacyTestCase): + """ + Notes on "excluded" tests: + + Images: the attributes don't get ordered the same so we skip this + + Code Blocks: some weird whitespace issue + + Links, reference style: weird issue with nested brackets TODO: fixme + + Backslash escapes: backticks in raw html attributes TODO: fixme + + Code Spans: more backticks in raw html attributes TODO: fixme + """ + location = os.path.join(parent_test_dir, 'pl/Tests_2007') + normalize = True + input_ext = '.text' + exclude = [ + 'Images', + 'Code_Blocks', + 'Links,_reference_style', + 'Backslash_escapes', + 'Code_Spans' + ] + + +class TestExtensions(LegacyTestCase): + location = os.path.join(parent_test_dir, 'extensions') + exclude = ['codehilite'] + + attr_list = Kwargs( + extensions=[ + 'markdown.extensions.attr_list', + 'markdown.extensions.def_list', + 'markdown.extensions.smarty' + ] + ) + + codehilite = Kwargs(extensions=['markdown.extensions.codehilite']) + + toc = Kwargs(extensions=['markdown.extensions.toc']) + + toc_invalid = Kwargs(extensions=['markdown.extensions.toc']) + + toc_out_of_order = Kwargs(extensions=['markdown.extensions.toc']) + + toc_nested = Kwargs( + extensions=['markdown.extensions.toc'], + extension_configs={'markdown.extensions.toc': {'permalink': True}} + ) + + toc_nested2 = Kwargs( + extensions=['markdown.extensions.toc'], + extension_configs={'markdown.extensions.toc': {'permalink': "[link]"}} + ) + + toc_nested_list = Kwargs(extensions=['markdown.extensions.toc']) + + wikilinks = Kwargs(extensions=['markdown.extensions.wikilinks']) + + fenced_code = Kwargs(extensions=['markdown.extensions.fenced_code']) + + github_flavored = Kwargs(extensions=['markdown.extensions.fenced_code']) + + sane_lists = Kwargs(extensions=['markdown.extensions.sane_lists']) + + nl2br_w_attr_list = Kwargs( + extensions=[ + 'markdown.extensions.nl2br', + 'markdown.extensions.attr_list' + ] + ) + + admonition = Kwargs(extensions=['markdown.extensions.admonition']) + + smarty = Kwargs( + extensions=['markdown.extensions.smarty'], + extension_configs={'markdown.extensions.smarty': {'smart_angled_quotes': True}} + ) + + +class TestExtensionsExtra(LegacyTestCase): + location = os.path.join(parent_test_dir, 'extensions/extra') + default_kwargs = Kwargs(extensions=['markdown.extensions.extra']) + + loose_def_list = Kwargs(extensions=['markdown.extensions.def_list']) + + simple_def_lists = Kwargs(extensions=['markdown.extensions.def_list']) + + abbr = Kwargs(extensions=['markdown.extensions.abbr']) + + footnotes = Kwargs(extensions=['markdown.extensions.footnotes']) + + tables = Kwargs(extensions=['markdown.extensions.tables']) + + tables_and_attr_list = Kwargs( + extensions=['markdown.extensions.tables', 'markdown.extensions.attr_list'] + ) + + extra_config = Kwargs( + extensions=['markdown.extensions.extra'], + extension_configs={ + 'markdown.extensions.extra': { + 'markdown.extensions.footnotes': { + 'PLACE_MARKER': '~~~placemarker~~~' + } + } + } + ) diff --git a/tox.ini b/tox.ini index 89cc39775..7a415bf90 100644 --- a/tox.ini +++ b/tox.ini @@ -3,12 +3,12 @@ envlist = py27, py32, py33, py34, py35, py36, pypy, flake8, checkspelling [testenv] deps = -rtest-requirements.txt -commands = coverage run --source=markdown {toxinidir}/run-tests.py {posargs} +commands = coverage run --source=markdown -m unittest discover {toxinidir}/tests coverage report --show-missing [testenv:flake8] deps = flake8 -commands = flake8 {toxinidir}/markdown {toxinidir}/tests {toxinidir}/setup.py {toxinidir}/run-tests.py +commands = flake8 {toxinidir}/markdown {toxinidir}/tests {toxinidir}/setup.py [testenv:checkspelling] deps = From 0143d12b7a22467fc6d3473deb7cc64c5a96dda7 Mon Sep 17 00:00:00 2001 From: Waylan Limberg Date: Sat, 6 Jan 2018 18:31:26 -0500 Subject: [PATCH 3/3] Document the new test tools. --- .spell-dict | 2 + docs/change_log/release-2.1.md | 2 +- docs/test_suite.md | 138 -------------------------- docs/test_tools.md | 174 +++++++++++++++++++++++++++++++++ mkdocs.yml | 2 +- 5 files changed, 178 insertions(+), 140 deletions(-) delete mode 100644 docs/test_suite.md create mode 100644 docs/test_tools.md diff --git a/.spell-dict b/.spell-dict index 13a94393e..ab6b7a575 100644 --- a/.spell-dict +++ b/.spell-dict @@ -11,6 +11,7 @@ Blockprocessor Blockprocessors blockquote blockquotes +boolean CamelCase Chodarev CLI @@ -18,6 +19,7 @@ CodeHilite Cogumbreiro convertFile CSS +dedent deliminators Dmitry docdata diff --git a/docs/change_log/release-2.1.md b/docs/change_log/release-2.1.md index 30cf0b253..c8fa0e4e9 100644 --- a/docs/change_log/release-2.1.md +++ b/docs/change_log/release-2.1.md @@ -112,7 +112,7 @@ script to accept input on `stdin`. The testing framework has been completely rebuilt using the Nose testing framework. This provides a number of benefits including the ability to better test the built-in extensions and other options available to change the parsing -behavior. See the [Test Suite](../test_suite.md) documentation for details. +behavior. See the Test Suite documentation for details. Various bug fixes have been made, which are too numerous to list here. See the [commit log](https://github.com/Python-Markdown/markdown/commits/master) for a diff --git a/docs/test_suite.md b/docs/test_suite.md deleted file mode 100644 index 9ead4c605..000000000 --- a/docs/test_suite.md +++ /dev/null @@ -1,138 +0,0 @@ -title: Test Suite -prev_title: Extension API -prev_url: extensions/api.html -next_title: Change Log -next_url: change_log.html - -# Test Suite - -Python-Markdown comes with a test suite which uses the [Nose] testing -framework and [YAML]. The test suite primarily serves to ensure that new bugs -are not introduced as existing bugs are patched or new features are added. It -also allows Python-Markdown to be tested with the tests from other -implementations such as John Gruber's [Perl] implementation or Michel -Fortin's [PHP] implementation. - -The test suite can be run by calling the `run_tests.py` command at the root of -the distribution tarball or by calling the `nosetests` command directly. Either -way, Nose will need to be installed on your system first (run `easy_install -nose`). Any standard nosetests configuration options can be passed in on the command -line (i.e.: verbosity level or use of a plugin like coverage). - -Additionally, a nicely formatted HTML report of all output is written to a -temporary file in `test-output.html`. Open the file in a browser to view -the report. - -A `tox.ini` file is also provided, so [tox] can be used to automatically create -virtual environments, install all testing dependencies and run the tests on -each supported Python version. See the wiki for instructions on -[setting up a testing environment] to use tox. - -The test suite contains two kinds of tests: Markdown Syntax Tests and Unit -Tests. - -## Markdown Syntax Tests - -The Syntax Tests are in the various directories contained within the 'tests' -directory of the packaged tarball. Each test consists of a matching pair of text -and HTML files. The text file contains a snippet of Markdown source text -formatted for a specific syntax feature and the HTML file contains the expected -HTML output of that snippet. When the test suite is run, each text file is run -through Markdown and the output is compared with the HTML file as a separate -Unit Test. - -In fact, this is the primary reason for using Nose, it gives us an easy way to -treat each of these tests as a separate unit test which is reported on -separately. Additionally, with the help of a couple custom Nose plugins which -are included with the Markdown Test Suite, we are able to get back an easy to -read diff of the actual output compared to expected output when a test fails. - -Here is some sample output with a test that is failing because of some -insignificant white space differences: - - $ ./run-tests.py - ..........................................................M........... - ............................SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS - SSSSSSSSSS.................S.......................................... - ......... - ====================================================================== - MarkdownSyntaxError: TestSyntax: "misc/lists3" - ---------------------------------------------------------------------- - MarkdownSyntaxError: Output from "/home/waylan/code/python-markdown/te - sts/misc/lists3.txt" failed to match expected output. - - --- /home/waylan/code/python-markdown/tests/misc/lists3.html - +++ actual_output.html - @@ -1,5 +1,5 @@ -
    -
  • blah blah blah - -sdf asdf asdf asdf asdf - -asda asdf asdfasd
  • - + sdf asdf asdf asdf asdf - + asda asdf asdfasd -
- - ---------------------------------------------------------------------- - Ran 219 tests in 7.698s - - FAILED (MarkdownSyntaxError=1, SKIP=53) - -Note that 219 tests were run, one of which failed with a `MarkdownSyntaxError`. -Only Markdown Syntax Tests should fail with a `MarkdownSyntaxError`. Nose then -formats the error reports for `MarkdownSyntaxError`s so that they only include -useful information. Namely the text file which failed and a unified diff showing -the failure. Without the plugin, you would also get a useless traceback showing -how the code stepped through the test framework, but nothing about how Markdown -actually ran. - -If, on the other hand, a Syntax Test failed because some other exception gets -raised by either Markdown or the test suite, then that would be reported as per -a normal unit test failure with the appropriate traceback for debugging -purposes. - -### Syntax Test Configuration Settings - -The other thing to note about the above example is that 53 tests were skipped. -Those tests have been explicitly configured to be skipped as they are primarily -tests from either PHP or Perl which are known to fail for various reasons. In -fact, a number of different configuration settings can be set for any specific -test. - -Each Syntax Test directory contains a `test.cfg` file in the [YAML] format. The -file may contain a separate section for each text file named exactly as the file -is named minus the file extension (i.e.; the section for a test in `foo.txt` -would be `foo`). All settings are optional. Default settings for the entire -directory can be set under the `DEFAULT` section (must be all caps). Any -settings under a specific file section will override anything in the -`DEFAULT` section for that specific test only. - -Below are the configuration options available and the defaults used when they -are not explicitly set. - -* `normalize`: Switches white space normalization of the test output on or off. - Defaults to `False` (off). Note: This requires that [PyTidyLib] be installed - on the system. Otherwise the test will be skipped, regardless of any other - settings. -* `skip`: Switches skipping of the test on and off. Defaults to `False` (off). -* `input_ext`: Extension of input file. Defaults to `.txt`. Useful for tests - from other implementations. -* `output_ext`: Extension of output file. Defaults to `.html`. Useful for tests - from other implementations. -* Any keyword argument accepted by the Markdown class. If not set, Markdown's - defaults are used. - -## Unit Tests - -Unit Tests are used as regression tests for Python-Markdown's API. -All Unit Tests shipped with Python-Markdown are standard Python Unit Tests and -are all contained in `tests/test_apis.py` and `tests/test_extensions.py`. -Standard discovery methods are used to find and run the tests. Therefore, when -writing new tests, those standards and naming conventions should be followed. - -[Nose]: http://somethingaboutorange.com/mrl/projects/nose/ -[Perl]: http://daringfireball.net/projects/markdown/ -[PHP]: http://michelf.com/projects/php-markdown/ -[PyTidyLib]: http://countergram.com/open-source/pytidylib/ -[tox]: http://testrun.org/tox/latest/ -[setting up a testing environment]: https://github.com/Python-Markdown/markdown/wiki/Test-Environment-Setup -[YAML]: http://yaml.org/ diff --git a/docs/test_tools.md b/docs/test_tools.md new file mode 100644 index 000000000..c2d595108 --- /dev/null +++ b/docs/test_tools.md @@ -0,0 +1,174 @@ +title: Test Tools + +# Test Tools + +Python-Markdown provides some testing tools which simplify testing actual +Markdown output again expected output. The tools are built on the Python +standard library [`unittest`][unittest]. Therefore, no additional libraries are +required. While Python-Markdown uses the tools for its own tests, they were +designed and built so that third party extensions could use them as well. +Therefore, the tools are importable from `markdown.test_tools`. + +The test tools include two different `unittest.TestCase` subclasses: +`markdown.test_tools.TestCase` and `markdown.test_tools.LegacyTestCase`. + +## markdown.test_tools.TestCase + +The `markdown.test_tools.TestCase` class is a `unittest.TestCase` subclass with +a few additional helpers to make testing Markdown output easier. + +Properties +: `default_kwargs`: A `dict` of keywords to pass to Markdown for each +test. The defaults can be overridden on individual tests. + +Methods +: `assertMarkdownRenders`: accepts the source text, the expected output, + and any keywords to pass to Markdown. The `default_kwargs` defined on the + class are used except where overridden by keyword arguments. The output and + expected output are passed to `TestCase.assertMultiLineEqual`. An + `AssertionError` is raised with a diff if the actual output does not equal the + expected output. + +: `dedent`: Dedent triple-quoted strings. + +In all other respects, `markdown.test_tools.TestCase` behaves as +`unittest.TestCase`. In fact, `assertMarkdownRenders` tests could be mixed with +other `unittest` style tests within the same test class. + +An example Markdown test might look like this: + +```python +from markdown.test_tools import TestCase + +class TestHr(TestCase): + def test_hr_before_paragraph(self): + self.assertMarkdownRenders( + # The Markdown source text used as input + self.dedent( + """ + *** + An HR followed by a paragraph with no blank line. + """ + ), + # The expected HTML output + self.dedent( + """ +
+

An HR followed by a paragraph with no blank line.

+ """ + ), + # Other keyword arguments to pass to `markdown.markdown` + output_format='html' + ) +``` + +## markdown.test_tools.LegacyTestCase + +In the past Python-Markdown exclusively used file-based tests. Many of those +tests still exist in Python-Markdown's test suite, including the test files from +the [reference implementation][perl] (`markdown.pl`) and [PHP Markdown][PHP]. +Each test consists of a matching pair of text and HTML files. The text file +contains a snippet of Markdown source text formatted for a specific syntax +feature and the HTML file contains the expected HTML output of that snippet. +When the test suite is run, each text file is run through Markdown and the +output is compared with the HTML file as a separate unit test. When a test +fails, the error report includes a diff of the expected output compared to the +actual output to easily identify any problems. + +A separate `markdown.test_tools.LegacyTestCase` subclass must be created for +each directory of test files. Various properties can be defined within the +subclass to point to a directory of text-based test files and define various +behaviors/defaults for those tests. The following properties are supported: + +* `location`: A path to the directory of test files. An absolute path is + preferred. +* `exclude`: A list of tests to skip. Each test name should comprise of a + file name without an extension. +* `normalize`: A boolean value indicating if the HTML should be normalized. + Default: `False`. Note: Normalization of HTML requires that [PyTidyLib] be + installed on the system. If PyTidyLib is not installed and `normalize` is set + to `True`, then the test will be skipped, regardless of any other settings. +* `input_ext`: A string containing the file extension of input files. + Default: `.txt`. +* `output_ext`: A string containing the file extension of expected output files. + Default: `html`. +* `default_kwargs`: A `markdown.test_tools.Kwargs` instance which stores the + default set of keyword arguments for all test files in the directory. + +In addition, properties can be defined for each individual set of test files +within the directory. The property should be given the name of the file without +the file extension. Any spaces and dashes in the file name should be replaced +with underscores. The value of the property should be a +`markdown.test_tools.Kwargs` instance which contains the keyword arguments that +should be passed to `markdown.markdown` for that test file. The keyword +arguments will "update" the `default_kwargs`. + +When the class instance is created during a test run, it will walk the given +directory and create a separate unit test for each set of test files using the +naming scheme: `test_filename`. One unit test will be run for each set of input +and output files. + +The definition of an example set of tests might look like this: + +```python +from markdown.test_tools import LegacyTestCase, Kwargs +import os + +# Get location of this file and use to find text file dirs. +parent_test_dir = os.path.abspath(os.path.dirname(__file__)) + + +class TestFoo(LegacyTestCase): + # Define location of text file directory. In this case, the directory is + # named "foo" and is in the same parent directory as this file. + location = os.path.join(parent_test_dir, 'foo') + # Define default keyword arguments. In this case, unless specified + # differently, all tests should use the output format "html". + default_kwargs = Kwargs(output_format='html') + + # The "xhtml" test should override the output format and use "xhtml". + xhtml = Kwargs(output_format='xhtml') + + # The "toc" test should use the "toc" extension with a custom permalink + # setting. + toc = Kwargs( + extensions=['markdown.extensions.toc'], + extension_configs={'markdown.extensions.toc': {'permalink': "[link]"}} + ) +``` + +Note that in the above example, the text file directory may contain many more +text-based test files than `xhtml` (`xhtml.txt` and `xhtml.html`) and `toc` +(`toc.txt` and `toc.html`). As long as each set of files exists as a pair, a +test will be created and run for each of them. Only the `xhtml` and `toc` tests +needed to be specifically identified as they had specific, non-default settings +which needed to be defined. + +## Running Python-Markdown's Tests + +As all of the tests for the `markdown` library are unit tests, standard +`unittest` methods of calling tests can be used. For example, to run all of +Python-Markdown's tests, from the root of the git repository, run the following +command: + +```sh +python -m unittest discover tests +``` + +That simple command will search everything in the `tests` directory and it's +sub-directories and run all `unittest` tests that it finds, including +`unittest.TestCase`, `markdown.test_tools.TestCase`, and +`markdown.test_tools.LegacyTestCase` subclasses. Normal `unittest` discovery +rules apply. + +Python-Markdown's git repository also includes a `tox.ini` file, so [tox] can be +used to automate the creation of virtual environments, installation of all +testing dependencies and running of the tests on each supported Python version. +See the wiki for instructions on [setting up a testing environment] to use tox. + +[unittest]: https://docs.python.org/3/library/unittest.html +[Perl]: http://daringfireball.net/projects/markdown/ +[PHP]: http://michelf.com/projects/php-markdown/ +[PyTidyLib]: http://countergram.com/open-source/pytidylib/ +[tox]: http://testrun.org/tox/latest/ +[setting up a testing environment]: https://github.com/Python-Markdown/markdown/wiki/Test-Environment-Setup diff --git a/mkdocs.yml b/mkdocs.yml index 95fa9a780..c915bee47 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -37,7 +37,7 @@ pages: - Tables: extensions/tables.md - WikiLinks: extensions/wikilinks.md - Extension API: extensions/api.md - - Test Suite: test_suite.md + - Test Tools: test_tools.md - Change Log: change_log/index.md - Release Notes for v.2.6: change_log/release-2.6.md - Release Notes for v.2.5: change_log/release-2.5.md