diff options
author | JensDiemer <git@jensdiemer.de> | 2020-01-19 10:59:00 +0100 |
---|---|---|
committer | JensDiemer <git@jensdiemer.de> | 2020-01-19 10:59:00 +0100 |
commit | ec6e9f5999997a6e02caa49a324ab7b49dc0ab53 (patch) | |
tree | dbdee65c83d47292db7abf0273d4ba7cddf724e6 /creole | |
parent | 02b095a123013f115e5b8501388954c8dc497dd7 (diff) | |
download | creole-ec6e9f5999997a6e02caa49a324ab7b49dc0ab53.tar.gz |
Fix code style with autopep8
Diffstat (limited to 'creole')
38 files changed, 411 insertions, 434 deletions
diff --git a/creole/__init__.py b/creole/__init__.py index 6c486d8..398cdc1 100644 --- a/creole/__init__.py +++ b/creole/__init__.py @@ -19,7 +19,6 @@ """ - import warnings from creole.emitter.creol2html_emitter import HtmlEmitter @@ -30,18 +29,18 @@ from creole.parser.creol2html_parser import CreoleParser from creole.parser.html_parser import HtmlParser __version__ = "1.4.0" -__api__ = "1.0" # Creole 1.0 spec - http://wikicreole.org/ +__api__ = "1.0" # Creole 1.0 spec - http://wikicreole.org/ -VERSION_STRING = __version__ # remove in future -API_STRING = __api__ # remove in future +VERSION_STRING = __version__ # remove in future +API_STRING = __api__ # remove in future def creole2html(markup_string, debug=False, - parser_kwargs=None, emitter_kwargs=None, - block_rules=None, blog_line_breaks=True, - macros=None, verbose=None, stderr=None, - strict=False, - ): + parser_kwargs=None, emitter_kwargs=None, + block_rules=None, blog_line_breaks=True, + macros=None, verbose=None, stderr=None, + strict=False, + ): """ convert creole markup into html code @@ -58,7 +57,9 @@ def creole2html(markup_string, debug=False, "debug": debug, } if parser_kwargs is not None: - warnings.warn("parser_kwargs argument in creole2html would be removed in the future!", PendingDeprecationWarning) + warnings.warn( + "parser_kwargs argument in creole2html would be removed in the future!", + PendingDeprecationWarning) parser_kwargs2.update(parser_kwargs) # Create document tree from creole markup @@ -73,7 +74,9 @@ def creole2html(markup_string, debug=False, "strict": strict, } if emitter_kwargs is not None: - warnings.warn("emitter_kwargs argument in creole2html would be removed in the future!", PendingDeprecationWarning) + warnings.warn( + "emitter_kwargs argument in creole2html would be removed in the future!", + PendingDeprecationWarning) emitter_kwargs2.update(emitter_kwargs) # Build html code from document tree @@ -92,13 +95,13 @@ def parse_html(html_string, debug=False): def html2creole( - html_string, - debug=False, - parser_kwargs=None, - emitter_kwargs=None, - unknown_emit=None, - strict=False, - ): + html_string, + debug=False, + parser_kwargs=None, + emitter_kwargs=None, + unknown_emit=None, + strict=False, +): """ convert html code into creole markup @@ -106,7 +109,9 @@ def html2creole( 'This is **creole //markup//**!' """ if parser_kwargs is not None: - warnings.warn("parser_kwargs argument in html2creole would be removed in the future!", PendingDeprecationWarning) + warnings.warn( + "parser_kwargs argument in html2creole would be removed in the future!", + PendingDeprecationWarning) document_tree = parse_html(html_string, debug=debug) @@ -115,7 +120,9 @@ def html2creole( "strict": strict, } if emitter_kwargs is not None: - warnings.warn("emitter_kwargs argument in html2creole would be removed in the future!", PendingDeprecationWarning) + warnings.warn( + "emitter_kwargs argument in html2creole would be removed in the future!", + PendingDeprecationWarning) emitter_kwargs2.update(emitter_kwargs) # create creole markup from the document tree @@ -124,9 +131,9 @@ def html2creole( def html2textile(html_string, debug=False, - parser_kwargs=None, emitter_kwargs=None, - unknown_emit=None - ): + parser_kwargs=None, emitter_kwargs=None, + unknown_emit=None + ): """ convert html code into textile markup @@ -134,7 +141,9 @@ def html2textile(html_string, debug=False, 'This is *textile __markup__*!' """ if parser_kwargs is not None: - warnings.warn("parser_kwargs argument in html2textile would be removed in the future!", PendingDeprecationWarning) + warnings.warn( + "parser_kwargs argument in html2textile would be removed in the future!", + PendingDeprecationWarning) document_tree = parse_html(html_string, debug=debug) @@ -142,7 +151,9 @@ def html2textile(html_string, debug=False, "unknown_emit": unknown_emit, } if emitter_kwargs is not None: - warnings.warn("emitter_kwargs argument in html2textile would be removed in the future!", PendingDeprecationWarning) + warnings.warn( + "emitter_kwargs argument in html2textile would be removed in the future!", + PendingDeprecationWarning) emitter_kwargs2.update(emitter_kwargs) # create textile markup from the document tree @@ -151,9 +162,9 @@ def html2textile(html_string, debug=False, def html2rest(html_string, debug=False, - parser_kwargs=None, emitter_kwargs=None, - unknown_emit=None - ): + parser_kwargs=None, emitter_kwargs=None, + unknown_emit=None + ): """ convert html code into ReStructuredText markup @@ -169,18 +180,11 @@ def html2rest(html_string, debug=False, "unknown_emit": unknown_emit, } if emitter_kwargs is not None: - warnings.warn("emitter_kwargs argument in html2rest would be removed in the future!", PendingDeprecationWarning) + warnings.warn( + "emitter_kwargs argument in html2rest would be removed in the future!", + PendingDeprecationWarning) emitter_kwargs2.update(emitter_kwargs) # create ReStructuredText markup from the document tree emitter = ReStructuredTextEmitter(document_tree, debug=debug, **emitter_kwargs2) return emitter.emit() - - - -if __name__ == '__main__': - print("runing local doctest...") - import doctest - print(doctest.testmod( -# verbose=True - )) diff --git a/creole/cmdline.py b/creole/cmdline.py index bfbd65c..3fcdfe6 100644 --- a/creole/cmdline.py +++ b/creole/cmdline.py @@ -27,14 +27,14 @@ class CreoleCLI(object): ) self.parser.add_argument( '--version', action='version', - version='%%(prog)s from python-creole v%s' % VERSION_STRING # noqa flynt + version='%%(prog)s from python-creole v%s' % VERSION_STRING # noqa flynt ) self.parser.add_argument("sourcefile", help="source file to convert") self.parser.add_argument("destination", help="Output filename") self.parser.add_argument("--encoding", - default="utf-8", - help="Codec for read/write file (default encoding: utf-8)" - ) + default="utf-8", + help="Codec for read/write file (default encoding: utf-8)" + ) args = self.parser.parse_args() @@ -58,12 +58,15 @@ class CreoleCLI(object): def cli_creole2html(): CreoleCLI(creole2html) + def cli_html2creole(): CreoleCLI(html2creole) + def cli_html2rest(): CreoleCLI(html2rest) + def cli_html2textile(): CreoleCLI(html2textile) diff --git a/creole/emitter/creol2html_emitter.py b/creole/emitter/creol2html_emitter.py index 7fb398a..e9c9091 100644 --- a/creole/emitter/creol2html_emitter.py +++ b/creole/emitter/creol2html_emitter.py @@ -64,7 +64,7 @@ class TableOfContent(object): def nested_headlines2html(self, nested_headlines, level=0): """Convert a python nested list like the one representing the toc to an html equivalent.""" - indent = "\t"*level + indent = "\t" * level if isinstance(nested_headlines, str): return f'{indent}<li><a href="#{nested_headlines}">{nested_headlines}</a></li>\n' elif isinstance(nested_headlines, list): @@ -91,17 +91,17 @@ class TableOfContent(object): return document - class HtmlEmitter(object): """ Generate HTML output for the document tree consisting of DocNodes. """ + def __init__(self, root, macros=None, verbose=None, stderr=None, strict=False): self.root = root - if callable(macros) == True: + if callable(macros): # was a DeprecationWarning in the past raise TypeError("Callable macros are not supported anymore!") @@ -110,7 +110,7 @@ class HtmlEmitter(object): else: self.macros = macros - if not "toc" in root.used_macros: + if "toc" not in root.used_macros: # The document has no <<toc>> self.toc = None else: @@ -127,7 +127,6 @@ class HtmlEmitter(object): self.toc = TableOfContent() self.macros.toc = self.toc - if verbose is None: self.verbose = 1 else: @@ -144,7 +143,7 @@ class HtmlEmitter(object): """Try to emit whatever text is in the node.""" try: return node.children[0].content or '' - except: + except BaseException: return node.content or '' def html_escape(self, text): @@ -210,7 +209,7 @@ class HtmlEmitter(object): def table_head_emit(self, node): return '\t<th>%s</th>\n' % self.emit_children(node) - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def _typeface(self, node, tag): return '<%(tag)s>%(data)s</%(tag)s>' % { @@ -221,22 +220,29 @@ class HtmlEmitter(object): # TODO: How can we generalize that: def emphasis_emit(self, node): return self._typeface(node, tag="i") + def strong_emit(self, node): return self._typeface(node, tag="strong") + def monospace_emit(self, node): return self._typeface(node, tag="tt") + def superscript_emit(self, node): return self._typeface(node, tag="sup") + def subscript_emit(self, node): return self._typeface(node, tag="sub") + def underline_emit(self, node): return self._typeface(node, tag="u") + def small_emit(self, node): return self._typeface(node, tag="small") + def delete_emit(self, node): return self._typeface(node, tag="del") - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def header_emit(self, node): header = f'<h{node.level:d}>{self.html_escape(node.content)}</h{node.level:d}>' @@ -274,12 +280,12 @@ class HtmlEmitter(object): height = int(h_str.strip()) return '<img src="%s" title="%s" alt="%s" width="%s" height="%s" />' % ( self.attr_escape(target), title, title, width, height) - except: + except BaseException: pass return f'<img src="{self.attr_escape(target)}" title="{text}" alt="{text}" />' def macro_emit(self, node): - #print(node.debug()) + # print(node.debug()) macro_name = node.macro_name text = node.content macro = None @@ -308,7 +314,7 @@ class HtmlEmitter(object): except AttributeError as e: exc_info = sys.exc_info() - if macro == None: + if macro is None: return self.error( f"Macro '{macro_name}' doesn't exist", exc_info diff --git a/creole/emitter/html2creole_emitter.py b/creole/emitter/html2creole_emitter.py index 8ff0360..7c6421e 100644 --- a/creole/emitter/html2creole_emitter.py +++ b/creole/emitter/html2creole_emitter.py @@ -21,6 +21,7 @@ class CreoleEmitter(BaseEmitter): Build from a document_tree (html2creole.parser.HtmlParser instance) a creole markup text. """ + def __init__(self, document_tree, strict=False, *args, **kwargs): self.strict = strict super(CreoleEmitter, self).__init__(document_tree, *args, **kwargs) @@ -30,13 +31,14 @@ class CreoleEmitter(BaseEmitter): def emit(self): """Emit the document represented by self.root DOM tree.""" - return self.emit_node(self.root).strip() # FIXME + return self.emit_node(self.root).strip() # FIXME - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def blockdata_pre_emit(self, node): """ pre block -> with newline at the end """ return "{{{%s}}}\n" % self.deentity.replace_all(node.content) + def inlinedata_pre_emit(self, node): """ a pre inline block -> no newline at the end """ return "{{{%s}}}" % self.deentity.replace_all(node.content) @@ -45,7 +47,7 @@ class CreoleEmitter(BaseEmitter): return f"{node.content}\n\n" return node.content - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def p_emit(self, node): result = self.emit_children(node) @@ -62,7 +64,7 @@ class CreoleEmitter(BaseEmitter): def headline_emit(self, node): return "%s %s\n\n" % ("=" * node.level, self.emit_children(node)) - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def strong_emit(self, node): return self._typeface(node, key="**") @@ -75,19 +77,24 @@ class CreoleEmitter(BaseEmitter): def tt_emit(self, node): return self._typeface(node, key="##") + def sup_emit(self, node): return self._typeface(node, key="^^") + def sub_emit(self, node): return self._typeface(node, key=",,") + def u_emit(self, node): return self._typeface(node, key="__") + def small_emit(self, node): return self._typeface(node, key="--") + def del_emit(self, node): return self._typeface(node, key="~~") strike_emit = del_emit - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def hr_emit(self, node): return "----\n\n" @@ -114,12 +121,12 @@ class CreoleEmitter(BaseEmitter): alt = node.attrs.get("alt", "") width = node.attrs.get("height", None) height = node.attrs.get("width", None) - if len(alt) > len(title): # Use the longest one + if len(alt) > len(title): # Use the longest one text = alt else: text = title - if text == "": # Use filename as picture text + if text == "": # Use filename as picture text text = posixpath.basename(src) if not self.strict: @@ -128,7 +135,7 @@ class CreoleEmitter(BaseEmitter): return "{{%s|%s}}" % (src, text) - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def ul_emit(self, node): return self._list_emit(node, list_type="*") @@ -136,7 +143,7 @@ class CreoleEmitter(BaseEmitter): def ol_emit(self, node): return self._list_emit(node, list_type="#") - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def div_emit(self, node): return self._emit_content(node) @@ -145,10 +152,6 @@ class CreoleEmitter(BaseEmitter): return self._emit_content(node) - - - - if __name__ == '__main__': import doctest print(doctest.testmod()) @@ -168,9 +171,9 @@ if __name__ == '__main__': from creole.shared.unknown_tags import escape_unknown_nodes e = CreoleEmitter(document_tree, - debug=True, - unknown_emit=escape_unknown_nodes - ) + debug=True, + unknown_emit=escape_unknown_nodes + ) content = e.emit() print("*" * 79) print(content) diff --git a/creole/emitter/html2rest_emitter.py b/creole/emitter/html2rest_emitter.py index 84af8e4..23de5ce 100644 --- a/creole/emitter/html2rest_emitter.py +++ b/creole/emitter/html2rest_emitter.py @@ -20,7 +20,7 @@ from creole.shared.base_emitter import BaseEmitter from creole.shared.markup_table import MarkupTable # Kink of nodes in which hyperlinks are stored in references intead of embedded urls. -DO_SUBSTITUTION = ("th", "td",) # TODO: In witch kind of node must we also substitude links? +DO_SUBSTITUTION = ("th", "td",) # TODO: In witch kind of node must we also substitude links? class Html2restException(Exception): @@ -32,6 +32,7 @@ class ReStructuredTextEmitter(BaseEmitter): Build from a document_tree (html2creole.parser.HtmlParser instance) a creole markup text. """ + def __init__(self, *args, **kwargs): super(ReStructuredTextEmitter, self).__init__(*args, **kwargs) @@ -54,7 +55,7 @@ class ReStructuredTextEmitter(BaseEmitter): self._substitution_data = [] return content - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def blockdata_pre_emit(self, node): """ pre block -> with newline at the end """ @@ -70,7 +71,7 @@ class ReStructuredTextEmitter(BaseEmitter): return f"{node.content}\n\n" return node.content - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def emit_children(self, node): """Emit all the children of a node.""" @@ -86,7 +87,7 @@ class ReStructuredTextEmitter(BaseEmitter): if self._substitution_data: # add rest at the end if not result.endswith("\n\n"): - result += "\n\n" + result += "\n\n" result += "%s\n\n" % self._get_block_data() return result @@ -102,13 +103,14 @@ class ReStructuredTextEmitter(BaseEmitter): return "%s\n\n" % self.emit_children(node) HEADLINE_DATA = { - 1:("=", True), - 2:("-", True), - 3:("=", False), - 4:("-", False), - 5:('`', False), - 6:("'", False), + 1: ("=", True), + 2: ("-", True), + 3: ("=", False), + 4: ("-", False), + 5: ('`', False), + 6: ("'", False), } + def headline_emit(self, node): text = self.emit_children(node) @@ -124,21 +126,23 @@ class ReStructuredTextEmitter(BaseEmitter): else: format = "%(t)s\n%(m)s\n\n" - return format % {"m":markup, "t":text} + return format % {"m": markup, "t": text} - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def _typeface(self, node, key): return key + self.emit_children(node) + key def strong_emit(self, node): return self._typeface(node, key="**") + def b_emit(self, node): return self._typeface(node, key="**") big_emit = strong_emit def i_emit(self, node): return self._typeface(node, key="*") + def em_emit(self, node): return self._typeface(node, key="*") @@ -166,7 +170,7 @@ class ReStructuredTextEmitter(BaseEmitter): # def code_emit(self, node): # return self._typeface(node, key="@") - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def hr_emit(self, node): return "----\n\n" @@ -230,12 +234,12 @@ class ReStructuredTextEmitter(BaseEmitter): title = node.attrs.get("title", "") alt = node.attrs.get("alt", "") - if len(alt) > len(title): # Use the longest one + if len(alt) > len(title): # Use the longest one substitution_text = alt else: substitution_text = title - if substitution_text == "": # Use filename as picture text + if substitution_text == "": # Use filename as picture text substitution_text = posixpath.basename(src) old_src = self._get_old_substitution( @@ -248,12 +252,12 @@ class ReStructuredTextEmitter(BaseEmitter): return f"|{substitution_text}|" - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def code_emit(self, node): return "``%s``" % self._emit_content(node) - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def li_emit(self, node): content = self.emit_children(node).strip("\n") @@ -327,14 +331,14 @@ if __name__ == '__main__': print(data) h2c = HtmlParser( -# debug=True + # debug=True ) document_tree = h2c.feed(data) h2c.debug() e = ReStructuredTextEmitter(document_tree, - debug=True - ) + debug=True + ) content = e.emit() print("*" * 79) print(content) diff --git a/creole/emitter/html2textile_emitter.py b/creole/emitter/html2textile_emitter.py index a557fe3..3cbbd02 100644 --- a/creole/emitter/html2textile_emitter.py +++ b/creole/emitter/html2textile_emitter.py @@ -30,13 +30,14 @@ class TextileEmitter(BaseEmitter): def emit(self): """Emit the document represented by self.root DOM tree.""" - return self.emit_node(self.root).strip() # FIXME + return self.emit_node(self.root).strip() # FIXME - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def blockdata_pre_emit(self, node): """ pre block -> with newline at the end """ return "<pre>%s</pre>\n" % self.deentity.replace_all(node.content) + def inlinedata_pre_emit(self, node): """ a pre inline block -> no newline at the end """ return "<pre>%s</pre>" % self.deentity.replace_all(node.content) @@ -45,8 +46,7 @@ class TextileEmitter(BaseEmitter): return f"{node.content}\n\n" return node.content - - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def p_emit(self, node): return "%s\n\n" % self.emit_children(node) @@ -54,40 +54,46 @@ class TextileEmitter(BaseEmitter): def headline_emit(self, node): return f"h{node.level:d}. {self.emit_children(node)}\n\n" - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def _typeface(self, node, key): return key + self.emit_children(node) + key def strong_emit(self, node): return self._typeface(node, key="*") + def b_emit(self, node): return self._typeface(node, key="**") big_emit = strong_emit def i_emit(self, node): return self._typeface(node, key="__") + def em_emit(self, node): return self._typeface(node, key="_") def sup_emit(self, node): return self._typeface(node, key="^") + def sub_emit(self, node): return self._typeface(node, key="~") + def del_emit(self, node): return self._typeface(node, key="-") def cite_emit(self, node): return self._typeface(node, key="??") + def ins_emit(self, node): return self._typeface(node, key="+") def span_emit(self, node): return self._typeface(node, key="%") + def code_emit(self, node): return self._typeface(node, key="@") - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def hr_emit(self, node): return "----\n\n" @@ -105,17 +111,17 @@ class TextileEmitter(BaseEmitter): title = node.attrs.get("title", "") alt = node.attrs.get("alt", "") - if len(alt) > len(title): # Use the longest one + if len(alt) > len(title): # Use the longest one text = alt else: text = title - if text == "": # Use filename as picture text + if text == "": # Use filename as picture text text = posixpath.basename(src) return f"!{src}({text})!" - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def ul_emit(self, node): return self._list_emit(node, list_type="*") @@ -124,12 +130,6 @@ class TextileEmitter(BaseEmitter): return self._list_emit(node, list_type="#") - - - - - - if __name__ == '__main__': import doctest print(doctest.testmod()) @@ -159,8 +159,8 @@ if __name__ == '__main__': h2c.debug() e = TextileEmitter(document_tree, - debug=True - ) + debug=True + ) content = e.emit() print("*" * 79) print(content) diff --git a/creole/exceptions.py b/creole/exceptions.py index 91f9042..d52e6b4 100644 --- a/creole/exceptions.py +++ b/creole/exceptions.py @@ -10,6 +10,5 @@ """ - class DocutilsImportError(ImportError): pass diff --git a/creole/html_tools/deentity.py b/creole/html_tools/deentity.py index b22a17c..23a6190 100644 --- a/creole/html_tools/deentity.py +++ b/creole/html_tools/deentity.py @@ -17,7 +17,7 @@ entities_rules = '|'.join([ r"(&\#x(?P<hex>[a-fA-F0-9]+);)", r"(&(?P<named>[a-zA-Z]+);)", ]) -#print(entities_rules) +# print(entities_rules) entities_regex = re.compile( entities_rules, re.VERBOSE | re.UNICODE | re.MULTILINE ) @@ -41,6 +41,7 @@ class Deentity(object): >>> d.replace_named("amp") '&' """ + def replace_number(self, text): """ unicode number entity """ unicode_no = int(text) diff --git a/creole/html_tools/strip_html.py b/creole/html_tools/strip_html.py index b6729b3..11a2f91 100644 --- a/creole/html_tools/strip_html.py +++ b/creole/html_tools/strip_html.py @@ -12,7 +12,6 @@ """ - import re from creole.parser.html_parser_config import BLOCK_TAGS @@ -32,7 +31,6 @@ strip_html_regex = re.compile( ) - def strip_html(html_code): """ Delete whitespace from html code. Doesn't recordnize preformatted blocks! @@ -87,10 +85,10 @@ def strip_html(html_code): elif startend_tag: # It's a closed start tag e.g.: <br /> - if space_start: # there was space before the tag + if space_start: # there was space before the tag result = " " + result - if space_end: # there was space after the tag + if space_end: # there was space after the tag result += " " else: # a start tag e.g.: <strong> diff --git a/creole/html_tools/text_tools.py b/creole/html_tools/text_tools.py index d42985a..16487a5 100644 --- a/creole/html_tools/text_tools.py +++ b/creole/html_tools/text_tools.py @@ -12,10 +12,11 @@ """ - import re space_re = re.compile(r"^(\s*)(.*?)(\s*)$", re.DOTALL) + + def clean_whitespace(txt): """ Special whitespaces cleanup diff --git a/creole/parser/creol2html_parser.py b/creole/parser/creol2html_parser.py index cd0c0e4..19f85c7 100644 --- a/creole/parser/creol2html_parser.py +++ b/creole/parser/creol2html_parser.py @@ -52,7 +52,6 @@ class CreoleParser(object): # For inline elements: inline_re = re.compile('|'.join(INLINE_RULES), INLINE_FLAGS) - def __init__(self, raw, block_rules=None, blog_line_breaks=True, debug=False): assert isinstance(raw, str) self.raw = raw @@ -69,12 +68,12 @@ class CreoleParser(object): self.root = DocNode('document', None) self.cur = self.root # The most recent document node self.text = None # The node to add inline characters to - self.last_text_break = None # Last break node, inserted by _text_repl() + self.last_text_break = None # Last break node, inserted by _text_repl() # Filled with all macros that's in the text self.root.used_macros = set() - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def cleanup_break(self, old_cur): """ @@ -96,22 +95,22 @@ class CreoleParser(object): of one of the listed kinds of nodes or root. Start at the node node. """ - self.cleanup_break(node) # remove unused end line breaks. - while node.parent is not None and not node.kind in kinds: + self.cleanup_break(node) # remove unused end line breaks. + while node.parent is not None and node.kind not in kinds: node = node.parent return node def _upto_block(self): - self.cur = self._upto(self.cur, ('document',))# 'section', 'blockquote')) + self.cur = self._upto(self.cur, ('document',)) # 'section', 'blockquote')) - #__________________________________________________________________________ + # __________________________________________________________________________ # The _*_repl methods called for matches in regexps. Sometimes the # same method needs several names, because of group names in regexps. def _text_repl(self, groups): -# print("_text_repl()", self.cur.kind) -# self.debug_groups(groups) + # print("_text_repl()", self.cur.kind) + # self.debug_groups(groups) if self.cur.kind in ('table', 'table_row', 'bullet_list', 'number_list'): self._upto_block() @@ -128,7 +127,7 @@ class CreoleParser(object): self.parse_inline(text) if groups.get('break') and self.cur.kind in ('paragraph', - 'emphasis', 'strong', 'pre_inline'): + 'emphasis', 'strong', 'pre_inline'): self.last_text_break = DocNode('break', self.cur, "") self.text = None @@ -167,14 +166,14 @@ class CreoleParser(object): _link_target_repl = _link_repl _link_text_repl = _link_repl - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def _add_macro(self, groups, macro_type, name_key, args_key, text_key=None): """ generic method to handle the macro, used for all variants: inline, inline-tag, block """ - #self.debug_groups(groups) + # self.debug_groups(groups) assert macro_type in ("macro_inline", "macro_block") if text_key: @@ -225,7 +224,6 @@ class CreoleParser(object): _macro_tag_name_repl = _macro_tag_repl _macro_tag_args_repl = _macro_tag_repl - def _macro_inline_repl(self, groups): """ inline macro tag with data, e.g.: <<macro>>text<</macro>> @@ -241,7 +239,7 @@ class CreoleParser(object): _macro_inline_args_repl = _macro_inline_repl _macro_inline_text_repl = _macro_inline_repl - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def _image_repl(self, groups): """Handles images and attachemnts included in the page.""" @@ -269,16 +267,16 @@ class CreoleParser(object): lst = self.cur # Find a list of the same kind and level up the tree while (lst and - not (lst.kind in ('number_list', 'bullet_list') and - lst.level == level) and - not lst.kind in ('document', 'section', 'blockquote')): + not (lst.kind in ('number_list', 'bullet_list') and + lst.level == level) and + lst.kind not in ('document', 'section', 'blockquote')): lst = lst.parent if lst and lst.kind == kind: self.cur = lst else: # Create a new level of list self.cur = self._upto(self.cur, - ('list_item', 'document', 'section', 'blockquote')) + ('list_item', 'document', 'section', 'blockquote')) self.cur = DocNode(kind, self.cur) self.cur.level = level self.cur = DocNode('list_item', self.cur) @@ -328,6 +326,7 @@ class CreoleParser(object): self._upto_block() kind = groups.get('pre_block_kind', None) text = groups.get('pre_block_text', "") + def remove_tilde(m): return m.group('indent') + m.group('rest') text = self.pre_escape_re.sub(remove_tilde, text) @@ -350,7 +349,7 @@ class CreoleParser(object): _pre_inline_text_repl = _pre_inline_repl _pre_inline_head_repl = _pre_inline_repl - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def _inline_mark(self, groups, key): self.cur = DocNode(key, self.cur) @@ -362,8 +361,8 @@ class CreoleParser(object): self.cur = self._upto(self.cur, (key,)).parent self.text = None - # TODO: How can we generalize that: + def _emphasis_repl(self, groups): self._inline_mark(groups, key='emphasis') _emphasis_text_repl = _emphasis_repl @@ -396,7 +395,7 @@ class CreoleParser(object): self._inline_mark(groups, key='delete') _delete_text_repl = _delete_repl - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def _linebreak_repl(self, groups): DocNode('break', self.cur, None) @@ -413,7 +412,7 @@ class CreoleParser(object): self.text = DocNode('text', self.cur, "") self.text.content += groups.get('char', "") - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def _replace(self, match): """Invoke appropriate _*_repl method. Called for every matched group.""" @@ -452,21 +451,22 @@ class CreoleParser(object): self.parse_block(text) return self.root + # -------------------------------------------------------------------------- - #-------------------------------------------------------------------------- def debug_tree(self, start_node=None): """ Display the current document tree """ print("_" * 80) - if start_node == None: + if start_node is None: start_node = self.root print(" document tree:") else: print(f" tree from {start_node}:") print("=" * 80) + def emit(node, ident=0): for child in node.children: print("%s%s: %r" % (" " * ident, child.kind, child.content)) @@ -483,9 +483,6 @@ class CreoleParser(object): print("-" * 80) - - - if __name__ == "__main__": import doctest print(doctest.testmod()) @@ -506,10 +503,9 @@ if __name__ == "__main__": def display_match(match): groups = match.groupdict() for name, text in groups.items(): - if name != "char" and text != None: + if name != "char" and text is not None: print("%20s: %r" % (name, text)) - parser = CreoleParser("", blog_line_breaks=blog_line_breaks) print("_" * 80) @@ -520,7 +516,6 @@ if __name__ == "__main__": print("merged inline rules test:") re.sub(parser.inline_re, display_match, txt) - def test_single(rules, flags, txt): for rule in rules: rexp = re.compile(rule, flags) @@ -535,5 +530,4 @@ if __name__ == "__main__": print("single inline rules match test:") test_single(INLINE_RULES, INLINE_FLAGS, txt) - print("---END---") diff --git a/creole/parser/creol2html_rules.py b/creole/parser/creol2html_rules.py index 0a9f059..01faeb7 100644 --- a/creole/parser/creol2html_rules.py +++ b/creole/parser/creol2html_rules.py @@ -10,7 +10,6 @@ """ - import re @@ -26,12 +25,12 @@ class InlineRules(object): (?P<url_target> (?P<url_proto> %s )://[^$\s]+ ) )''' % proto # Original uri matching regex inherited from MoinMoin code. - #url = r'''(?P<url> - #(^ | (?<=\s | [.,:;!?()/=])) - #(?P<escaped_url>~)? - #(?P<url_target> (?P<url_proto> %s ):\S+? ) - #($ | (?=\s | [,.:;!?()] (\s | $))) - #)''' % proto + # url = r'''(?P<url> + # (^ | (?<=\s | [.,:;!?()/=])) + # (?P<escaped_url>~)? + # (?P<url_target> (?P<url_proto> %s ):\S+? ) + # ($ | (?=\s | [,.:;!?()] (\s | $))) + # )''' % proto link = r'''(?P<link> \[\[ (?P<link_target>.+?) \s* @@ -58,7 +57,7 @@ class InlineRules(object): (\| \s* (?P<image_text>.+?) \s*)? }} )''' - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- # a macro like: <<macro>>text<</macro>> macro_inline = r''' @@ -98,10 +97,6 @@ class InlineRules(object): char = r'(?P<char> . )' - - - - class BlockRules(object): """ All used block rules. @@ -125,7 +120,7 @@ class BlockRules(object): ) ''' - line = r'''(?P<line> ^\s*$ )''' # empty line that separates paragraphs + line = r'''(?P<line> ^\s*$ )''' # empty line that separates paragraphs head = r'''(?P<head> ^ @@ -133,7 +128,7 @@ class BlockRules(object): (?P<head_text> .*? ) (=|\s)*?$ )''' - separator = r'(?P<separator> ^ \s* ----) [ \t]* $' # horizontal line + separator = r'(?P<separator> ^ \s* ----) [ \t]* $' # horizontal line pre_block = r'''(?P<pre_block> ^{{{ \s* $ @@ -174,9 +169,6 @@ class BlockRules(object): ) - - - class SpecialRules(object): """ re rules witch not directly used as inline/block rules. @@ -195,11 +187,11 @@ class SpecialRules(object): (?P<cell> ( %s | [^|])+ ) ) \s* ''' % '|'.join([ - InlineRules.link, - InlineRules.macro_inline, InlineRules.macro_tag, - InlineRules.image, - InlineRules.pre_inline - ]) + InlineRules.link, + InlineRules.macro_inline, InlineRules.macro_tag, + InlineRules.image, + InlineRules.pre_inline + ]) # For pre escaping, in creole 1.0 done with ~: pre_escape = r' ^(?P<indent>\s*) ~ (?P<rest> \}\}\} \s*) $' @@ -236,7 +228,7 @@ def _verify_rules(rules, flags): rule_list = [] for rule in rules: try: -# print(rule) + # print(rule) re.compile(rule, flags) # Try to merge the rules. e.g. Check if group named double used. diff --git a/creole/parser/html_parser.py b/creole/parser/html_parser.py index 741754f..d83a936 100644 --- a/creole/parser/html_parser.py +++ b/creole/parser/html_parser.py @@ -151,8 +151,7 @@ class HtmlParser(HTMLParser): return self.root - - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def _upto(self, node, kinds): """ @@ -172,7 +171,7 @@ class HtmlParser(HTMLParser): self.cur = self._upto(self.cur, kinds) self.debug_msg("go up to", self.cur) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def handle_starttag(self, tag, attrs): self.debug_msg("starttag", f"{tag!r} atts: {attrs}") @@ -222,7 +221,7 @@ class HtmlParser(HTMLParser): f"{tag}_{attr_dict['type']}", self.cur, content=self.blockdata[id], -# attrs = attr_dict + # attrs = attr_dict ) else: DocNode(tag, self.cur, None, attrs) @@ -233,7 +232,7 @@ class HtmlParser(HTMLParser): self.debug_msg("endtag", f"{tag!r}") - if tag == "br": # handled in starttag + if tag == "br": # handled in starttag return self.debug_msg("starttag", "%r" % self.get_starttag_text()) @@ -246,7 +245,7 @@ class HtmlParser(HTMLParser): else: self.cur = self.cur.parent - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def debug_msg(self, method, txt): if not self.debugging: @@ -259,13 +258,14 @@ class HtmlParser(HTMLParser): """ print("_" * 80) - if start_node == None: + if start_node is None: start_node = self.root print(" document tree:") else: print(f" tree from {start_node}:") print("=" * 80) + def emit(node, ident=0): for child in node.children: txt = "%s%s" % (" " * ident, child.kind) @@ -276,7 +276,7 @@ class HtmlParser(HTMLParser): if child.attrs: txt += f" - attrs: {child.attrs!r}" - if child.level != None: + if child.level is not None: txt += f" - level: {child.level!r}" print(txt) @@ -291,7 +291,7 @@ if __name__ == '__main__': # p = HtmlParser(debug=True) # p.feed("""\ -#<p><span>in span</span><br /> -#<code>in code</code></p> -#""") +# <p><span>in span</span><br /> +# <code>in code</code></p> +# """) # p.debug() diff --git a/creole/parser/html_parser_config.py b/creole/parser/html_parser_config.py index ddbda8f..679db4c 100644 --- a/creole/parser/html_parser_config.py +++ b/creole/parser/html_parser_config.py @@ -12,7 +12,6 @@ """ - BLOCK_TAGS = ( "address", "blockquote", "center", "dir", "div", "dl", "fieldset", "form", diff --git a/creole/rest_tools/clean_writer.py b/creole/rest_tools/clean_writer.py index c56e44b..c9b9923 100644 --- a/creole/rest_tools/clean_writer.py +++ b/creole/rest_tools/clean_writer.py @@ -37,7 +37,6 @@ except ImportError: raise DocutilsImportError(msg) - DEBUG = False #DEBUG = True @@ -53,6 +52,7 @@ class CleanHTMLWriter(html4css1.Writer): """ This docutils writer will use the CleanHTMLTranslator class below. """ + def __init__(self): html4css1.Writer.__init__(self) self.translator_class = CleanHTMLTranslator @@ -62,6 +62,7 @@ class CleanHTMLTranslator(html4css1.HTMLTranslator, object): """ Clean html translator for docutils system. """ + def _do_nothing(self, node, *args, **kwargs): pass @@ -128,8 +129,7 @@ class CleanHTMLTranslator(html4css1.HTMLTranslator, object): + self.body_suffix[:-1]) assert not self.context, 'len(context) = %s' % len(self.context) - - #__________________________________________________________________________ + # __________________________________________________________________________ # Clean table: visit_thead = _do_nothing @@ -161,7 +161,7 @@ class CleanHTMLTranslator(html4css1.HTMLTranslator, object): def depart_docinfo(self, node): self.body.append('</table>\n') - #__________________________________________________________________________ + # __________________________________________________________________________ # Clean image: depart_figure = _do_nothing @@ -183,7 +183,6 @@ class CleanHTMLTranslator(html4css1.HTMLTranslator, object): self.body[-1] = self.body[-1].replace(' />', f' align="{align}" />') - def rest2html(content, enable_exit_status=None, **kwargs): """ Convert reStructuredText markup to clean html code: No extra div, class or ids. @@ -217,7 +216,7 @@ def rest2html(content, enable_exit_status=None, **kwargs): ) # import pprint # pprint.pprint(parts) - return parts["html_body"] # Don't detache the first heading + return parts["html_body"] # Don't detache the first heading if __name__ == '__main__': @@ -225,11 +224,11 @@ if __name__ == '__main__': print(doctest.testmod()) # print(rest2html(""") -#+------------+------------+ -#| Headline 1 | Headline 2 | -#+============+============+ -#| cell one | cell two | -#+------------+------------+ +# +------------+------------+ +# | Headline 1 | Headline 2 | +# +============+============+ +# | cell one | cell two | +# +------------+------------+ # """) # print(rest2html(""") diff --git a/creole/rest_tools/pypi_rest2html.py b/creole/rest_tools/pypi_rest2html.py index c60ae0c..4f86640 100644 --- a/creole/rest_tools/pypi_rest2html.py +++ b/creole/rest_tools/pypi_rest2html.py @@ -12,7 +12,6 @@ """ - try: # Python 3 from urllib.parse import urlparse @@ -51,11 +50,11 @@ def pypi_rest2html(source, output_encoding='unicode'): 'file_insertion_enabled': 0, # no file/URL access 'halt_level': 2, # at warnings or errors, raise an exception 'report_level': 5, # never report problems with the reST code - } + } # Convert reStructuredText to HTML using Docutils. document = publish_doctree(source=source, - settings_overrides=settings_overrides) + settings_overrides=settings_overrides) for node in document.traverse(): if node.tagname == '#text': @@ -73,7 +72,7 @@ def pypi_rest2html(source, output_encoding='unicode'): # now turn the transformed document into HTML reader = readers.doctree.Reader(parser_name='null') pub = Publisher(reader, source=io.DocTreeInput(document), - destination_class=io.StringOutput) + destination_class=io.StringOutput) pub.set_writer('html') pub.process_programmatic_settings(None, settings_overrides, None) pub.set_destination(None, None) diff --git a/creole/setup_utils.py b/creole/setup_utils.py index a4cf583..17623f5 100644 --- a/creole/setup_utils.py +++ b/creole/setup_utils.py @@ -97,7 +97,7 @@ def get_long_description(package_root, filename="README.creole", raise_errors=No # convert html to ReSt long_description_rest = html2rest( long_description_html, - emitter_kwargs={"unknown_emit":unknown_emit} + emitter_kwargs={"unknown_emit": unknown_emit} ) except Exception: if raise_errors: @@ -131,7 +131,9 @@ def _get_long_description(*args, **kwargs): else: warnings.warn(msg, DeprecationWarning) return get_long_description(*args, **kwargs) -GetLongDescription = _get_long_description # for backward-compatibility + + +GetLongDescription = _get_long_description # for backward-compatibility if __name__ == "__main__": diff --git a/creole/shared/base_emitter.py b/creole/shared/base_emitter.py index a9964e5..b7467e4 100644 --- a/creole/shared/base_emitter.py +++ b/creole/shared/base_emitter.py @@ -20,6 +20,7 @@ class BaseEmitter(object): Build from a document_tree (html2creole.parser.HtmlParser instance) a creole markup text. """ + def __init__(self, document_tree, unknown_emit=None, debug=False): self.root = document_tree @@ -31,20 +32,20 @@ class BaseEmitter(object): self.last = None self.debugging = debug - self.deentity = Deentity() # for replacing html entities + self.deentity = Deentity() # for replacing html entities self._inner_list = "" self._mask_linebreak = False - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def blockdata_pass_emit(self, node): return f"{node.content}\n\n" return node.content - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def data_emit(self, node): - #node.debug() + # node.debug() return node.content def entityref_emit(self, node): @@ -58,7 +59,7 @@ class BaseEmitter(object): except KeyError as err: if self.debugging: print(f"unknown html entity found: {entity!r}") - return f"&{entity}" # FIXME + return f"&{entity}" # FIXME except UnicodeDecodeError as err: raise UnicodeError( f"Error handling entity {entity!r}: {err}" @@ -78,7 +79,7 @@ class BaseEmitter(object): # entity as a unicode number return self.deentity.replace_number(entity) - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def p_emit(self, node): return "%s\n\n" % self.emit_children(node) @@ -89,12 +90,12 @@ class BaseEmitter(object): else: return "\n" - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def _typeface(self, node, key): return key + self.emit_children(node) + key - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def li_emit(self, node): content = self.emit_children(node) @@ -106,7 +107,7 @@ class BaseEmitter(object): if not self.last.content or not self.last.content.endswith("\n"): start_newline = True - if self._inner_list == "": # Start a new list + if self._inner_list == "": # Start a new list self._inner_list = list_type else: self._inner_list += list_type @@ -115,7 +116,7 @@ class BaseEmitter(object): self._inner_list = self._inner_list[:-1] - if self._inner_list == "": # Start a new list + if self._inner_list == "": # Start a new list if start_newline: return "\n" + content + "\n\n" else: @@ -123,7 +124,7 @@ class BaseEmitter(object): else: return content - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def table_emit(self, node): self._table = MarkupTable( @@ -161,7 +162,7 @@ class BaseEmitter(object): self._table.add_td(content) return "" - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def _emit_content(self, node): content = self.emit_children(node) @@ -176,7 +177,7 @@ class BaseEmitter(object): def span_emit(self, node): return self._emit_content(node) - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def document_emit(self, node): self.last = node @@ -227,10 +228,10 @@ class BaseEmitter(object): # def emit(self): # """Emit the document represented by self.root DOM tree.""" # result = self.emit_node(self.root) -## return result.strip() # FIXME +# return result.strip() # FIXME # return result.rstrip() # FIXME - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def debug_msg(self, method, txt): if not self.debugging: diff --git a/creole/shared/document_tree.py b/creole/shared/document_tree.py index 31af1d8..20c6a44 100644 --- a/creole/shared/document_tree.py +++ b/creole/shared/document_tree.py @@ -22,6 +22,7 @@ class DocNode: The Document tree would be created in the parser and used in the emitter. """ + def __init__(self, kind='', parent=None, content=None, attrs=[], level=None): self.kind = kind @@ -91,7 +92,7 @@ class DebugList(list): super(DebugList, self).__init__() def append(self, item): -# for stack_frame in inspect.stack(): print(stack_frame) + # for stack_frame in inspect.stack(): print(stack_frame) line, method = inspect.stack()[1][2:4] msg = "%-8s append: %-35r (%-15s line:%s)" % ( diff --git a/creole/shared/example_macros.py b/creole/shared/example_macros.py index 25deac7..354469d 100644 --- a/creole/shared/example_macros.py +++ b/creole/shared/example_macros.py @@ -24,7 +24,6 @@ except ImportError: PYGMENTS = False - def html(text): """ Macro tag <<html>>...<</html>> @@ -63,7 +62,7 @@ def code(ext, text): try: highlighted_text = highlight(text, lexer, formatter).decode('utf-8') - except: + except BaseException: highlighted_text = pre(text) finally: return highlighted_text.replace('\n', '<br />\n') diff --git a/creole/shared/markup_table.py b/creole/shared/markup_table.py index 3cddccc..acb9b21 100644 --- a/creole/shared/markup_table.py +++ b/creole/shared/markup_table.py @@ -4,6 +4,7 @@ class MarkupTable(object): Container for holding table data and render the data in creole markup. Format every cell width to the same col width. """ + def __init__(self, head_prefix="= ", auto_width=True, debug_msg=None): self.head_prefix = head_prefix self.auto_width = auto_width @@ -30,7 +31,7 @@ class MarkupTable(object): self.add_td(self.head_prefix + text) def add_td(self, text): - if self.row_index == None: + if self.row_index is None: self.add_tr() self.debug_msg("Table.add_td", text) @@ -44,9 +45,9 @@ class MarkupTable(object): cell = cell.strip() if cell != "": if self.head_prefix and cell.startswith(self.head_prefix): - cell += " " # Headline + cell += " " # Headline else: - cell = f" {cell} " # normal cell + cell = f" {cell} " # normal cell line_cells.append(cell) cells.append(line_cells) @@ -81,8 +82,8 @@ class MarkupTable(object): # preformat every table cell cells, widths = self._get_preformat_info() - separator_line = "+%s+" % "+".join(["-"*width for width in widths]) - headline_separator = "+%s+" % "+".join(["="*width for width in widths]) + separator_line = "+%s+" % "+".join(["-" * width for width in widths]) + headline_separator = "+%s+" % "+".join(["=" * width for width in widths]) lines = [] for no, row in enumerate(cells): @@ -99,6 +100,7 @@ class MarkupTable(object): return "\n".join(lines) + if __name__ == '__main__': import doctest print(doctest.testmod()) diff --git a/creole/shared/unknown_tags.py b/creole/shared/unknown_tags.py index cf4aa4a..26cfd3a 100644 --- a/creole/shared/unknown_tags.py +++ b/creole/shared/unknown_tags.py @@ -12,7 +12,6 @@ """ - from xml.sax.saxutils import escape @@ -38,7 +37,6 @@ def _mask_content(emitter, node, mask_tag): return start_tag + content + end_tag - def raise_unknown_node(emitter, node): """ unknown_emit callable for Html2CreoleEmitter diff --git a/creole/shared/utils.py b/creole/shared/utils.py index a1b5167..9ac82e2 100644 --- a/creole/shared/utils.py +++ b/creole/shared/utils.py @@ -10,7 +10,6 @@ """ - import json import shlex @@ -29,6 +28,7 @@ KEYWORD_MAP = { "None": None, } + def string2dict(raw_content): """ convert a string into a dictionary. e.g.: @@ -83,7 +83,7 @@ def dict2string(d): def get_pygments_formatter(): if PYGMENTS: - return HtmlFormatter(lineos = True, encoding='utf-8', + return HtmlFormatter(lineos=True, encoding='utf-8', style='colorful', outencoding='utf-8', cssclass='pygments') @@ -92,7 +92,7 @@ def get_pygments_lexer(source_type, code): if PYGMENTS: try: return lexers.get_lexer_by_name(source_type) - except: + except BaseException: return lexers.guess_lexer(code) else: return None diff --git a/creole/tests/test_TODOs.py b/creole/tests/test_TODOs.py index e0606ee..a2b75c9 100644 --- a/creole/tests/test_TODOs.py +++ b/creole/tests/test_TODOs.py @@ -45,7 +45,7 @@ class CrossCompareCreoleTests(BaseCreoleTest): @unittest.expectedFailure def test_cross_paragraphs(self): """ TODO: bold/italics cross paragraphs in creole2html - see: http://code.google.com/p/python-creole/issues/detail?id=13 + see: http://code.google.com/p/python-creole/issues/detail?id=13 """ self.assert_creole2html(""" But, should //not be... @@ -62,14 +62,14 @@ class CrossCompareCreoleTests(BaseCreoleTest): """ self.cross_compare_creole(r""" this is {{{**escaped** inline}}}, isn't it? - + {{{ a **code** block }}} """, """ <p>this is <tt>**escaped** inline</tt>, isn't it?</p> - + <pre> a **code** block @@ -92,25 +92,25 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): """ TODO: http://code.google.com/p/python-creole/issues/detail?id=16#c5 """ self.assert_html2creole(r""" **foo** - + = one """, """ <b>foo</b> <h1>one</h1> - """)#, debug=True) + """) # , debug=True) @unittest.expectedFailure def test_no_space_before_blocktag(self): """ TODO: Bug in html2creole.strip_html(): Don't add a space before/after block tags """ self.assert_html2creole(r""" **foo** - + * one """, """ <b>foo</b> <ul><li>one</li></ul> - """#, debug=True - ) + """ # , debug=True + ) @unittest.expectedFailure def test_escape_char(self): @@ -144,5 +144,5 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): a <img src="/image.png" alt="PNG pictures" /> !</p> <p>picture <a href="www.domain.tld"><img src="foo.JPG" alt="Foo"></a> as a link</p> - """#, debug=True - ) + """ # , debug=True + ) diff --git a/creole/tests/test_cli.py b/creole/tests/test_cli.py index 74c3083..e03a53c 100644 --- a/creole/tests/test_cli.py +++ b/creole/tests/test_cli.py @@ -10,7 +10,6 @@ """ - import os import subprocess import sys @@ -70,7 +69,7 @@ class CreoleCLITests(BaseCreoleTest, SubprocessMixin, CliTestMixins): dest_file = tempfile.NamedTemporaryFile() destfilepath = dest_file.name - stdout=( + stdout = ( "Convert '%(src)s' to '%(dst)s' with %(prog)s (codec: utf-8)\n" "done. '%(dst)s' created." ) % { @@ -100,7 +99,6 @@ class CreoleCLITests(BaseCreoleTest, SubprocessMixin, CliTestMixins): ) - class CreoleCLITestsDirect(BaseCreoleTest, CliTestMixins): def setUp(self): diff --git a/creole/tests/test_creole2html.py b/creole/tests/test_creole2html.py index de02abd..02c0762 100644 --- a/creole/tests/test_creole2html.py +++ b/creole/tests/test_creole2html.py @@ -15,7 +15,6 @@ """ - import sys import unittest from io import StringIO @@ -33,12 +32,11 @@ except ImportError: PYGMENTS = False - - class TestCreole2html(BaseCreoleTest): """ Tests around creole2html API and macro function. """ + def setUp(self): # For fallback tests example_macros.PYGMENTS = PYGMENTS @@ -51,8 +49,8 @@ class TestCreole2html(BaseCreoleTest): creole2html( markup_string="<<notexist1>><<notexist2>><</notexist2>>", emitter_kwargs={ - "verbose":2, - "stderr":my_stderr, + "verbose": 2, + "stderr": my_stderr, } ) error_msg = my_stderr.getvalue() @@ -65,9 +63,9 @@ class TestCreole2html(BaseCreoleTest): "Traceback", "'notexist1'", "'notexist2'", ) for part in must_have: - tb_lines = [" -"*40] + tb_lines = [" -" * 40] tb_lines += error_msg.splitlines() - tb_lines += [" -"*40] + tb_lines += [" -" * 40] tb = "\n".join([" >>> %s" % l for l in tb_lines]) msg = f"{part!r} not found in:\n{tb}" # TODO: use assertIn if python 2.6 will be not support anymore. @@ -81,9 +79,9 @@ class TestCreole2html(BaseCreoleTest): html = creole2html( markup_string="<<html>><p>foo</p><</html>><bar?>", emitter_kwargs={ - "verbose":1, - "macros":example_macros, - "stderr":sys.stderr, + "verbose": 1, + "macros": example_macros, + "stderr": sys.stderr, } ) self.assertEqual(html, '<p>foo</p>\n<p><bar?></p>') @@ -92,9 +90,9 @@ class TestCreole2html(BaseCreoleTest): html = creole2html( markup_string="<<html>>{{{<nocode>}}}<</html>>", emitter_kwargs={ - "verbose":1, - "macros":example_macros, - "stderr":sys.stderr, + "verbose": 1, + "macros": example_macros, + "stderr": sys.stderr, } ) self.assertEqual(html, '{{{<nocode>}}}') @@ -103,9 +101,9 @@ class TestCreole2html(BaseCreoleTest): html = creole2html( markup_string="<<html>>1<</html>><<html>>2<</html>>", emitter_kwargs={ - "verbose":1, - "macros":example_macros, - "stderr":sys.stderr, + "verbose": 1, + "macros": example_macros, + "stderr": sys.stderr, } ) self.assertEqual(html, '1\n2') @@ -120,9 +118,9 @@ class TestCreole2html(BaseCreoleTest): html = creole2html( markup_string="<<test bar='b' foo='a'>>c<</test>>", emitter_kwargs={ - "verbose":1, - "macros":{"test":test}, - "stderr":sys.stderr, + "verbose": 1, + "macros": {"test": test}, + "stderr": sys.stderr, } ) self.assertEqual(html, 'a|b|c') @@ -135,14 +133,14 @@ class TestCreole2html(BaseCreoleTest): pass self.assertRaises(TypeError, - creole2html, - markup_string="<<test no=1 arg2='foo'>>bar<</test>>", - emitter_kwargs={ - "verbose":1, - "macros":testmacro, - "stderr":sys.stderr, - } - ) + creole2html, + markup_string="<<test no=1 arg2='foo'>>bar<</test>>", + emitter_kwargs={ + "verbose": 1, + "macros": testmacro, + "stderr": sys.stderr, + } + ) def test_macro_wrong_arguments_with_error_report(self): """ @@ -155,14 +153,14 @@ class TestCreole2html(BaseCreoleTest): html = creole2html( markup_string="<<test bar='foo'>>c<</test>>", emitter_kwargs={ - "verbose":2, - "macros":{"test":test}, - "stderr":my_stderr, + "verbose": 2, + "macros": {"test": test}, + "stderr": my_stderr, } ) self.assertEqual(html, - "[Error: Macro 'test' error: test() got an unexpected keyword argument 'bar']" - ) + "[Error: Macro 'test' error: test() got an unexpected keyword argument 'bar']" + ) error_msg = my_stderr.getvalue() # Check traceback information into our stderr handler @@ -174,7 +172,6 @@ class TestCreole2html(BaseCreoleTest): for part in must_have: self.assertIn(part, error_msg) - def test_macro_wrong_arguments_quite(self): """ simple test for the "macro API" @@ -186,14 +183,14 @@ class TestCreole2html(BaseCreoleTest): html = creole2html( markup_string="<<test bar='foo'>>c<</test>>", emitter_kwargs={ - "verbose":1, - "macros":{"test":test}, - "stderr":my_stderr, + "verbose": 1, + "macros": {"test": test}, + "stderr": my_stderr, } ) self.assertEqual(html, - "[Error: Macro 'test' error: test() got an unexpected keyword argument 'bar']" - ) + "[Error: Macro 'test' error: test() got an unexpected keyword argument 'bar']" + ) error_msg = my_stderr.getvalue() self.assertEqual(error_msg, "") @@ -213,8 +210,8 @@ class TestCreole2html(BaseCreoleTest): <span class="nb">print</span><span class="p">(</span><span class="s1">'hello world'</span><span class="p">)</span><br /> </pre></div><br /> """, - macros={'code': example_macros.code} - ) + macros={'code': example_macros.code} + ) def test_code_macro_fallback(self): # force to use fallback. Will be reset in self.setUp() @@ -251,8 +248,6 @@ class TestCreole2html(BaseCreoleTest): ) - - class TestCreole2htmlMarkup(BaseCreoleTest): def test_creole_basic(self): @@ -270,7 +265,7 @@ class TestCreole2htmlMarkup(BaseCreoleTest): out_string = creole2html("first\r\nsecond") self.assertEqual(out_string, "<p>first<br />\nsecond</p>") - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def test_creole_linebreak(self): self.assert_creole2html(r""" @@ -384,8 +379,8 @@ class TestCreole2htmlMarkup(BaseCreoleTest): the|text <p>the end</p> """, - macros=test_macros, - ) + macros=test_macros, + ) def test_macro_html1(self): self.assert_creole2html(r""" @@ -401,8 +396,8 @@ class TestCreole2htmlMarkup(BaseCreoleTest): <p>inline: {...} code</p> """, - macros=example_macros, - ) + macros=example_macros, + ) def test_macro_not_exist1(self): """ @@ -432,7 +427,7 @@ class TestCreole2htmlMarkup(BaseCreoleTest): self.assert_creole2html(source_string, should_string, verbose=1) - #---------------------------------------------------------------------- + # ---------------------------------------------------------------------- # Test with verbose=2 ans a StringIO stderr handler def test_wrong_macro_syntax(self): @@ -443,8 +438,8 @@ class TestCreole2htmlMarkup(BaseCreoleTest): <p>wrong macro line:<br /> [Error: Wrong macro arguments: ">Some funky page summary.<</summary" for macro 'summary' (maybe wrong macro tag syntax?)] </p> - """, # verbose=True - ) + """, # verbose=True + ) def test_macro_not_exist2(self): """ @@ -466,8 +461,7 @@ class TestCreole2htmlMarkup(BaseCreoleTest): <p>inline macro:<br /> </p> """, verbose=False - ) - + ) def test_toc_simple(self): """ @@ -792,7 +786,7 @@ class TestCreole2htmlMarkup(BaseCreoleTest): """, """ <p>a link to the <a href="http://www.pylucid.org">http://www.pylucid.org</a> page.</p> """ - ) + ) def test_wiki_style_line_breaks1(self): html = creole2html( @@ -863,7 +857,6 @@ class TestCreole2htmlMarkup(BaseCreoleTest): <p>end</p> """)) - def test_headline_spaces(self): """ https://code.google.com/p/python-creole/issues/detail?id=15 @@ -950,24 +943,27 @@ class TestStr2Dict(unittest.TestCase): {'key3': 3, 'key2': 2, 'key1': 1} ) + class TestDict2String(unittest.TestCase): def test_basic(self): self.assertEqual( - dict2string({'key':'value'}), + dict2string({'key': 'value'}), 'key="value"' ) def test_basic2(self): self.assertEqual( - dict2string({'foo':"bar", "no":123}), + dict2string({'foo': "bar", "no": 123}), 'foo="bar" no=123' ) + def test_basic3(self): self.assertEqual( - dict2string({"foo":'bar', "no":"ABC"}), + dict2string({"foo": 'bar', "no": "ABC"}), 'foo="bar" no="ABC"' ) + if __name__ == '__main__': unittest.main( verbosity=2 diff --git a/creole/tests/test_cross_compare_all.py b/creole/tests/test_cross_compare_all.py index ad715bc..2d8e97d 100644 --- a/creole/tests/test_cross_compare_all.py +++ b/creole/tests/test_cross_compare_all.py @@ -19,7 +19,6 @@ """ - import unittest from creole.tests.utils.base_unittest import BaseCreoleTest @@ -30,6 +29,7 @@ class CrossCompareTests(BaseCreoleTest): Cross compare tests for creol2html _and_ html2creole with the same test strings. Used BaseCreoleTest.assertCreole() """ + def test_bold_italics(self): self.cross_compare( creole_string=r""" @@ -372,6 +372,7 @@ class CrossCompareTests(BaseCreoleTest): # """ # ) + def test_pre1(self): self.cross_compare( creole_string=r""" @@ -389,7 +390,7 @@ class CrossCompareTests(BaseCreoleTest): * no list </pre> """) - self.cross_compare(# FIXME: Not the best html2rest output + self.cross_compare( # FIXME: Not the best html2rest output rest_string=""" Preformatting text: @@ -444,6 +445,7 @@ class CrossCompareTests(BaseCreoleTest): # <p>end</p> # """) + def test_pre_contains_braces(self): self.cross_compare( creole_string=""" diff --git a/creole/tests/test_cross_compare_creole.py b/creole/tests/test_cross_compare_creole.py index ea48603..7c4d893 100644 --- a/creole/tests/test_cross_compare_creole.py +++ b/creole/tests/test_cross_compare_creole.py @@ -17,7 +17,6 @@ """ - import unittest from creole.shared import example_macros @@ -75,7 +74,6 @@ class CrossCompareCreoleTests(BaseCreoleTest): lines.</strong></p> """) - def test_small(self): """ http://code.google.com/p/python-creole/issues/detail?id=12#c0 @@ -214,7 +212,6 @@ class CrossCompareCreoleTests(BaseCreoleTest): <p>this is <tt><strong>strong</strong> Teletyper</tt> ;)</p> """) - def test_no_inline_headline(self): self.cross_compare_creole( creole_string=r""" @@ -361,8 +358,8 @@ class CrossCompareCreoleTests(BaseCreoleTest): </ol></li> </ol> """, -# debug = True - ) + # debug = True + ) def test_big_table(self): self.cross_compare_creole(r""" @@ -408,8 +405,8 @@ class CrossCompareCreoleTests(BaseCreoleTest): </table> <p>...end</p> """, -# debug = True - ) + # debug = True + ) def test_html_macro_unknown_nodes(self): """ @@ -428,11 +425,11 @@ class CrossCompareCreoleTests(BaseCreoleTest): <p>555<x />666</p> """, - # use macro in creole2html emitter: - macros=example_macros, - # escape unknown tags with <<html>> in html2creole emitter: - unknown_emit=use_html_macro, - ) + # use macro in creole2html emitter: + macros=example_macros, + # escape unknown tags with <<html>> in html2creole emitter: + unknown_emit=use_html_macro, + ) def test_entities(self): self.cross_compare_creole(""" @@ -471,7 +468,6 @@ class CrossCompareCreoleTests(BaseCreoleTest): # """) - # def test_macro_pygments_code(self): # self.cross_compare_creole(r""" # a macro: @@ -498,7 +494,5 @@ class CrossCompareCreoleTests(BaseCreoleTest): # """) - - if __name__ == '__main__': unittest.main() diff --git a/creole/tests/test_cross_compare_rest.py b/creole/tests/test_cross_compare_rest.py index 454d6e5..ea02e19 100644 --- a/creole/tests/test_cross_compare_rest.py +++ b/creole/tests/test_cross_compare_rest.py @@ -14,7 +14,6 @@ """ - import unittest from creole.tests.utils.base_unittest import BaseCreoleTest @@ -32,7 +31,7 @@ class CrossCompareReStTests(BaseCreoleTest): <p>less-than sign: <</p> <p>greater-than sign: ></p> """, -# debug=True + # debug=True ) def test_bullet_lists_basic(self): @@ -51,7 +50,7 @@ class CrossCompareReStTests(BaseCreoleTest): <li>item 3</li> </ul> """, -# debug=True + # debug=True ) def test_numbered_lists(self): @@ -81,7 +80,7 @@ class CrossCompareReStTests(BaseCreoleTest): </li> </ol> """, -# debug=True + # debug=True ) def test_bullet_lists_nested(self): @@ -133,7 +132,7 @@ class CrossCompareReStTests(BaseCreoleTest): </ul> <p>Text under list.</p> """, -# debug=True + # debug=True ) def test_typeface_basic(self): @@ -285,7 +284,7 @@ class CrossCompareReStTests(BaseCreoleTest): </table> <p>Text after table.</p> """, -# debug=True + # debug=True ) def test_reuse_link_substitution1(self): @@ -313,7 +312,7 @@ class CrossCompareReStTests(BaseCreoleTest): </table> <p>Text after table.</p> """, -# debug=True + # debug=True ) def test_reuse_link_substitution2(self): @@ -337,7 +336,7 @@ class CrossCompareReStTests(BaseCreoleTest): </table> <p>and here <a href="foo/bar/">foo bar</a> again, after table.</p> """, -# debug=True + # debug=True ) def test_reuse_image_substitution(self): @@ -362,7 +361,7 @@ class CrossCompareReStTests(BaseCreoleTest): </tr> </table> """, -# debug=True + # debug=True ) def test_duplicate_image_substitution(self): @@ -391,12 +390,10 @@ class CrossCompareReStTests(BaseCreoleTest): </table> <p>again: the <img alt="same" src="/image.png" /> image and <a href="/url/foo/">same</a> link!</p> """, -# debug=True + # debug=True ) - - # def test_inline_literal(self): # """ TODO # http://docutils.sourceforge.net/docs/user/rst/quickref.html#inline-markup @@ -422,9 +419,7 @@ class CrossCompareReStTests(BaseCreoleTest): # <html escaped> # </pre> # """) - - if __name__ == '__main__': unittest.main( -# defaultTest="CrossCompareReStTests.test_paragraph_bwlow_table_links", + # defaultTest="CrossCompareReStTests.test_paragraph_bwlow_table_links", ) diff --git a/creole/tests/test_cross_compare_textile.py b/creole/tests/test_cross_compare_textile.py index fbbd871..63ce6c7 100644 --- a/creole/tests/test_cross_compare_textile.py +++ b/creole/tests/test_cross_compare_textile.py @@ -17,7 +17,6 @@ """ - import unittest from creole.tests.utils.base_unittest import BaseCreoleTest diff --git a/creole/tests/test_html2creole.py b/creole/tests/test_html2creole.py index 41c6e8e..60b35a3 100644 --- a/creole/tests/test_html2creole.py +++ b/creole/tests/test_html2creole.py @@ -14,7 +14,6 @@ """ - import unittest from creole import html2creole @@ -30,14 +29,12 @@ class TestHtml2Creole(unittest.TestCase): pass - - class TestHtml2CreoleMarkup(BaseCreoleTest): -# def assertCreole(self, raw_markup, raw_html, debug=False, **kwargs): -# self.assert_html2creole(raw_markup, raw_html, debug=debug, **kwargs) + # def assertCreole(self, raw_markup, raw_html, debug=False, **kwargs): + # self.assert_html2creole(raw_markup, raw_html, debug=debug, **kwargs) - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def test_not_used(self): """ @@ -55,7 +52,7 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): <i>italic</i></p> """) - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def test_raise_unknown_node(self): """ @@ -63,10 +60,10 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): Raise NotImplementedError on unknown tags. """ self.assertRaises(NotImplementedError, - html2creole, - html_string="<unknwon>", - unknown_emit=raise_unknown_node - ) + html2creole, + html_string="<unknwon>", + unknown_emit=raise_unknown_node + ) def test_use_html_macro(self): """ @@ -84,8 +81,8 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): <p>555<unknown />666</p> """, - unknown_emit=use_html_macro - ) + unknown_emit=use_html_macro + ) def test_escape_unknown_nodes(self): """ @@ -103,8 +100,8 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): <p>555<unknown />666</p> """, - unknown_emit=escape_unknown_nodes - ) + unknown_emit=escape_unknown_nodes + ) def test_escape_unknown_nodes2(self): """ @@ -118,8 +115,8 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): var js_sha_link='<p>***</p>'; </script> """, - unknown_emit=escape_unknown_nodes - ) + unknown_emit=escape_unknown_nodes + ) def test_transparent_unknown_nodes(self): """ @@ -132,7 +129,7 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): """, """ <form class="foo" id="bar"><label><em>baz</em></label>, <strong>quux</strong></form> """, unknown_emit=transparent_unknown_nodes - ) + ) def test_transparent_unknown_nodes2(self): """ @@ -144,7 +141,7 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): """, """ <p>FOO <script>var a='<em>STRONG</em>';</script> BAR</p> """, unknown_emit=transparent_unknown_nodes - ) + ) def test_transparent_unknown_nodes_block_elements(self): """ @@ -160,9 +157,9 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): <div><em>baz</em>,</div> <fieldset><strong>quux</strong></fieldset> <span>spam, </span><label>ham, </label>and eggs """, unknown_emit=transparent_unknown_nodes - ) + ) - #-------------------------------------------------------------------------- + # -------------------------------------------------------------------------- def test_entities(self): """ @@ -375,7 +372,7 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): # foo """, """ <ol class=gbtc><li>foo</li></ol> - """)#, debug=True) + """) # , debug=True) def test_ignore_links_without_href(self): """https://code.google.com/p/python-creole/issues/detail?id=19#c4""" @@ -383,7 +380,7 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): bar """, """ <a class="foo">bar</a> - """)#, debug=True) + """) # , debug=True) def test_newlines_after_headlines(self): self.assert_html2creole(r""" @@ -517,7 +514,7 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): # </ol> # <p>list 'b' end</p> # """, -## debug=True +# debug=True # ) # # def test_list2(self): @@ -538,11 +535,11 @@ class TestHtml2CreoleMarkup(BaseCreoleTest): # <li><tt>//this// is **not** [[processed]]</tt></li> # </ol> # """, -## debug=True +# debug=True # ) if __name__ == '__main__': unittest.main( -# defaultTest="TestHtml2CreoleMarkup.test_nested_listsitems_with_paragraph" + # defaultTest="TestHtml2CreoleMarkup.test_nested_listsitems_with_paragraph" ) diff --git a/creole/tests/test_html2rest.py b/creole/tests/test_html2rest.py index 29d197a..a10ae2a 100644 --- a/creole/tests/test_html2rest.py +++ b/creole/tests/test_html2rest.py @@ -14,7 +14,6 @@ """ - import unittest from creole.emitter.html2rest_emitter import Html2restException @@ -38,7 +37,7 @@ class ReStTests(BaseCreoleTest): <p>second block, line 1 and line 2</p> """, -# debug=True + # debug=True ) def test_substitution_image_without_alt_or_title(self): @@ -213,7 +212,7 @@ class ReStTests(BaseCreoleTest): def test_duplicate_substitution1(self): self.assertRaises(Html2restException, self.assert_html2rest, - rest_string=""" + rest_string=""" +-----------------------------+ | this is `same`_ first time. | +-----------------------------+ @@ -222,20 +221,20 @@ class ReStTests(BaseCreoleTest): the `same </other/>`_ link? """, - html_string=""" + html_string=""" <table> <tr><td>the <a href="/first/">same</a> first time.</td> </tr> </table> <p>the <a href="/other/">same</a> link?</p> """, -# debug=True - ) + # debug=True + ) def test_duplicate_link_substitution(self): self.assertRaises(Html2restException, self.assert_html2rest, -# self.cross_compare( - rest_string=""" + # self.cross_compare( + rest_string=""" +-----------------------------+ | this is `same`_ first time. | +-----------------------------+ @@ -244,33 +243,32 @@ class ReStTests(BaseCreoleTest): the `same </other/>`_ link? """, - html_string=""" + html_string=""" <table> <tr><td>the <a href="/first/">same</a> first time.</td> </tr> </table> <p>the <a href="/other/">same</a> link?</p> """, -# debug=True - ) + # debug=True + ) def test_duplicate_image_substitution(self): self.assertRaises(Html2restException, self.assert_html2rest, -# self.cross_compare( - rest_string=""" + # self.cross_compare( + rest_string=""" a |image|... and a other |image|! .. |image| image:: /image.png .. |image| image:: /other.png """, - html_string=""" + html_string=""" <p>a <img src="/image.png" title="image" alt="image" />...<br /> and a other <img src="/other.png" title="image" alt="image" />!</p> """, -# debug=True - ) - + # debug=True + ) # def test_preformat_unknown_nodes(self): @@ -315,6 +313,5 @@ class ReStTests(BaseCreoleTest): # """, # ) - if __name__ == '__main__': unittest.main() diff --git a/creole/tests/test_html2textile.py b/creole/tests/test_html2textile.py index b26b3e9..cd03b88 100644 --- a/creole/tests/test_html2textile.py +++ b/creole/tests/test_html2textile.py @@ -14,7 +14,6 @@ """ - import unittest from creole.shared.unknown_tags import preformat_unknown_nodes @@ -35,7 +34,7 @@ class TextileTests(BaseCreoleTest): <p>less-than sign: <<br /> greater-than sign: ></p> """, -# debug=True + # debug=True ) def test_preformat_unknown_nodes(self): @@ -55,7 +54,7 @@ class TextileTests(BaseCreoleTest): <p>555<x />666</p> """, - emitter_kwargs={"unknown_emit":preformat_unknown_nodes} + emitter_kwargs={"unknown_emit": preformat_unknown_nodes} ) def test_transparent_unknown_nodes(self): diff --git a/creole/tests/test_macros.py b/creole/tests/test_macros.py index e2548e2..c596a81 100644 --- a/creole/tests/test_macros.py +++ b/creole/tests/test_macros.py @@ -12,8 +12,6 @@ """ - - import json @@ -39,6 +37,7 @@ def unittest_macro2(char, text): """ return char.join(text.split()) + if __name__ == '__main__': import doctest print(doctest.testmod()) diff --git a/creole/tests/test_rest2html.py b/creole/tests/test_rest2html.py index 23261d9..dee787c 100644 --- a/creole/tests/test_rest2html.py +++ b/creole/tests/test_rest2html.py @@ -12,7 +12,6 @@ """ - import tempfile import unittest @@ -112,7 +111,7 @@ class ReSt2HtmlTests(BaseCreoleTest): .. include:: doesntexist.txt """, """ <p>Include should be disabled by default.</p> - """, report_level=3) # Set log level to "error" to suppress the waring output + """, report_level=3) # Set log level to "error" to suppress the waring output def test_include_enabled(self): test_content = "Content from include file." @@ -138,7 +137,7 @@ class ReSt2HtmlTests(BaseCreoleTest): <hr width=50 size=10> """, """ <p>Raw directive should be disabled by default.</p> - """, report_level=3) # Set log level to "error" to suppress the waring output + """, report_level=3) # Set log level to "error" to suppress the waring output def test_raw_enabled(self): self.assert_rest2html(""" diff --git a/creole/tests/test_setup_utils.py b/creole/tests/test_setup_utils.py index 0d6eb3b..8e8e32a 100644 --- a/creole/tests/test_setup_utils.py +++ b/creole/tests/test_setup_utils.py @@ -26,7 +26,6 @@ except ImportError: DOCUTILS = False - CREOLE_PACKAGE_ROOT = os.path.abspath(os.path.join(os.path.dirname(creole.__file__), "..")) TEST_README_DIR = os.path.abspath(os.path.dirname(__file__)) TEST_README_FILENAME = "test_README.creole" @@ -37,7 +36,7 @@ TEST_README_FILENAME = "test_README.creole" class SetupUtilsTests(BaseCreoleTest): def run(self, *args, **kwargs): # TODO: Remove if python 2.6 will be not support anymore. - if DOCUTILS == False: + if not DOCUTILS: warnings.warn("Skip SetupUtilsTests, because 'docutils' not installed.") return return super(SetupUtilsTests, self).run(*args, **kwargs) diff --git a/creole/tests/utils/base_unittest.py b/creole/tests/utils/base_unittest.py index 5f6bba4..3d28c94 100644 --- a/creole/tests/utils/base_unittest.py +++ b/creole/tests/utils/base_unittest.py @@ -10,7 +10,6 @@ """ - import re import warnings @@ -30,7 +29,6 @@ else: test_textile = True - try: from creole.rest_tools.clean_writer import rest2html except DocutilsImportError as err: @@ -42,7 +40,6 @@ else: tabs2spaces_re = re.compile(r"^(\t*)(.*?)$", re.M) - def tabs2spaces(html): """ form reformating textile html code >>> tabs2spaces("\\t<p>one<br />\\n\\t\\ttwo<br />\\n\\t\\t\\ttree</p>") @@ -72,11 +69,11 @@ def strip_html_lines(html, strip_lines=False): return html - class BaseCreoleTest(MarkupTest): """ Basic unittest class for all python-creole unittest classes. """ + def _debug_text(self, msg, raw_text): text = raw_text.replace(" ", ".") text = text.replace("\n", "\\n\n") @@ -89,12 +86,12 @@ class BaseCreoleTest(MarkupTest): print("-" * 79) def assert_creole2html( - self, raw_creole, raw_html, - strip_lines=False, debug=True, - parser_kwargs={}, emitter_kwargs={}, - block_rules=None, blog_line_breaks=True, macros=None, verbose=True, stderr=None, - strict=False, - ): + self, raw_creole, raw_html, + strip_lines=False, debug=True, + parser_kwargs={}, emitter_kwargs={}, + block_rules=None, blog_line_breaks=True, macros=None, verbose=True, stderr=None, + strict=False, + ): """ compare the generated html code from the markup string >creole_string< with the >html_string< reference. @@ -131,10 +128,10 @@ class BaseCreoleTest(MarkupTest): self.assertEqual(out_string, html_string, msg="creole2html") def assert_html2creole2(self, creole, html, - debug=True, - unknown_emit=None, - strict=False, - ): + debug=True, + unknown_emit=None, + strict=False, + ): # convert html code into creole markup out_string = html2creole( html, debug, unknown_emit=unknown_emit, strict=strict @@ -144,14 +141,14 @@ class BaseCreoleTest(MarkupTest): # compare self.assertEqual(out_string, creole, msg="html2creole") - def assert_html2creole(self, raw_creole, raw_html, \ - strip_lines=False, debug=True, - # OLD API: - parser_kwargs={}, emitter_kwargs={}, - # html2creole: - unknown_emit=None, - strict=False, - ): + def assert_html2creole(self, raw_creole, raw_html, + strip_lines=False, debug=True, + # OLD API: + parser_kwargs={}, emitter_kwargs={}, + # html2creole: + unknown_emit=None, + strict=False, + ): """ Compare the genereted markup from the given >raw_html< html code, with the given >creole_string< reference string. @@ -176,17 +173,17 @@ class BaseCreoleTest(MarkupTest): self.assert_html2creole2(creole, html, debug, unknown_emit, strict) def cross_compare_creole(self, creole_string, html_string, - strip_lines=False, debug=True, - # creole2html old API: - creole_parser_kwargs={}, html_emitter_kwargs={}, - # html2creole old API: - html_parser_kwargs={}, creole_emitter_kwargs={}, - - # creole2html new API: - block_rules=None, blog_line_breaks=True, macros=None, stderr=None, - # html2creole: - unknown_emit=None - ): + strip_lines=False, debug=True, + # creole2html old API: + creole_parser_kwargs={}, html_emitter_kwargs={}, + # html2creole old API: + html_parser_kwargs={}, creole_emitter_kwargs={}, + + # creole2html new API: + block_rules=None, blog_line_breaks=True, macros=None, stderr=None, + # html2creole: + unknown_emit=None + ): """ Cross compare with: * creole2html @@ -213,8 +210,8 @@ class BaseCreoleTest(MarkupTest): unknown_emit=unknown_emit, ) - def assert_html2textile(self, textile_string, html_string, \ - strip_lines=False, debug=False, parser_kwargs={}, emitter_kwargs={}): + def assert_html2textile(self, textile_string, html_string, + strip_lines=False, debug=False, parser_kwargs={}, emitter_kwargs={}): """ Check html2textile """ @@ -237,8 +234,8 @@ class BaseCreoleTest(MarkupTest): return textile_string, html_string - def cross_compare_textile(self, textile_string, html_string, \ - strip_lines=False, debug=False, parser_kwargs={}, emitter_kwargs={}): + def cross_compare_textile(self, textile_string, html_string, + strip_lines=False, debug=False, parser_kwargs={}, emitter_kwargs={}): """ Checks: * html2textile @@ -268,8 +265,8 @@ class BaseCreoleTest(MarkupTest): self.assertEqual(html_string, html, msg="textile2html") - def assert_html2rest(self, rest_string, html_string, \ - strip_lines=False, debug=False, parser_kwargs={}, emitter_kwargs={}): + def assert_html2rest(self, rest_string, html_string, + strip_lines=False, debug=False, parser_kwargs={}, emitter_kwargs={}): """ Check html to reStructuredText converter """ @@ -294,8 +291,8 @@ class BaseCreoleTest(MarkupTest): return rest_string, html_string - def assert_rest2html(self, rest_string, html_string, \ - strip_lines=False, debug=False, prepare_strings=True, **kwargs): + def assert_rest2html(self, rest_string, html_string, + strip_lines=False, debug=False, prepare_strings=True, **kwargs): # compare rest -> html if not REST_INSTALLED: @@ -321,10 +318,10 @@ class BaseCreoleTest(MarkupTest): self.assertEqual(html, html_string, msg="rest2html") - def cross_compare_rest(self, rest_string, html_string, \ - strip_lines=False, debug=False, parser_kwargs={}, emitter_kwargs={}): -# assert isinstance(textile_string, str) -# assert isinstance(html_string, str) + def cross_compare_rest(self, rest_string, html_string, + strip_lines=False, debug=False, parser_kwargs={}, emitter_kwargs={}): + # assert isinstance(textile_string, str) + # assert isinstance(html_string, str) self.assertNotEqual(rest_string, html_string) rest_string, html_string = self.assert_html2rest( @@ -340,11 +337,11 @@ class BaseCreoleTest(MarkupTest): ) def cross_compare(self, - html_string, - creole_string=None, - textile_string=None, - rest_string=None, - strip_lines=False, debug=False, parser_kwargs={}, emitter_kwargs={}): + html_string, + creole_string=None, + textile_string=None, + rest_string=None, + strip_lines=False, debug=False, parser_kwargs={}, emitter_kwargs={}): """ Cross compare with: * creole2html @@ -367,6 +364,7 @@ class BaseCreoleTest(MarkupTest): rest_string, html_string, strip_lines, debug, parser_kwargs, emitter_kwargs ) + if __name__ == '__main__': import doctest print(doctest.testmod()) diff --git a/creole/tests/utils/unittest_subprocess.py b/creole/tests/utils/unittest_subprocess.py index 16ef649..126a6bc 100644 --- a/creole/tests/utils/unittest_subprocess.py +++ b/creole/tests/utils/unittest_subprocess.py @@ -51,11 +51,11 @@ class SubprocessMixin: print(f"stderr: {stderr!r}") stdout = stdout.strip() - print("="*100) + print("=" * 100) print("stdout:") - print("-"*100) + print("-" * 100) print(stdout) - print("-"*100) + print("-" * 100) return popen_args, retcode, stdout def assertSubprocess(self, popen_args, retcode, stdout): |