Debian Codegraph @

markdown/test_tools.py

raw
1 # Python Markdown
2
3 # A Python implementation of John Gruber's Markdown.
4
5 # Documentation: https://python-markdown.github.io/
6 # GitHub: https://github.com/Python-Markdown/markdown/
7 # PyPI: https://pypi.org/project/Markdown/
8
9 # Started by Manfred Stienstra (http://www.dwerg.net/).
10 # Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
11 # Currently maintained by Waylan Limberg (https://github.com/waylan),
12 # Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
13
14 # Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
15 # Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
16 # Copyright 2004 Manfred Stienstra (the original version)
17
18 # License: BSD (see LICENSE.md for details).
19
20 """ A collection of tools for testing the Markdown code base and extensions. """
21
22 from __future__ import annotations
23
24 import os
25 import sys
26 import unittest
27 import textwrap
28 from typing import Any
29 from . import markdown, Markdown, util
30
31 try:
32 import tidylib
33 except ImportError:
34 tidylib = None
35
36 __all__ = ['TestCase', 'LegacyTestCase', 'Kwargs']
37
38
39 class TestCase(unittest.TestCase):
40 """
41 A [`unittest.TestCase`][] subclass with helpers for testing Markdown output.
42
43 Define `default_kwargs` as a `dict` of keywords to pass to Markdown for each
44 test. The defaults can be overridden on individual tests.
45
46 The `assertMarkdownRenders` method accepts the source text, the expected
47 output, and any keywords to pass to Markdown. The `default_kwargs` are used
48 except where overridden by `kwargs`. The output and expected output are passed
49 to `TestCase.assertMultiLineEqual`. An `AssertionError` is raised with a diff
50 if the actual output does not equal the expected output.
51
52 The `dedent` method is available to dedent triple-quoted strings if
53 necessary.
54
55 In all other respects, behaves as `unittest.TestCase`.
56 """
57
58 default_kwargs: dict[str, Any] = {}
59 """ Default options to pass to Markdown for each test. """
60
61 def assertMarkdownRenders(self, source, expected, expected_attrs=None, **kwargs):
62 """
63 Test that source Markdown text renders to expected output with given keywords.
64
65 `expected_attrs` accepts a `dict`. Each key should be the name of an attribute
66 on the `Markdown` instance and the value should be the expected value after
67 the source text is parsed by Markdown. After the expected output is tested,
68 the expected value for each attribute is compared against the actual
69 attribute of the `Markdown` instance using `TestCase.assertEqual`.
70 """
71
72 expected_attrs = expected_attrs or {}
73 kws = self.default_kwargs.copy()
74 kws.update(kwargs)
75 md = Markdown(**kws)
76 output = md.convert(source)
77 self.assertMultiLineEqual(output, expected)
78 for key, value in expected_attrs.items():
79 self.assertEqual(getattr(md, key), value)
80
81 def dedent(self, text):
82 """
83 Dedent text.
84 """
85
86 # TODO: If/when actual output ends with a newline, then use:
87 # return textwrap.dedent(text.strip('/n'))
88 return textwrap.dedent(text).strip()
89
90
91 class recursionlimit:
92 """
93 A context manager which temporarily modifies the Python recursion limit.
94
95 The testing framework, coverage, etc. may add an arbitrary number of levels to the depth. To maintain consistency
96 in the tests, the current stack depth is determined when called, then added to the provided limit.
97
98 Example usage:
99
100 ``` python
101 with recursionlimit(20):
102 # test code here
103 ```
104
105 See <https://stackoverflow.com/a/50120316/866026>.
106 """
107
108 def __init__(self, limit):
109 self.limit = util._get_stack_depth() + limit
110 self.old_limit = sys.getrecursionlimit()
111
112 def __enter__(self):
113 sys.setrecursionlimit(self.limit)
114
115 def __exit__(self, type, value, tb):
116 sys.setrecursionlimit(self.old_limit)
117
118
119 #########################
120 # Legacy Test Framework #
121 #########################
122
123
124 class Kwargs(dict):
125 """ A `dict` like class for holding keyword arguments. """
126 pass
127
128
129 def _normalize_whitespace(text):
130 """ Normalize whitespace for a string of HTML using `tidylib`. """
131 output, errors = tidylib.tidy_fragment(text, options={
132 'drop_empty_paras': 0,
133 'fix_backslash': 0,
134 'fix_bad_comments': 0,
135 'fix_uri': 0,
136 'join_styles': 0,
137 'lower_literals': 0,
138 'merge_divs': 0,
139 'output_xhtml': 1,
140 'quote_ampersand': 0,
141 'newline': 'LF'
142 })
143 return output
144
145
146 class LegacyTestMeta(type):
147 def __new__(cls, name, bases, dct):
148
149 def generate_test(infile, outfile, normalize, kwargs):
150 def test(self):
151 with open(infile, encoding="utf-8") as f:
152 input = f.read()
153 with open(outfile, encoding="utf-8") as f:
154 # Normalize line endings
155 # (on Windows, git may have altered line endings).
156 expected = f.read().replace("\r\n", "\n")
157 output = markdown(input, **kwargs)
158 if tidylib and normalize:
159 try:
160 expected = _normalize_whitespace(expected)
161 output = _normalize_whitespace(output)
162 except OSError:
163 self.skipTest("Tidylib's c library not available.")
164 elif normalize:
165 self.skipTest('Tidylib not available.')
166 self.assertMultiLineEqual(output, expected)
167 return test
168
169 location = dct.get('location', '')
170 exclude = dct.get('exclude', [])
171 normalize = dct.get('normalize', False)
172 input_ext = dct.get('input_ext', '.txt')
173 output_ext = dct.get('output_ext', '.html')
174 kwargs = dct.get('default_kwargs', Kwargs())
175
176 if os.path.isdir(location):
177 for file in os.listdir(location):
178 infile = os.path.join(location, file)
179 if os.path.isfile(infile):
180 tname, ext = os.path.splitext(file)
181 if ext == input_ext:
182 outfile = os.path.join(location, tname + output_ext)
183 tname = tname.replace(' ', '_').replace('-', '_')
184 kws = kwargs.copy()
185 if tname in dct:
186 kws.update(dct[tname])
187 test_name = 'test_%s' % tname
188 if tname not in exclude:
189 dct[test_name] = generate_test(infile, outfile, normalize, kws)
190 else:
191 dct[test_name] = unittest.skip('Excluded')(lambda: None)
192
193 return type.__new__(cls, name, bases, dct)
194
195
196 class LegacyTestCase(unittest.TestCase, metaclass=LegacyTestMeta):
197 """
198 A [`unittest.TestCase`][] subclass for running Markdown's legacy file-based tests.
199
200 A subclass should define various properties which point to a directory of
201 text-based test files and define various behaviors/defaults for those tests.
202 The following properties are supported:
203
204 Attributes:
205 location (str): A path to the directory of test files. An absolute path is preferred.
206 exclude (list[str]): A list of tests to exclude. Each test name should comprise the filename
207 without an extension.
208 normalize (bool): A boolean value indicating if the HTML should be normalized. Default: `False`.
209 input_ext (str): A string containing the file extension of input files. Default: `.txt`.
210 output_ext (str): A string containing the file extension of expected output files. Default: `html`.
211 default_kwargs (Kwargs[str, Any]): The default set of keyword arguments for all test files in the directory.
212
213 In addition, properties can be defined for each individual set of test files within
214 the directory. The property should be given the name of the file without the file
215 extension. Any spaces and dashes in the filename should be replaced with
216 underscores. The value of the property should be a `Kwargs` instance which
217 contains the keyword arguments that should be passed to `Markdown` for that
218 test file. The keyword arguments will "update" the `default_kwargs`.
219
220 When the class instance is created, it will walk the given directory and create
221 a separate `Unitttest` for each set of test files using the naming scheme:
222 `test_filename`. One `Unittest` will be run for each set of input and output files.
223 """
224 pass