diff --git a/markdown/__init__.py b/markdown/__init__.py index 1b8655313..7d116821b 100644 --- a/markdown/__init__.py +++ b/markdown/__init__.py @@ -117,7 +117,7 @@ def __init__(self, *args, **kwargs): for c, arg in enumerate(args): if pos[c] not in kwargs: kwargs[pos[c]] = arg - if c+1 == len(pos): # pragma: no cover + if c + 1 == len(pos): # pragma: no cover # ignore any additional args break if len(args): @@ -209,7 +209,7 @@ def build_extension(self, ext_name, configs): # Parse extensions config params (ignore the order) pos = ext_name.find("(") # find the first "(" if pos > 0: - ext_args = ext_name[pos+1:-1] + ext_args = ext_name[pos + 1:-1] ext_name = ext_name[:pos] pairs = [x.split("=") for x in ext_args.split(",")] configs.update([(x.strip(), y.strip()) for (x, y) in pairs]) @@ -235,7 +235,7 @@ def build_extension(self, ext_name, configs): # For backward compat (until deprecation) # check that this is an extension. if ('.' not in ext_name and not (hasattr(module, 'makeExtension') or - (class_name and hasattr(module, class_name)))): + (class_name and hasattr(module, class_name)))): # We have a name conflict # eg: extensions=['tables'] and PyTables is installed raise ImportError diff --git a/markdown/__main__.py b/markdown/__main__.py index 17bfa9f3c..43d4e8d29 100644 --- a/markdown/__main__.py +++ b/markdown/__main__.py @@ -60,7 +60,7 @@ def parse_options(args=None, values=None): "`--extension` option.", metavar="CONFIG_FILE") parser.add_option("-q", "--quiet", default=CRITICAL, - action="store_const", const=CRITICAL+10, dest="verbose", + action="store_const", const=CRITICAL + 10, dest="verbose", help="Suppress all warnings.") parser.add_option("-v", "--verbose", action="store_const", const=WARNING, dest="verbose", diff --git a/markdown/blockprocessors.py b/markdown/blockprocessors.py index 870151bec..bcbb381d5 100644 --- a/markdown/blockprocessors.py +++ b/markdown/blockprocessors.py @@ -65,7 +65,7 @@ def detab(self, text): newtext = [] lines = text.split('\n') for line in lines: - if line.startswith(' '*self.tab_length): + if line.startswith(' ' * self.tab_length): newtext.append(line[self.tab_length:]) elif not line.strip(): newtext.append('') @@ -77,8 +77,8 @@ def looseDetab(self, text, level=1): """ Remove a tab from front of lines but allowing dedented lines. """ lines = text.split('\n') for i in range(len(lines)): - if lines[i].startswith(' '*self.tab_length*level): - lines[i] = lines[i][self.tab_length*level:] + if lines[i].startswith(' ' * self.tab_length * level): + lines[i] = lines[i][self.tab_length * level:] return '\n'.join(lines) def test(self, parent, block): @@ -145,7 +145,7 @@ def __init__(self, *args): self.INDENT_RE = re.compile(r'^(([ ]{%s})+)' % self.tab_length) def test(self, parent, block): - return block.startswith(' '*self.tab_length) and \ + return block.startswith(' ' * self.tab_length) and \ not self.parser.state.isstate('detabbed') and \ (parent.tag in self.ITEM_TYPES or (len(parent) and parent[-1] is not None and @@ -197,7 +197,7 @@ def get_level(self, parent, block): # Get indent level m = self.INDENT_RE.match(block) if m: - indent_level = len(m.group(1))/self.tab_length + indent_level = len(m.group(1)) / self.tab_length else: indent_level = 0 if self.parser.state.isstate('list'): @@ -210,7 +210,7 @@ def get_level(self, parent, block): while indent_level > level: child = self.lastChild(parent) if (child is not None and - (child.tag in self.LIST_TYPES or child.tag in self.ITEM_TYPES)): + (child.tag in self.LIST_TYPES or child.tag in self.ITEM_TYPES)): if child.tag in self.LIST_TYPES: level += 1 parent = child @@ -225,14 +225,14 @@ class CodeBlockProcessor(BlockProcessor): """ Process code blocks. """ def test(self, parent, block): - return block.startswith(' '*self.tab_length) + return block.startswith(' ' * self.tab_length) def run(self, parent, blocks): sibling = self.lastChild(parent) block = blocks.pop(0) theRest = '' if (sibling is not None and sibling.tag == "pre" and - len(sibling) and sibling[0].tag == "code"): + len(sibling) and sibling[0].tag == "code"): # The previous block was a code block. As blank lines do not start # new code blocks, append this block to the previous, adding back # linebreaks removed from the split into a list. @@ -311,7 +311,8 @@ class OListProcessor(BlockProcessor): def __init__(self, parser): super(OListProcessor, self).__init__(parser) # Detect an item (``1. item``). ``group(1)`` contains contents of item. - self.RE = re.compile(r'^[ ]{0,%d}\d+\.[ ]+(.*)' % (self.tab_length - 1)) + self.RE = re.compile(r'^[ ]{0,%d}\d+\.[ ]+(.*)' % + (self.tab_length - 1)) # Detect items on secondary lines. they can be of either list type. self.CHILD_RE = re.compile(r'^[ ]{0,%d}((\d+\.)|[*+-])[ ]+(.*)' % (self.tab_length - 1)) @@ -372,7 +373,7 @@ def run(self, parent, blocks): # Loop through items in block, recursively parsing each with the # appropriate parent. for item in items: - if item.startswith(' '*self.tab_length): + if item.startswith(' ' * self.tab_length): # Item is indented. Parse with last item as parent self.parser.parseBlocks(lst[-1], [item]) else: @@ -397,7 +398,7 @@ def get_items(self, block): items.append(m.group(3)) elif self.INDENT_RE.match(line): # This is an indented (possibly nested) item. - if items[-1].startswith(' '*self.tab_length): + if items[-1].startswith(' ' * self.tab_length): # Previous item was indented. Append to that item. items[-1] = '%s\n%s' % (items[-1], line) else: @@ -416,7 +417,8 @@ class UListProcessor(OListProcessor): def __init__(self, parser): super(UListProcessor, self).__init__(parser) # Detect an item (``1. item``). ``group(1)`` contains contents of item. - self.RE = re.compile(r'^[ ]{0,%d}[*+-][ ]+(.*)' % (self.tab_length - 1)) + self.RE = re.compile(r'^[ ]{0,%d}[*+-][ ]+(.*)' % + (self.tab_length - 1)) class HashHeaderProcessor(BlockProcessor): @@ -527,7 +529,7 @@ def run(self, parent, blocks): blocks.insert(0, theRest) sibling = self.lastChild(parent) if (sibling is not None and sibling.tag == 'pre' and - len(sibling) and sibling[0].tag == 'code'): + len(sibling) and sibling[0].tag == 'code'): # Last block is a codeblock. Append to preserve whitespace. sibling[0].text = util.AtomicString( '%s%s' % (sibling[0].text, filler) diff --git a/markdown/extensions/attr_list.py b/markdown/extensions/attr_list.py index 683bdf831..7247e8155 100644 --- a/markdown/extensions/attr_list.py +++ b/markdown/extensions/attr_list.py @@ -104,12 +104,12 @@ def run(self, doc): if m: self.assign_attrs(elem, m.group(1)) elem[-1].tail = elem[-1].tail[:m.start()] - elif pos is not None and pos > 0 and elem[pos-1].tail: + elif pos is not None and pos > 0 and elem[pos - 1].tail: # use tail of last child before ul or ol - m = RE.search(elem[pos-1].tail) + m = RE.search(elem[pos - 1].tail) if m: self.assign_attrs(elem, m.group(1)) - elem[pos-1].tail = elem[pos-1].tail[:m.start()] + elem[pos - 1].tail = elem[pos - 1].tail[:m.start()] elif elem.text: # use text. ul is first child. m = RE.search(elem.text) @@ -167,6 +167,7 @@ def sanitize_name(self, name): class AttrListExtension(Extension): + def extendMarkdown(self, md, md_globals): md.treeprocessors.add( 'attr_list', AttrListTreeprocessor(md), '>prettify' diff --git a/markdown/extensions/codehilite.py b/markdown/extensions/codehilite.py index 0657c3768..723148d3b 100644 --- a/markdown/extensions/codehilite.py +++ b/markdown/extensions/codehilite.py @@ -248,7 +248,7 @@ def __init__(self, *args, **kwargs): 'Use Pygments to Highlight code blocks. ' 'Disable if using a JavaScript library. ' 'Default: True'] - } + } super(CodeHiliteExtension, self).__init__(*args, **kwargs) diff --git a/markdown/extensions/extra.py b/markdown/extensions/extra.py index de5db03cd..fac7644a1 100644 --- a/markdown/extensions/extra.py +++ b/markdown/extensions/extra.py @@ -75,6 +75,7 @@ def makeExtension(*args, **kwargs): class MarkdownInHtmlProcessor(BlockProcessor): """Process Markdown Inside HTML Blocks.""" + def test(self, parent, block): return block == util.TAG_PLACEHOLDER % \ str(self.parser.blockprocessors.tag_counter + 1) diff --git a/markdown/extensions/footnotes.py b/markdown/extensions/footnotes.py index b52815f3c..ab17fe65b 100644 --- a/markdown/extensions/footnotes.py +++ b/markdown/extensions/footnotes.py @@ -151,7 +151,7 @@ def makeFootnotesDiv(self, root): backlink.set( "title", "Jump back to footnote %d in the text" % - (self.footnotes.index(id)+1) + (self.footnotes.index(id) + 1) ) backlink.text = FN_BACKLINK_TEXT @@ -188,13 +188,13 @@ def run(self, lines): while True: m = DEF_RE.match(lines[i]) if m: - fn, _i = self.detectTabbed(lines[i+1:]) + fn, _i = self.detectTabbed(lines[i + 1:]) fn.insert(0, m.group(2)) - i += _i-1 # skip past footnote + i += _i - 1 # skip past footnote self.footnotes.setFootnote(m.group(1), "\n".join(fn)) else: newlines.append(lines[i]) - if len(lines) > i+1: + if len(lines) > i + 1: i += 1 else: break @@ -232,7 +232,7 @@ def detab(line): i += 1 continue else: - return items, i+1 + return items, i + 1 else: # Blank line: _maybe_ we are done. blank_line = True @@ -306,6 +306,7 @@ def run(self, root): class FootnotePostprocessor(Postprocessor): """ Replace placeholders with html entities. """ + def __init__(self, footnotes): self.footnotes = footnotes diff --git a/markdown/extensions/headerid.py b/markdown/extensions/headerid.py index 2cb20b97a..5fd721562 100644 --- a/markdown/extensions/headerid.py +++ b/markdown/extensions/headerid.py @@ -39,7 +39,8 @@ def run(self, doc): if "id" in elem.attrib: id = elem.get('id') else: - id = stashedHTML2text(''.join(elem.itertext()), self.md) + id = stashedHTML2text( + ''.join(elem.itertext()), self.md) id = slugify(id, sep) elem.set('id', unique(id, self.IDs)) if start_level: @@ -61,6 +62,7 @@ def _get_meta(self): class HeaderIdExtension(Extension): + def __init__(self, *args, **kwargs): # set defaults self.config = { diff --git a/markdown/extensions/smarty.py b/markdown/extensions/smarty.py index 600d74cd6..839d15dd8 100644 --- a/markdown/extensions/smarty.py +++ b/markdown/extensions/smarty.py @@ -151,6 +151,7 @@ class SubstituteTextPattern(HtmlPattern): + def __init__(self, pattern, replace, markdown_instance): """ Replaces matches with some text. """ HtmlPattern.__init__(self, pattern) @@ -168,6 +169,7 @@ def handleMatch(self, m): class SmartyExtension(Extension): + def __init__(self, *args, **kwargs): self.config = { 'smart_quotes': [True, 'Educate quotes'], diff --git a/markdown/extensions/tables.py b/markdown/extensions/tables.py index 39c09a46a..84df1b9b5 100644 --- a/markdown/extensions/tables.py +++ b/markdown/extensions/tables.py @@ -97,7 +97,8 @@ def _split(self, row, marker): if self._row_has_unpaired_backticks(row): # fallback on old behaviour return row.split(marker) - # modify the backtick pattern to only match at the beginning of the search string + # modify the backtick pattern to only match at the beginning of the + # search string backtick_pattern = BacktickPattern('^' + BACKTICK_RE) elements = [] current = '' @@ -108,7 +109,8 @@ def _split(self, row, marker): if current != '' or len(elements) == 0: # Don't append empty string unless it is the first element # The border is already removed when we get the row, then the line is strip()'d - # If the first element is a marker, then we have an empty first cell + # If the first element is a marker, then we have an empty + # first cell elements.append(current) current = '' else: @@ -117,9 +119,13 @@ def _split(self, row, marker): current += letter else: groups = match.groups() - delim = groups[1] # the code block delimeter (ie 1 or more backticks) - row_contents = groups[2] # the text contained inside the code block - i += match.start(4) - 1 # jump pointer to the beginning of the rest of the text (group #4) + # the code block delimeter (ie 1 or more backticks) + delim = groups[1] + # the text contained inside the code block + row_contents = groups[2] + # jump pointer to the beginning of the rest of the text + # (group #4) + i += match.start(4) - 1 element = delim + row_contents + delim # reinstert backticks current += element i += 1 diff --git a/markdown/extensions/toc.py b/markdown/extensions/toc.py index 56db33c50..573c84cfa 100644 --- a/markdown/extensions/toc.py +++ b/markdown/extensions/toc.py @@ -37,7 +37,7 @@ def unique(id, ids): while id in ids or not id: m = IDCOUNT_RE.match(id) if m: - id = '%s_%d' % (m.group(1), int(m.group(2))+1) + id = '%s_%d' % (m.group(1), int(m.group(2)) + 1) else: id = '%s_%d' % (id, 1) ids.add(id) @@ -124,6 +124,7 @@ def nest_toc_tokens(toc_list): class TocTreeprocessor(Treeprocessor): + def __init__(self, md, config): super(TocTreeprocessor, self).__init__(md) @@ -239,7 +240,8 @@ def run(self, doc): # Do not override pre-existing ids if "id" not in el.attrib: innertext = stashedHTML2text(text, self.markdown) - el.attrib["id"] = unique(self.slugify(innertext, self.sep), used_ids) + el.attrib["id"] = unique( + self.slugify(innertext, self.sep), used_ids) toc_tokens.append({ 'level': int(el.tag[-1]), diff --git a/markdown/extensions/wikilinks.py b/markdown/extensions/wikilinks.py index 94e1b6794..5532a4643 100644 --- a/markdown/extensions/wikilinks.py +++ b/markdown/extensions/wikilinks.py @@ -52,6 +52,7 @@ def extendMarkdown(self, md, md_globals): class WikiLinks(Pattern): + def __init__(self, pattern, config): super(WikiLinks, self).__init__(pattern) self.config = config diff --git a/markdown/inlinepatterns.py b/markdown/inlinepatterns.py index dcf4ad47c..15cf93dd3 100644 --- a/markdown/inlinepatterns.py +++ b/markdown/inlinepatterns.py @@ -95,8 +95,8 @@ def build_inlinepatterns(md_instance, **kwargs): NOBRACKET = r'[^\]\[]*' BRK = ( r'\[(' + - (NOBRACKET + r'(\[')*6 + - (NOBRACKET + r'\])*')*6 + + (NOBRACKET + r'(\[') * 6 + + (NOBRACKET + r'\])*') * 6 + NOBRACKET + r')\]' ) NOIMG = r'(?` element containing the matching text. """ + def __init__(self, pattern): Pattern.__init__(self, pattern) self.tag = "code" @@ -315,6 +319,7 @@ class DoubleTagPattern(SimpleTagPattern): Useful for strong emphasis etc. """ + def handleMatch(self, m): tag1, tag2 = self.tag.split(",") el1 = util.etree.Element(tag1) @@ -327,6 +332,7 @@ def handleMatch(self, m): class HtmlPattern(Pattern): """ Store raw inline html and return a placeholder. """ + def handleMatch(self, m): rawhtml = self.unescape(m.group(2)) place_holder = self.markdown.htmlStash.store(rawhtml) @@ -353,6 +359,7 @@ def get_stash(m): class LinkPattern(Pattern): """ Return a link element from the given match. """ + def handleMatch(self, m): el = util.etree.Element("a") el.text = m.group(2) @@ -420,6 +427,7 @@ def sanitize_url(self, url): class ImagePattern(LinkPattern): """ Return a img element from the given match. """ + def handleMatch(self, m): el = util.etree.Element("img") src_parts = m.group(9).split() @@ -479,6 +487,7 @@ def makeTag(self, href, title, text): class ImageReferencePattern(ReferencePattern): """ Match to a stored reference and return img element. """ + def makeTag(self, href, title, text): el = util.etree.Element("img") el.set("src", self.sanitize_url(href)) @@ -494,6 +503,7 @@ def makeTag(self, href, title, text): class AutolinkPattern(Pattern): """ Return a link Element given an autolink (``). """ + def handleMatch(self, m): el = util.etree.Element("a") el.set('href', self.unescape(m.group(2))) @@ -505,6 +515,7 @@ class AutomailPattern(Pattern): """ Return a mailto link Element given an automail link (``). """ + def handleMatch(self, m): el = util.etree.Element('a') email = self.unescape(m.group(2)) diff --git a/markdown/postprocessors.py b/markdown/postprocessors.py index 8b311b268..ee24a82d8 100644 --- a/markdown/postprocessors.py +++ b/markdown/postprocessors.py @@ -62,7 +62,7 @@ def run(self, text): else: html = self.markdown.html_replacement_text if (self.isblocklevel(html) and - (safe or not self.markdown.safeMode)): + (safe or not self.markdown.safeMode)): replacements["

%s

" % (self.markdown.htmlStash.get_placeholder(i))] = \ html + "\n" diff --git a/markdown/preprocessors.py b/markdown/preprocessors.py index 7ea4fcf9f..ce254c969 100644 --- a/markdown/preprocessors.py +++ b/markdown/preprocessors.py @@ -34,6 +34,7 @@ class Preprocessor(util.Processor): Preprocessors must extend markdown.Preprocessor. """ + def run(self, lines): """ Each subclass of Preprocessor should override the `run` method, which @@ -98,7 +99,7 @@ def _get_left_tag(self, block): return tag, len(m.group(0)), attrs else: tag = block[1:].split(">", 1)[0].lower() - return tag, len(tag)+2, {} + return tag, len(tag) + 2, {} def _recursive_tagfind(self, ltag, rtag, start_index, block): while 1: diff --git a/markdown/serializers.py b/markdown/serializers.py index 1e8d9dd28..8ee86a1dc 100644 --- a/markdown/serializers.py +++ b/markdown/serializers.py @@ -76,7 +76,7 @@ def _raise_serialization_error(text): # pragma: no cover raise TypeError( "cannot serialize %r (type %s)" % (text, type(text).__name__) - ) + ) def _encode(text, encoding): @@ -242,7 +242,7 @@ def add_qname(qname): raise ValueError( "cannot use non-qualified names with " "default_namespace option" - ) + ) qnames[qname] = qname except TypeError: # pragma: no cover _raise_serialization_error(qname) diff --git a/markdown/treeprocessors.py b/markdown/treeprocessors.py index d06f19288..4f91f4c40 100644 --- a/markdown/treeprocessors.py +++ b/markdown/treeprocessors.py @@ -31,6 +31,7 @@ class Treeprocessor(util.Processor): Treeprocessors must extend markdown.Treeprocessor. """ + def run(self, root): """ Subclasses of Treeprocessor should implement a `run` method, which @@ -239,7 +240,7 @@ def __applyPattern(self, pattern, data, patternIndex, startIndex=0): node = pattern.handleMatch(match) if node is None: - return data, True, len(leftData)+match.span(len(match.groups()))[0] + return data, True, len(leftData) + match.span(len(match.groups()))[0] if not isString(node): if not isinstance(node.text, util.AtomicString): diff --git a/markdown/util.py b/markdown/util.py index d3d48f099..904dc3863 100644 --- a/markdown/util.py +++ b/markdown/util.py @@ -38,10 +38,10 @@ # Placeholders STX = '\u0002' # Use STX ("Start of text") for start-of-placeholder ETX = '\u0003' # Use ETX ("End of text") for end-of-placeholder -INLINE_PLACEHOLDER_PREFIX = STX+"klzzwxh:" +INLINE_PLACEHOLDER_PREFIX = STX + "klzzwxh:" INLINE_PLACEHOLDER = INLINE_PLACEHOLDER_PREFIX + "%s" + ETX INLINE_PLACEHOLDER_RE = re.compile(INLINE_PLACEHOLDER % r'([0-9]+)') -AMP_SUBSTITUTE = STX+"amp"+ETX +AMP_SUBSTITUTE = STX + "amp" + ETX HTML_PLACEHOLDER = STX + "wzxhzdk:%s" + ETX HTML_PLACEHOLDER_RE = re.compile(HTML_PLACEHOLDER % r'([0-9]+)') TAG_PLACEHOLDER = STX + "hzzhzkh:%s" + ETX @@ -123,6 +123,7 @@ class AtomicString(text_type): class Processor(object): + def __init__(self, markdown_instance=None): if markdown_instance: self.markdown = markdown_instance diff --git a/tests/__init__.py b/tests/__init__.py index f759ceb74..0bbed3747 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -28,6 +28,7 @@ class YamlConfig(): + def __init__(self, defaults, filename): """ Set defaults and load config file if it exists. """ self.DEFAULT_SECTION = 'DEFAULT' @@ -93,6 +94,7 @@ def normalize(text): class CheckSyntax(object): + def __init__(self, description=None): if description: self.description = 'TestSyntax: "%s"' % description diff --git a/tests/test_apis.py b/tests/test_apis.py index e3de779dd..1839d89d0 100644 --- a/tests/test_apis.py +++ b/tests/test_apis.py @@ -52,7 +52,8 @@ def testNamedExtension(self): def TestNamedExtensionWithClass(self): """ Test Extension loading with class name (`path.to.module:Class`). """ - markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension']) + markdown.Markdown( + extensions=['markdown.extensions.footnotes:FootnoteExtension']) class TestBlockParser(unittest.TestCase): @@ -161,18 +162,23 @@ def testReset(self): def testUnsafeHtmlInSafeMode(self): """ Test that unsafe HTML gets escaped in safe_mode. """ - output = markdown.markdown('foo', extensions=[self.build_extension()], safe_mode='escape') - self.assertEqual(output, '

<script>print("evil")</script>

') + output = markdown.markdown( + 'foo', extensions=[self.build_extension()], safe_mode='escape') + self.assertEqual( + output, '

<script>print("evil")</script>

') def build_extension(self): """ Build an extention that addes unsafe html to Stash in same_mode. """ class Unsafe(markdown.treeprocessors.Treeprocessor): + def run(self, root): el = root.find('p') - el.text = self.markdown.htmlStash.store('', safe=False) + el.text = self.markdown.htmlStash.store( + '', safe=False) return root class StoreUnsafeHtml(markdown.extensions.Extension): + def extendMarkdown(self, md, md_globals): md.treeprocessors.add('unsafe', Unsafe(md), '_end') @@ -191,7 +197,8 @@ def setUp(self): def testValues(self): """ Test output of OrderedDict.values(). """ - self.assertEqual(list(self.odict.values()), ['This', 'a', 'self', 'test']) + self.assertEqual(list(self.odict.values()), [ + 'This', 'a', 'self', 'test']) def testKeys(self): """ Test output of OrderedDict.keys(). """ @@ -357,7 +364,8 @@ def testLoadExtensionFailure(self): def testLoadBadExtension(self): """ Test loading of an Extension with no makeExtension function. """ - self.assertRaises(AttributeError, markdown.Markdown, extensions=['markdown.util']) + self.assertRaises(AttributeError, markdown.Markdown, + extensions=['markdown.util']) def testNonExtension(self): """ Test loading a non Extension object as an extension. """ @@ -389,7 +397,8 @@ def testStringConfigExtention(self): """ Test that passing configs to an Extension in the name raises a DeprecationWarning. """ self.assertRaises( DeprecationWarning, - markdown.Markdown, extensions=['markdown.extension.footnotes(PLACE_MARKER=FOO)'] + markdown.Markdown, extensions=[ + 'markdown.extension.footnotes(PLACE_MARKER=FOO)'] ) @@ -464,6 +473,7 @@ def testCommentPrettify(self): class testElementTailTests(unittest.TestCase): """ Element Tail Tests """ + def setUp(self): self.pretty = markdown.treeprocessors.PrettifyTreeprocessor() @@ -520,6 +530,7 @@ def fakeSerializer(elem): return '

foo

' class registerFakeSerializer(markdown.extensions.Extension): + def extendMarkdown(self, md, md_globals): md.output_formats['fake'] = fakeSerializer @@ -586,6 +597,7 @@ def testNestedAtomicString(self): class TestConfigParsing(unittest.TestCase): + def assertParses(self, value, result): self.assertTrue(markdown.util.parseBoolValue(value, False) is result) @@ -598,8 +610,10 @@ def testBooleansParsing(self): self.assertParses('none', False) def testPreserveNone(self): - self.assertTrue(markdown.util.parseBoolValue('None', preserve_none=True) is None) - self.assertTrue(markdown.util.parseBoolValue(None, preserve_none=True) is None) + self.assertTrue(markdown.util.parseBoolValue( + 'None', preserve_none=True) is None) + self.assertTrue(markdown.util.parseBoolValue( + None, preserve_none=True) is None) def testInvalidBooleansParsing(self): self.assertRaises(ValueError, markdown.util.parseBoolValue, 'novalue') @@ -678,7 +692,8 @@ def testNoLazyOlOption(self): self.assertEqual(options, self.default_options) def testExtensionOption(self): - options, logging_level = parse_options(['-x', 'markdown.extensions.footnotes']) + options, logging_level = parse_options( + ['-x', 'markdown.extensions.footnotes']) self.default_options['extensions'] = ['markdown.extensions.footnotes'] self.assertEqual(options, self.default_options) diff --git a/tests/test_extensions.py b/tests/test_extensions.py index 19a138974..7ba607655 100644 --- a/tests/test_extensions.py +++ b/tests/test_extensions.py @@ -41,7 +41,8 @@ def testGetConfig(self): def testGetConfigDefault(self): self.assertEqual(self.ext.getConfig('baz'), '') - self.assertEqual(self.ext.getConfig('baz', default='missing'), 'missing') + self.assertEqual(self.ext.getConfig( + 'baz', default='missing'), 'missing') def testGetConfigs(self): self.assertEqual(self.ext.getConfigs(), {'foo': 'bar', 'bar': 'baz'}) @@ -111,8 +112,10 @@ def testBasicCodeHilite(self): text = '\t# A Code Comment' md = markdown.Markdown(extensions=['markdown.extensions.codehilite']) if self.has_pygments: - # Pygments can use random lexer here as we did not specify the language - self.assertStartsWith('
', md.convert(text))
+            # Pygments can use random lexer here as we did not specify the
+            # language
+            self.assertStartsWith(
+                '
', md.convert(text))
         else:
             self.assertEqual(
                 md.convert(text),
@@ -144,7 +147,8 @@ def testLinenumsFalse(self):
         md = markdown.Markdown(
             extensions=[markdown.extensions.codehilite.CodeHiliteExtension(linenums=False)])
         if self.has_pygments:
-            self.assertStartsWith('
', md.convert(text))
+            # Pygments can use random lexer here as we did not specify the
+            # language
+            self.assertStartsWith(
+                '
', md.convert(text))
         else:
             self.assertEqual(
                 md.convert(text),
@@ -188,10 +194,12 @@ def testLinenumsNoneWithShebang(self):
     def testLinenumsNoneWithColon(self):
         text = '\t:::Python\n\t# A Code Comment'
         md = markdown.Markdown(
-            extensions=[markdown.extensions.codehilite.CodeHiliteExtension(linenums=None)]
+            extensions=[
+                markdown.extensions.codehilite.CodeHiliteExtension(linenums=None)]
         )
         if self.has_pygments:
-            self.assertStartsWith('
Some Header\n'
             '

Another Header

' ) @@ -409,7 +424,8 @@ def testHeaderIdWithMetaData(self): # A Header''' self.assertEqual( - markdown.markdown(text, ['markdown.extensions.headerid', 'markdown.extensions.meta']), + markdown.markdown( + text, ['markdown.extensions.headerid', 'markdown.extensions.meta']), '

A Header

' ) @@ -418,13 +434,15 @@ def testHeaderIdWithAttr_List(self): text = '# Header1 {: #foo }\n# Header2 {: .bar }' self.assertEqual( - markdown.markdown(text, ['markdown.extensions.headerid', 'markdown.extensions.attr_list']), + markdown.markdown( + text, ['markdown.extensions.headerid', 'markdown.extensions.attr_list']), '

Header1

\n' '

Header2

' ) # Switch order extensions are loaded - should be no change in behavior. self.assertEqual( - markdown.markdown(text, ['markdown.extensions.attr_list', 'markdown.extensions.headerid']), + markdown.markdown( + text, ['markdown.extensions.attr_list', 'markdown.extensions.headerid']), '

Header1

\n' '

Header2

' ) @@ -501,7 +519,8 @@ class TestWikiLinks(unittest.TestCase): """ Test Wikilinks Extension. """ def setUp(self): - self.md = markdown.Markdown(extensions=['markdown.extensions.wikilinks']) + self.md = markdown.Markdown( + extensions=['markdown.extensions.wikilinks']) self.text = "Some text with a [[WikiLink]]." def testBasicWikilinks(self): @@ -533,8 +552,8 @@ def testSimpleSettings(self): base_url='/wiki/', end_url='.html', html_class='foo') - ] - ), + ] + ), '

Some text with a ' 'WikiLink.

') @@ -566,7 +585,8 @@ def testWikilinksMetaData(self): wiki_html_class: Some text with a [[WikiLink]].""" - md = markdown.Markdown(extensions=['markdown.extensions.meta', 'markdown.extensions.wikilinks']) + md = markdown.Markdown( + extensions=['markdown.extensions.meta', 'markdown.extensions.wikilinks']) self.assertEqual( md.convert(text), '

Some text with a ' @@ -588,7 +608,8 @@ def testURLCallback(self): def my_url_builder(label, base, end): return '/bar/' - md = markdown.Markdown(extensions=[WikiLinkExtension(build_url=my_url_builder)]) + md = markdown.Markdown( + extensions=[WikiLinkExtension(build_url=my_url_builder)]) self.assertEqual( md.convert('[[foo]]'), '

foo

' @@ -599,7 +620,8 @@ class TestAdmonition(unittest.TestCase): """ Test Admonition Extension. """ def setUp(self): - self.md = markdown.Markdown(extensions=['markdown.extensions.admonition']) + self.md = markdown.Markdown( + extensions=['markdown.extensions.admonition']) def testRE(self): RE = self.md.parser.blockprocessors['admonition'].RE @@ -660,7 +682,8 @@ def testNoMarker(self): def testAlternateMarker(self): """ Test TOC with user defined marker. """ md = markdown.Markdown( - extensions=[markdown.extensions.toc.TocExtension(marker='{{marker}}')] + extensions=[markdown.extensions.toc.TocExtension( + marker='{{marker}}')] ) text = '{{marker}}\n\n# Header 1\n\n## Header 2' self.assertEqual( @@ -850,7 +873,8 @@ def testPermalinkWithDoubleInlineCode(self): def testTitle(self): """ Test TOC Title. """ md = markdown.Markdown( - extensions=[markdown.extensions.toc.TocExtension(title='Table of Contents')] + extensions=[markdown.extensions.toc.TocExtension( + title='Table of Contents')] ) md.convert('# Header 1\n\n## Header 2') self.assertStartsWith( @@ -860,7 +884,8 @@ def testTitle(self): def testWithAttrList(self): """ Test TOC with attr_list Extension. """ - md = markdown.Markdown(extensions=['markdown.extensions.toc', 'markdown.extensions.attr_list']) + md = markdown.Markdown( + extensions=['markdown.extensions.toc', 'markdown.extensions.attr_list']) text = '# Header 1\n\n## Header 2 { #foo }' self.assertEqual( md.convert(text), @@ -889,6 +914,7 @@ def testUniqueFunc(self): class TestSmarty(unittest.TestCase): + def setUp(self): config = { 'markdown.extensions.smarty': [