diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..8637dba --- /dev/null +++ b/.flake8 @@ -0,0 +1,6 @@ +[flake8] +max-line-length = 120 +exclude = + .git, + build, + dist diff --git a/.vscode/settings.json b/.vscode/settings.json index 9b38853..ff801d3 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,5 +3,6 @@ "tests" ], "python.testing.unittestEnabled": false, - "python.testing.pytestEnabled": true + "python.testing.pytestEnabled": true, + "python.formatting.provider": "black" } \ No newline at end of file diff --git a/codecov.yml b/codecov.yml index bb6b121..fe4fe8c 100644 --- a/codecov.yml +++ b/codecov.yml @@ -3,4 +3,4 @@ coverage: project: default: target: 80% # the required coverage value - threshold: 1% \ No newline at end of file + threshold: 5% \ No newline at end of file diff --git a/mdutils/fileutils/fileutils.py b/mdutils/fileutils/fileutils.py index cacdab4..16de978 100644 --- a/mdutils/fileutils/fileutils.py +++ b/mdutils/fileutils/fileutils.py @@ -7,6 +7,7 @@ # MIT License: (C) 2018 Dídac Coll from typing import Optional + class MarkDownFile(object): """MarkDownFile class creates a new file of MarkDown extension. @@ -15,49 +16,56 @@ class MarkDownFile(object): - Rewrite a file with new data. - Write at the end of the file.""" - def __init__(self, name='', dirname: Optional[str] = None): + def __init__(self, name="", dirname: Optional[str] = None): """Creates a markdown file, if name is not empty. :param str name: provide the file name or a path joinly with the file name. For example: `./my-path/my-file.md`. - :param str dirname: use dirname if you want to provide the path separately from the name. + :param str dirname: use dirname if you want to provide the path separately from the name. If not you can specify the path directly on the name.""" if name: self.dirname = dirname self.file_name = self._get_file_name(name, dirname) - self.file = open(f'{self.file_name}', 'w+', encoding='UTF-8') + self.file = open(f"{self.file_name}", "w+", encoding="UTF-8") self.file.close() - def _get_file_name(self, name: str, dirname: Optional[str] = None ) -> str: - if dirname: - return f'{dirname}/{name}' if name.endswith('.md') else f'{dirname}/{name}.md' - - return name if name.endswith('.md') else f'{name}.md' + def _get_file_name(self, name: str, dirname: Optional[str] = None) -> str: + if dirname: + return ( + f"{dirname}/{name}" if name.endswith(".md") else f"{dirname}/{name}.md" + ) + + return name if name.endswith(".md") else f"{name}.md" def rewrite_all_file(self, data: str): """Rewrite all the data of a Markdown file by ``data``. - :param str data: is a string containing all the data that is written in the markdown file.""" - with open(f'{self.file_name}', 'w', encoding='utf-8') as self.file: + :param str data: is a string containing all the data that is written in the markdown file. + """ + with open(f"{self.file_name}", "w", encoding="utf-8") as self.file: self.file.write(data) def append_end(self, data: str): """Write at the last position of a Markdown file. - :param str data: is a string containing all the data that is written in the markdown file.""" - with open(f'{self.file_name}', 'a', encoding='utf-8') as self.file: + :param str data: is a string containing all the data that is written in the markdown file. + """ + with open(f"{self.file_name}", "a", encoding="utf-8") as self.file: self.file.write(data) def append_after_second_line(self, data: str): """Write after the file's first line. - :param str data: is a string containing all the data that is written in the markdown file.""" - with open(f'{self.file_name}', 'r+', encoding='utf-8') as self.file: + :param str data: is a string containing all the data that is written in the markdown file. + """ + with open(f"{self.file_name}", "r+", encoding="utf-8") as self.file: file_data = self.file.read() # Save all the file's content self.file.seek(0, 0) # Place file pointer at the beginning first_line = self.file.readline() # Read the first line second_line = self.file.readline() # Read the second line - self.file.seek(len(first_line + second_line), 0) # Place file pointer at the end of the first line + self.file.seek( + len(first_line + second_line), 0 + ) # Place file pointer at the end of the first line self.file.write(data) # Write data - self.file.write('\n' + file_data[len(first_line + second_line):]) + self.file.write("\n" + file_data[len(first_line + second_line):]) @staticmethod def read_file(file_name: str) -> str: @@ -68,15 +76,15 @@ def read_file(file_name: str) -> str: :return: return all file's data. :rtype: str""" - if file_name.find('.md') == -1: - file_name += '.md' + if file_name.find(".md") == -1: + file_name += ".md" - with open(file_name, 'r', encoding='utf-8') as file: + with open(file_name, "r", encoding="utf-8") as file: file_data = file.read() return file_data -if __name__ == '__main__': - new_file = MarkDownFile('Example') +if __name__ == "__main__": + new_file = MarkDownFile("Example") new_file.rewrite_all_file(data="# Some Text Example") diff --git a/mdutils/mdutils.py b/mdutils/mdutils.py index bce3f17..8cf9cc9 100644 --- a/mdutils/mdutils.py +++ b/mdutils/mdutils.py @@ -45,7 +45,7 @@ class MdUtils: - **file_data_text:** contains all the file data that will be written on the markdown file. """ - def __init__(self, file_name: str, title: str = '', author: str = ''): + def __init__(self, file_name: str, title: str = "", author: str = ""): """ :param file_name: it is the name of the Markdown file. @@ -59,7 +59,7 @@ def __init__(self, file_name: str, title: str = '', author: str = ''): self.author = author self.header = Header() self.textUtils = TextUtils - self.title = self.header.choose_header(level=1, title=title, style='setext') + self.title = self.header.choose_header(level=1, title=title, style="setext") self.table_of_contents = "" self.file_data_text = "" self._table_titles = [] @@ -71,7 +71,10 @@ def create_md_file(self) -> MarkDownFile: :return: return an instance of a MarkDownFile.""" md_file = MarkDownFile(self.file_name) md_file.rewrite_all_file( - data=self.title + self.table_of_contents + self.file_data_text + self.reference.get_references_as_markdown() + data=self.title + + self.table_of_contents + + self.file_data_text + + self.reference.get_references_as_markdown() ) return md_file @@ -79,7 +82,12 @@ def get_md_text(self) -> str: """Instead of writing the markdown text into a file it returns it as a string. :return: return a string with the markdown text.""" - return self.title + self.table_of_contents + self.file_data_text + self.reference.get_references_as_markdown() + return ( + self.title + + self.table_of_contents + + self.file_data_text + + self.reference.get_references_as_markdown() + ) def read_md_file(self, file_name: str) -> str: """Reads a Markdown file and save it to global class `file_data_text`. @@ -94,7 +102,14 @@ def read_md_file(self, file_name: str) -> str: return file_data - def new_header(self, level: int, title: str, style: str = 'atx', add_table_of_contents: str = 'y', header_id: str = '') -> str: + def new_header( + self, + level: int, + title: str, + style: str = "atx", + add_table_of_contents: str = "y", + header_id: str = "", + ) -> str: """Add a new header to the Markdown file. :param level: Header level. *atx* style can take values 1 til 6 and *setext* style take values 1 and 2. @@ -118,9 +133,11 @@ def new_header(self, level: int, title: str, style: str = 'atx', add_table_of_co '\\nHeader Title\\n-------------\\n' """ - if add_table_of_contents == 'y': + if add_table_of_contents == "y": self.__add_new_item_table_of_content(level, title) - self.___update_file_data(self.header.choose_header(level, title, style, header_id)) + self.___update_file_data( + self.header.choose_header(level, title, style, header_id) + ) return self.header.choose_header(level, title, style, header_id) def __add_new_item_table_of_content(self, level: int, item: Union[List[str], str]): @@ -135,7 +152,7 @@ def __add_new_item_table_of_content(self, level: int, item: Union[List[str], str curr = self._table_titles - for i in range(level-1): + for i in range(level - 1): curr = curr[-1] curr.append(item) @@ -143,8 +160,9 @@ def __add_new_item_table_of_content(self, level: int, item: Union[List[str], str if level < 6: curr.append([]) - - def new_table_of_contents(self, table_title: str = "Table of contents", depth: int = 1, marker: str = '') -> str: + def new_table_of_contents( + self, table_title: str = "Table of contents", depth: int = 1, marker: str = "" + ) -> str: """Table of contents can be created if Headers of 'atx' style have been defined. This method allows to create a table of contents and define a title for it. Moreover, `depth` allows user to @@ -164,19 +182,34 @@ def new_table_of_contents(self, table_title: str = "Table of contents", depth: i if marker: self.table_of_contents = "" - marker_table_of_contents = self.header.choose_header(level=1, title=table_title, style='setext') + marker_table_of_contents = self.header.choose_header( + level=1, title=table_title, style="setext" + ) marker_table_of_contents += mdutils.tools.TableOfContents.TableOfContents().create_table_of_contents( - self._table_titles, depth) - self.file_data_text = self.place_text_using_marker(marker_table_of_contents, marker) + self._table_titles, depth + ) + self.file_data_text = self.place_text_using_marker( + marker_table_of_contents, marker + ) else: marker_table_of_contents = "" - self.table_of_contents += self.header.choose_header(level=1, title=table_title, style='setext') + self.table_of_contents += self.header.choose_header( + level=1, title=table_title, style="setext" + ) self.table_of_contents += mdutils.tools.TableOfContents.TableOfContents().create_table_of_contents( - self._table_titles, depth) + self._table_titles, depth + ) return self.table_of_contents + marker_table_of_contents - def new_table(self, columns: int, rows: int, text: List[str], text_align: str = 'center', marker: str = '') -> str: + def new_table( + self, + columns: int, + rows: int, + text: List[str], + text_align: str = "center", + marker: str = "", + ) -> str: """This method takes a list of strings and creates a table. Using arguments ``columns`` and ``rows`` allows to create a table of *n* columns and *m* rows. The @@ -223,7 +256,14 @@ def new_table(self, columns: int, rows: int, text: List[str], text_align: str = return text_table - def new_paragraph(self, text: str = '', bold_italics_code: str = '', color: str = 'black', align: str = '', wrap_width:int = 0) -> str: + def new_paragraph( + self, + text: str = "", + bold_italics_code: str = "", + color: str = "black", + align: str = "", + wrap_width: int = 0, + ) -> str: """Add a new paragraph to Markdown file. The text is saved to the global variable file_data_text. :param text: is a string containing the paragraph text. Optionally, the paragraph text is returned. @@ -234,8 +274,8 @@ def new_paragraph(self, text: str = '', bold_italics_code: str = '', color: str :type color: str :param align: Using this parameter you can align text. :type align: str - :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. - Use width of 0 to disable wrapping. + :param wrap_width: wraps text with designated width by number of characters. By default, long words are not + broken. Use width of 0 to disable wrapping. :type wrap_width: int :return: ``'\\n\\n' + text``. Not necessary to take it, if only has to be written to the file. @@ -244,16 +284,32 @@ def new_paragraph(self, text: str = '', bold_italics_code: str = '', color: str """ if wrap_width > 0: - text = fill(text, wrap_width, break_long_words=False, replace_whitespace=False, drop_whitespace=False) - - if bold_italics_code or color != 'black' or align: - self.___update_file_data('\n\n' + self.textUtils.text_format(text, bold_italics_code, color, align)) + text = fill( + text, + wrap_width, + break_long_words=False, + replace_whitespace=False, + drop_whitespace=False, + ) + + if bold_italics_code or color != "black" or align: + self.___update_file_data( + "\n\n" + + self.textUtils.text_format(text, bold_italics_code, color, align) + ) else: - self.___update_file_data('\n\n' + text) + self.___update_file_data("\n\n" + text) return self.file_data_text - def new_line(self, text: str = '', bold_italics_code: str = '', color: str = 'black', align: str = '', wrap_width: int = 0) -> str: + def new_line( + self, + text: str = "", + bold_italics_code: str = "", + color: str = "black", + align: str = "", + wrap_width: int = 0, + ) -> str: """Add a new line to Markdown file. The text is saved to the global variable file_data_text. :param text: is a string containing the paragraph text. Optionally, the paragraph text is returned. @@ -264,8 +320,8 @@ def new_line(self, text: str = '', bold_italics_code: str = '', color: str = 'bl :type color: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str - :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. - Use width of 0 to disable wrapping. + :param wrap_width: wraps text with designated width by number of characters. By default, long words are not + broken. Use width of 0 to disable wrapping. :type wrap_width: int :return: return a string ``'\\n' + text``. Not necessary to take it, if only has to be written to the file. @@ -273,16 +329,33 @@ def new_line(self, text: str = '', bold_italics_code: str = '', color: str = 'bl """ if wrap_width > 0: - text = fill(text, wrap_width, break_long_words=False, replace_whitespace=False, drop_whitespace=False) - - if bold_italics_code or color != 'black' or align: - self.___update_file_data(' \n' + self.textUtils.text_format(text, bold_italics_code, color, align)) + text = fill( + text, + wrap_width, + break_long_words=False, + replace_whitespace=False, + drop_whitespace=False, + ) + + if bold_italics_code or color != "black" or align: + self.___update_file_data( + " \n" + + self.textUtils.text_format(text, bold_italics_code, color, align) + ) else: - self.___update_file_data(' \n' + text) + self.___update_file_data(" \n" + text) return self.file_data_text - def write(self, text: str = '', bold_italics_code: str = '', color: str = 'black', align: str = '', marker: str = '', wrap_width: int = 0) -> str: + def write( + self, + text: str = "", + bold_italics_code: str = "", + color: str = "black", + align: str = "", + marker: str = "", + wrap_width: int = 0, + ) -> str: """Write text in ``file_Data_text`` string. :param text: a text a string. @@ -293,15 +366,21 @@ def write(self, text: str = '', bold_italics_code: str = '', color: str = 'black :type color: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str - :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. - Use width of 0 to disable wrapping. + :param wrap_width: wraps text with designated width by number of characters. By default, long words are not + broken. Use width of 0 to disable wrapping. :type wrap_width: int :param marker: allows to replace a marker on some point of the file by the text. :type marker: str """ if wrap_width > 0: - text = fill(text, wrap_width, break_long_words=False, replace_whitespace=False, drop_whitespace=False) + text = fill( + text, + wrap_width, + break_long_words=False, + replace_whitespace=False, + drop_whitespace=False, + ) if bold_italics_code or color or align: new_text = self.textUtils.text_format(text, bold_italics_code, color, align) @@ -315,7 +394,7 @@ def write(self, text: str = '', bold_italics_code: str = '', color: str = 'black return new_text - def insert_code(self, code: str, language: str = '') -> str: + def insert_code(self, code: str, language: str = "") -> str: """This method allows to insert a peace of code on a markdown file. :param code: code string. @@ -325,7 +404,7 @@ def insert_code(self, code: str, language: str = '') -> str: :return: :rtype: str """ - md_code = '\n\n' + self.textUtils.insert_code(code, language) + md_code = "\n\n" + self.textUtils.insert_code(code, language) self.___update_file_data(md_code) return md_code @@ -342,7 +421,7 @@ def create_marker(self, text_marker: str) -> str: :rtype: str """ - new_marker = '##--[' + text_marker + ']--##' + new_marker = "##--[" + text_marker + "]--##" self.___update_file_data(new_marker) return new_marker @@ -364,7 +443,13 @@ def place_text_using_marker(self, text: str, marker: str) -> str: def ___update_file_data(self, file_data): self.file_data_text += file_data - def new_inline_link(self, link: str, text: Optional[str] = None, bold_italics_code: str = '', align: str = '') -> str: + def new_inline_link( + self, + link: str, + text: Optional[str] = None, + bold_italics_code: str = "", + align: str = "", + ) -> str: """Creates a inline link in markdown format. :param link: @@ -389,11 +474,20 @@ def new_inline_link(self, link: str, text: Optional[str] = None, bold_italics_co n_text = text if bold_italics_code or align: - n_text = self.textUtils.text_format(text=n_text, bold_italics_code=bold_italics_code, align=align) + n_text = self.textUtils.text_format( + text=n_text, bold_italics_code=bold_italics_code, align=align + ) return Inline.new_link(link=link, text=n_text) - def new_reference_link(self, link: str, text: str, reference_tag: Optional[str] = None, bold_italics_code: str = '', align: str = '') -> str: + def new_reference_link( + self, + link: str, + text: str, + reference_tag: Optional[str] = None, + bold_italics_code: str = "", + align: str = "", + ) -> str: """Creates a reference link in markdown format. All references will be stored at the end of the markdown file. @@ -433,16 +527,22 @@ def new_reference_link(self, link: str, text: str, reference_tag: Optional[str] """ if reference_tag is None: - if bold_italics_code != '': - raise TypeError('For using bold_italics_code param, reference_tag must be defined') - if align != '': - raise TypeError('For using align, reference_tag must be defined') + if bold_italics_code != "": + raise TypeError( + "For using bold_italics_code param, reference_tag must be defined" + ) + if align != "": + raise TypeError("For using align, reference_tag must be defined") n_text = text if bold_italics_code or align: - n_text = self.textUtils.text_format(text=n_text, bold_italics_code=bold_italics_code, align=align) + n_text = self.textUtils.text_format( + text=n_text, bold_italics_code=bold_italics_code, align=align + ) - return self.reference.new_link(link=link, text=n_text, reference_tag=reference_tag) + return self.reference.new_link( + link=link, text=n_text, reference_tag=reference_tag + ) @staticmethod def new_inline_image(text: str, path: str) -> str: @@ -459,7 +559,9 @@ def new_inline_image(text: str, path: str) -> str: return Image.new_inline_image(text=text, path=path) - def new_reference_image(self, text: str, path: str, reference_tag: Optional[str] = None) -> str: + def new_reference_image( + self, text: str, path: str, reference_tag: Optional[str] = None + ) -> str: """Add reference images in a markdown file. For example ``[MyImage][my_image]``. All references will be stored at the end of the markdown file. @@ -475,7 +577,9 @@ def new_reference_image(self, text: str, path: str, reference_tag: Optional[str] .. note:: If param reference_tag is not provided, text param will be used instead. """ - return self.image.new_reference_image(text=text, path=path, reference_tag=reference_tag) + return self.image.new_reference_image( + text=text, path=path, reference_tag=reference_tag + ) def new_list(self, items: List[str], marked_with: str = "-"): """Add unordered or ordered list in MarkDown file. @@ -488,7 +592,7 @@ def new_list(self, items: List[str], marked_with: str = "-"): :return: """ mdlist = MDList(items, marked_with) - self.___update_file_data('\n' + mdlist.get_md()) + self.___update_file_data("\n" + mdlist.get_md()) def new_checkbox_list(self, items: List[str], checked: bool = False): """Add checkbox list in MarkDown file. @@ -501,7 +605,7 @@ def new_checkbox_list(self, items: List[str], checked: bool = False): """ mdcheckbox = MDCheckbox(items=items, checked=checked) - self.___update_file_data('\n' + mdcheckbox.get_md()) + self.___update_file_data("\n" + mdcheckbox.get_md()) if __name__ == "__main__": diff --git a/mdutils/tools/Header.py b/mdutils/tools/Header.py index ae04e69..d55a7c5 100644 --- a/mdutils/tools/Header.py +++ b/mdutils/tools/Header.py @@ -25,7 +25,7 @@ class Header: # * Atx-Style * # ******************************************************************** @staticmethod - def atx_level_1(title: str, header_id: str = '') -> str: + def atx_level_1(title: str, header_id: str = "") -> str: """Return a atx level 1 header. :param str title: text title. @@ -34,12 +34,12 @@ def atx_level_1(title: str, header_id: str = '') -> str: :rtype: str """ if len(header_id): - header_id = ' {#' + header_id + '}' + header_id = " {#" + header_id + "}" - return '\n# ' + title + header_id + '\n' + return "\n# " + title + header_id + "\n" @staticmethod - def atx_level_2(title: str, header_id: str = '') -> str: + def atx_level_2(title: str, header_id: str = "") -> str: """Return a atx level 2 header. :param str title: text title. @@ -48,12 +48,12 @@ def atx_level_2(title: str, header_id: str = '') -> str: :rtype: str """ if len(header_id): - header_id = ' {#' + header_id + '}' + header_id = " {#" + header_id + "}" - return '\n## ' + title + header_id + '\n' + return "\n## " + title + header_id + "\n" @staticmethod - def atx_level_3(title: str, header_id: str = '') -> str: + def atx_level_3(title: str, header_id: str = "") -> str: """Return a atx level 3 header. :param str title: text title. @@ -62,12 +62,12 @@ def atx_level_3(title: str, header_id: str = '') -> str: :rtype: str """ if len(header_id): - header_id = ' {#' + header_id + '}' + header_id = " {#" + header_id + "}" - return '\n### ' + title + header_id + '\n' + return "\n### " + title + header_id + "\n" @staticmethod - def atx_level_4(title: str, header_id: str = '') -> str: + def atx_level_4(title: str, header_id: str = "") -> str: """Return a atx level 4 header. :param str title: text title. @@ -76,12 +76,12 @@ def atx_level_4(title: str, header_id: str = '') -> str: :rtype: str """ if len(header_id): - header_id = ' {#' + header_id + '}' + header_id = " {#" + header_id + "}" - return '\n#### ' + title + header_id + '\n' + return "\n#### " + title + header_id + "\n" @staticmethod - def atx_level_5(title: str, header_id: str = '') -> str: + def atx_level_5(title: str, header_id: str = "") -> str: """Return a atx level 5 header. :param str title: text title. @@ -90,12 +90,12 @@ def atx_level_5(title: str, header_id: str = '') -> str: :rtype: str """ if len(header_id): - header_id = ' {#' + header_id + '}' + header_id = " {#" + header_id + "}" - return '\n##### ' + title + header_id + '\n' + return "\n##### " + title + header_id + "\n" @staticmethod - def atx_level_6(title: str, header_id: str = '') -> str: + def atx_level_6(title: str, header_id: str = "") -> str: """Return a atx level 6 header. :param str title: text title. @@ -104,9 +104,9 @@ def atx_level_6(title: str, header_id: str = '') -> str: :rtype: str """ if len(header_id): - header_id = ' {#' + header_id + '}' + header_id = " {#" + header_id + "}" - return '\n###### ' + title + header_id + '\n' + return "\n###### " + title + header_id + "\n" # ******************************************************************** # * Setext-Style * @@ -120,21 +120,21 @@ def setext_level_1(title: str) -> str: :rtype: str """ - return '\n' + title + '\n' + ''.join(['=' for _ in title]) + '\n' + return "\n" + title + "\n" + "".join(["=" for _ in title]) + "\n" @staticmethod def setext_level_2(title: str) -> str: """Return a setext level 1 header. - :param str title: text title. - :return: a header titlte of form: ``'\\n' + title +'\\n------------\\n'``. - :rtype: str + :param str title: text title. + :return: a header titlte of form: ``'\\n' + title +'\\n------------\\n'``. + :rtype: str """ - return '\n' + title + '\n' + ''.join(['-' for _ in title]) + '\n' + return "\n" + title + "\n" + "".join(["-" for _ in title]) + "\n" @staticmethod - def header_anchor(text: str, link: str = '') -> str: + def header_anchor(text: str, link: str = "") -> str: """Creates an internal link of a defined Header level 1 or level 2 in the markdown file. Giving a text string an text link you can create an internal link of already existing header. If the ``link`` @@ -150,35 +150,37 @@ def header_anchor(text: str, link: str = '') -> str: **Example:** [Title 1](#title-1) """ if link: - if link[0] != '#': - link = link.lower().replace(' ', '-') + if link[0] != "#": + link = link.lower().replace(" ", "-") else: - link = '#' + link + link = "#" + link else: - link = '#' + text.lower().replace(' ', '-') + link = "#" + text.lower().replace(" ", "-") - return '[' + text + '](' + link + ')' + return "[" + text + "](" + link + ")" @staticmethod - def choose_header(level: int, title: str, style: str = 'atx', header_id: str = '') -> str: + def choose_header( + level: int, title: str, style: str = "atx", header_id: str = "" + ) -> str: # noinspection SpellCheckingInspection """This method choose the style and the header level. - :Examples: - >>> from mdutils.tools.Header import Header - >>> Header.choose_header(level=1, title='New Header', style='atx') - '\\n# New Header\\n' - - >>> Header.choose_header(level=2, title='Another Header 1', style='setext') - '\\nAnother Header 1\\n----------------\\n' - - :param level: Header Level, For Atx-style 1 til 6. For Setext-style 1 and 2 header levels. - :param title: Header Title. - :param style: Header Style atx or setext. - :param header_id: ID of the header for extended Markdown syntax - :return: - """ - if style.lower() == 'atx': + :Examples: + >>> from mdutils.tools.Header import Header + >>> Header.choose_header(level=1, title='New Header', style='atx') + '\\n# New Header\\n' + + >>> Header.choose_header(level=2, title='Another Header 1', style='setext') + '\\nAnother Header 1\\n----------------\\n' + + :param level: Header Level, For Atx-style 1 til 6. For Setext-style 1 and 2 header levels. + :param title: Header Title. + :param style: Header Style atx or setext. + :param header_id: ID of the header for extended Markdown syntax + :return: + """ + if style.lower() == "atx": if level == 1: return Header.atx_level_1(title, header_id) elif level == 2: @@ -192,18 +194,25 @@ def choose_header(level: int, title: str, style: str = 'atx', header_id: str = ' elif level == 6: return Header.atx_level_6(title, header_id) else: - raise ValueError("For 'atx' style, level's expected value: 1, 2, 3, 4, 5 or 6, but level = " - + str(level)) - elif style.lower() == 'setext': + raise ValueError( + "For 'atx' style, level's expected value: 1, 2, 3, 4, 5 or 6, but level = " + + str(level) + ) + elif style.lower() == "setext": if level == 1: return Header.setext_level_1(title) elif level == 2: return Header.setext_level_2(title) else: - raise ValueError("For 'setext' style, level's expected value: 1, 2, 3, 4, 5 or 6, but level = " - + str(level)) + raise ValueError( + "For 'setext' style, level's expected value: 1, 2, 3, 4, 5 or 6, but level = " + + str(level) + ) else: - raise ValueError("style's expected value: 'atx' or 'setext', but style = " + style.lower()) + raise ValueError( + "style's expected value: 'atx' or 'setext', but style = " + + style.lower() + ) if __name__ == "__main__": diff --git a/mdutils/tools/Html.py b/mdutils/tools/Html.py index a7c23e6..64aac0d 100644 --- a/mdutils/tools/Html.py +++ b/mdutils/tools/Html.py @@ -8,7 +8,6 @@ class Html: - @staticmethod def paragraph(text: str, align: str = None) -> str: """ @@ -20,7 +19,7 @@ def paragraph(text: str, align: str = None) -> str: """ if align is None: - return '

\n {}\n

'.format(text) + return "

\n {}\n

".format(text) if align is not None: if align not in ["left", "center", "right"]: @@ -49,14 +48,18 @@ def image(cls, path: str, size: str = None, align: str = None) -> str: """ if align: - return cls.paragraph(text=cls.__html_image(path=path, size=size), align=align) + return cls.paragraph( + text=cls.__html_image(path=path, size=size), align=align + ) return cls.__html_image(path=path, size=size) @classmethod def __html_image(cls, path: str, size: str = None): if size: - return ''.format(path, HtmlSize.size_to_width_and_height(size=size)) + return ''.format( + path, HtmlSize.size_to_width_and_height(size=size) + ) return ''.format(path) @@ -67,18 +70,20 @@ def size_to_width_and_height(cls, size: str) -> str: if size.isdigit(): return cls.__get_width(size=size) - if size.startswith('x'): + if size.startswith("x"): height = size[1:] if height.isdigit(): return cls.__get_height(size=height) raise SizeBadFormat(size) - width_height = size.split('x') + width_height = size.split("x") if len(width_height) == 2: if width_height[0].isdigit() and width_height[1].isdigit(): - return "{} {}".format(cls.__get_width(width_height[0]), cls.__get_height(width_height[1])) + return "{} {}".format( + cls.__get_width(width_height[0]), cls.__get_height(width_height[1]) + ) raise SizeBadFormat(size) @@ -98,6 +103,13 @@ def __get_height(cls, size: str): class SizeBadFormat(Exception): """Raise exception when size does not match the expected format""" + def __init__(self, message): - Exception.__init__(self, "Unexpected format: {}. Expected: '', 'x' or 'x'".format(message)) + Exception.__init__( + self, + "Unexpected format: {}. Expected: '', 'x' or 'x'".format( + message + ), + ) + pass diff --git a/mdutils/tools/Image.py b/mdutils/tools/Image.py index 8e96bf5..75bfc48 100644 --- a/mdutils/tools/Image.py +++ b/mdutils/tools/Image.py @@ -10,7 +10,6 @@ class Image: - def __init__(self, reference: Reference): """ :param reference: @@ -30,9 +29,11 @@ def new_inline_image(text: str, path: str, tooltip: str = None) -> str: :return: return the image in markdown format ``'![ + text + '](' + path + 'tooltip' + ')'``. :rtype: str """ - return '!' + Inline.new_link(link=path, text=text, tooltip=tooltip) + return "!" + Inline.new_link(link=path, text=text, tooltip=tooltip) - def new_reference_image(self, text: str, path: str, reference_tag: str = None, tooltip: str = None) -> str: + def new_reference_image( + self, text: str, path: str, reference_tag: str = None, tooltip: str = None + ) -> str: """ :param text: Text that is going to be displayed in the markdown file as a image. :type text: str @@ -45,7 +46,9 @@ def new_reference_image(self, text: str, path: str, reference_tag: str = None, t :return: return the image in markdown format ``'![ + text + '][' + reference_tag + ']'``. :rtype: str """ - return '!' + self.reference.new_link(link=path, text=text, reference_tag=reference_tag, tooltip=tooltip) + return "!" + self.reference.new_link( + link=path, text=text, reference_tag=reference_tag, tooltip=tooltip + ) if __name__ == "__main__": diff --git a/mdutils/tools/Link.py b/mdutils/tools/Link.py index 6db35bb..3245b17 100644 --- a/mdutils/tools/Link.py +++ b/mdutils/tools/Link.py @@ -9,7 +9,6 @@ class Reference: - def __init__(self): self.references = {} @@ -26,14 +25,16 @@ def get_references_as_markdown(self) -> str: :rtype: str """ if not bool(self.references): - return '' + return "" - references_as_markdown = '' + references_as_markdown = "" for key in sorted(self.references.keys()): - references_as_markdown += '[' + key + ']: ' + self.references[key] + '\n' - return '\n\n\n' + references_as_markdown + references_as_markdown += "[" + key + "]: " + self.references[key] + "\n" + return "\n\n\n" + references_as_markdown - def new_link(self, link: str, text: str, reference_tag: str = None, tooltip: str = None) -> str: + def new_link( + self, link: str, text: str, reference_tag: str = None, tooltip: str = None + ) -> str: """ :param link: :type link: str @@ -48,22 +49,23 @@ def new_link(self, link: str, text: str, reference_tag: str = None, tooltip: str """ if reference_tag is None: self.__update_ref(link, text, tooltip) - return '[' + text + ']' + return "[" + text + "]" self.__update_ref(link, reference_tag, tooltip) - return '[' + text + '][' + reference_tag + ']' + return "[" + text + "][" + reference_tag + "]" def __update_ref(self, link: str, reference_tag: str, tooltip: str = None): if not (reference_tag in self.references.keys()): if tooltip is not None: - self.references.update({reference_tag: TextUtils.add_tooltip(link, tooltip)}) + self.references.update( + {reference_tag: TextUtils.add_tooltip(link, tooltip)} + ) return self.references.update({reference_tag: link}) class Inline: - @staticmethod def new_link(link: str, text: str = None, tooltip: str = None): """ @@ -79,12 +81,16 @@ def new_link(link: str, text: str = None, tooltip: str = None): if tooltip: if text is None: - return Inline.__md_link(link=TextUtils.add_tooltip(link=link, tip=tooltip), text=link) + return Inline.__md_link( + link=TextUtils.add_tooltip(link=link, tip=tooltip), text=link + ) - return Inline.__md_link(link=TextUtils.add_tooltip(link=link, tip=tooltip), text=text) + return Inline.__md_link( + link=TextUtils.add_tooltip(link=link, tip=tooltip), text=text + ) if text is None: - return '<' + link + '>' + return "<" + link + ">" return Inline.__md_link(link=link, text=text) diff --git a/mdutils/tools/MDList.py b/mdutils/tools/MDList.py index 87d0a49..1c4c38e 100644 --- a/mdutils/tools/MDList.py +++ b/mdutils/tools/MDList.py @@ -5,7 +5,6 @@ # This file is part of mdutils. https://github.com/didix21/mdutils # # MIT License: (C) 2020 Dídac Coll -from typing import List import re @@ -39,12 +38,21 @@ def _get_ordered_markdown_list(self, items) -> str: return md_list def _add_new_item(self, item: str, marker: str): - item_with_hyphen = item if self._is_there_marker_in_item(item) else self._add_hyphen(item, marker) - return self._n_spaces(4 * self.n_tabs) + item_with_hyphen + '\n' + item_with_hyphen = ( + item + if self._is_there_marker_in_item(item) + else self._add_hyphen(item, marker) + ) + return self._n_spaces(4 * self.n_tabs) + item_with_hyphen + "\n" @classmethod def _is_there_marker_in_item(cls, item: str) -> bool: - if item.startswith('-') or item.startswith('*') or item.startswith('+') or re.search(r"^(\d\.)", item): + if ( + item.startswith("-") + or item.startswith("*") + or item.startswith("+") + or re.search(r"^(\d\.)", item) + ): return True return False @@ -58,10 +66,9 @@ def _n_spaces(cls, number_spaces: int = 1): class MDList(MDListHelper): - """This class allows to create unordered or ordered MarkDown list. + """This class allows to create unordered or ordered MarkDown list.""" - """ - def __init__(self, items, marked_with: str = '-'): + def __init__(self, items, marked_with: str = "-"): """ :param items: Array of items for generating the list. @@ -71,8 +78,11 @@ def __init__(self, items, marked_with: str = '-'): :type marked_with: str """ super().__init__() - self.md_list = self._get_ordered_markdown_list(items) if marked_with == '1' else \ - self._get_unordered_markdown_list(items, marked_with) + self.md_list = ( + self._get_ordered_markdown_list(items) + if marked_with == "1" + else self._get_unordered_markdown_list(items, marked_with) + ) def get_md(self) -> str: """Get the list in markdown format. @@ -84,9 +94,7 @@ def get_md(self) -> str: class MDCheckbox(MDListHelper): - """This class allows to create checkbox MarkDown list. - - """ + """This class allows to create checkbox MarkDown list.""" def __init__(self, items, checked: bool = False): """ @@ -97,17 +105,22 @@ def __init__(self, items, checked: bool = False): :type checked: bool """ super().__init__() - self.checked = " " if not checked else 'x' - self.md_list = self._get_unordered_markdown_list(items, marker=f'- [{self.checked}]') + self.checked = " " if not checked else "x" + self.md_list = self._get_unordered_markdown_list( + items, marker=f"- [{self.checked}]" + ) def get_md(self) -> str: return self.md_list def _add_new_item(self, item: str, marker: str): - item_with_hyphen = self._add_hyphen(item[2:], '- [x]') if self.__is_checked(item) \ + item_with_hyphen = ( + self._add_hyphen(item[2:], "- [x]") + if self.__is_checked(item) else self._add_hyphen(item, marker) - return self._n_spaces(4 * self.n_tabs) + item_with_hyphen + '\n' + ) + return self._n_spaces(4 * self.n_tabs) + item_with_hyphen + "\n" @classmethod def __is_checked(cls, item: str) -> bool: - return item.startswith('x') + return item.startswith("x") diff --git a/mdutils/tools/Table.py b/mdutils/tools/Table.py index b51694b..a5c24b9 100644 --- a/mdutils/tools/Table.py +++ b/mdutils/tools/Table.py @@ -9,14 +9,13 @@ class Table: - def __init__(self): self.rows = 0 self.columns = 0 @staticmethod def _align(columns: int, text_align: Optional[Union[str, Iterable]] = None) -> str: - """ This private method it's in charge of aligning text of a table. + """This private method it's in charge of aligning text of a table. - notes: more information about `text_align` @@ -31,45 +30,48 @@ def _align(columns: int, text_align: Optional[Union[str, Iterable]] = None) -> s .. note: """ - column_align_string = '' - ta2pat={ # text_align to pattern translator - 'center': ' :---: |', - 'left': ' :--- |', - 'right': ' ---: |', - None: ' --- |' + column_align_string = "" + ta2pat = { # text_align to pattern translator + "center": " :---: |", + "left": " :--- |", + "right": " ---: |", + None: " --- |", } if type(text_align) == str: - - text_align = [text_align.lower()]*columns - + text_align = [text_align.lower()] * columns + elif text_align is None: - - text_align = [None]*columns - + text_align = [None] * columns + else: - - text_align = list(text_align)[:columns] # make a local redimensionnable copy - + text_align = list(text_align)[ + :columns + ] # make a local redimensionnable copy + if len(text_align) < columns: - - text_align += [None]*(columns-len(text_align)) - - column_align_string = '|' - for i,ta in enumerate(text_align): - - if not ta is None: - + text_align += [None] * (columns - len(text_align)) + + column_align_string = "|" + for i, ta in enumerate(text_align): + if ta is not None: ta = ta.lower() - + if ta not in ta2pat: - - raise ValueError(f"text_align's expected value: 'right', 'center', 'left' or None , but in column {i+1} text_align = '{ta}'") - + raise ValueError( + f"text_align's expected value: 'right', 'center', 'left' or None , but in column {i+1} text_align = '{ta}'" + ) + column_align_string += ta2pat[ta] return column_align_string - def create_table(self, columns: int, rows: int, text: List[str], text_align: Optional[Union[str, list]] = None): + def create_table( + self, + columns: int, + rows: int, + text: List[str], + text_align: Optional[Union[str, list]] = None, + ): """This method takes a list of strings and creates a table. Using arguments ``columns`` and ``rows`` allows to create a table of *n* columns and *m* rows. @@ -79,7 +81,9 @@ def create_table(self, columns: int, rows: int, text: List[str], text_align: Opt :param int rows: number of rows of the table. :param text: a list of strings. :type text: list of str - :param str_or_list text_align: text align argument. Values available are: ``'right'``, ``'center'``, ``'left'`` and ``None`` (default). If text_align is a list then individual alignment can be set for each column. + :param str_or_list text_align: text align argument. + Values available are: ``'right'``, ``'center'``, ``'left'`` and ``None`` (default). + If text_align is a list then individual alignment can be set for each column. :return: a markdown table. :rtype: str @@ -102,7 +106,7 @@ def create_table(self, columns: int, rows: int, text: List[str], text_align: Opt """ self.columns = columns self.rows = rows - table = '\n' + table = "\n" column_align_string = self._align(columns, text_align) index = 0 if columns * rows == len(text): @@ -110,11 +114,11 @@ def create_table(self, columns: int, rows: int, text: List[str], text_align: Opt if row == 1: table += column_align_string # Row align, Example: '| :---: | :---: | ... | \n' else: - table += '|' + table += "|" for _ in range(columns): - table += str(text[index]).replace("|", r"\|") + '|' + table += str(text[index]).replace("|", r"\|") + "|" index += 1 - table += '\n' + table += "\n" return table else: raise ValueError("columns * rows is not equal to text length") diff --git a/mdutils/tools/TableOfContents.py b/mdutils/tools/TableOfContents.py index f432edc..5f18ebc 100644 --- a/mdutils/tools/TableOfContents.py +++ b/mdutils/tools/TableOfContents.py @@ -10,7 +10,7 @@ class TableOfContents: - def _loop_through(self, elements, tab: str = '', depth: int = 1) -> str: + def _loop_through(self, elements, tab: str = "", depth: int = 1) -> str: """Method that go through a list of elements that contain strings and other list and return a string. The returned string is ready to be written in a markdown file in order to create a table of contents. @@ -23,18 +23,29 @@ def _loop_through(self, elements, tab: str = '', depth: int = 1) -> str: :type depth: int :rtype: str """ - elements_to_string = '' + elements_to_string = "" for item in elements: if isinstance(item, list): if item and depth > 1: - elements_to_string += self._loop_through(item, tab=tab+'\t', depth=depth-1) + elements_to_string += self._loop_through( + item, tab=tab + "\t", depth=depth - 1 + ) else: - elements_to_string += '\n' + tab + '* [' + item + '](#' \ - + re.sub('[^a-z0-9_\-]', '', item.lower().replace(' ', '-')) + ')' + elements_to_string += ( + "\n" + + tab + + "* [" + + item + + "](#" + + re.sub("[^a-z0-9_\-]", "", item.lower().replace(" ", "-")) + + ")" + ) return elements_to_string - def create_table_of_contents(self, array_of_title_contents: List[str], depth: int = 1) -> str: + def create_table_of_contents( + self, array_of_title_contents: List[str], depth: int = 1 + ) -> str: """This method can create a table of contents using an array of the different titles. The depth can be changed. :param array_of_title_contents: a string list with the different headers. :type array_of_title_contents: list @@ -43,13 +54,17 @@ def create_table_of_contents(self, array_of_title_contents: List[str], depth: in :return: return a string ready to be written to a Markdown file. :rtype: str """ - if depth in range(1,7): - table_of_contents = '' - table_of_contents += self._loop_through(array_of_title_contents, depth=depth) - table_of_contents += '\n' + if depth in range(1, 7): + table_of_contents = "" + table_of_contents += self._loop_through( + array_of_title_contents, depth=depth + ) + table_of_contents += "\n" return table_of_contents else: - raise ValueError("depth's expected value: between 1 and 6, but depth = " + str(depth)) + raise ValueError( + "depth's expected value: between 1 and 6, but depth = " + str(depth) + ) if __name__ == "__main__": diff --git a/mdutils/tools/TextUtils.py b/mdutils/tools/TextUtils.py index 4ee603c..233aea8 100644 --- a/mdutils/tools/TextUtils.py +++ b/mdutils/tools/TextUtils.py @@ -8,9 +8,7 @@ class TextUtils: - """This class helps to create bold, italics and change color text. - - """ + """This class helps to create bold, italics and change color text.""" @staticmethod def bold(text: str) -> str: @@ -20,7 +18,7 @@ def bold(text: str) -> str: :type text: str :return: a string like this example: ``'**text**'`` :rtype: str""" - return '**' + text + '**' + return "**" + text + "**" @staticmethod def italics(text: str) -> str: @@ -30,7 +28,7 @@ def italics(text: str) -> str: :type text: str :return: a string like this example: ``'_text_'`` :rtype: str""" - return '*' + text + '*' + return "*" + text + "*" @staticmethod def inline_code(text: str) -> str: @@ -40,7 +38,7 @@ def inline_code(text: str) -> str: :type text: str :return: a string like this example: ``'``text``'`` :rtype: str""" - return '``' + text + '``' + return "``" + text + "``" @staticmethod def center_text(text: str) -> str: @@ -50,7 +48,7 @@ def center_text(text: str) -> str: :type text: str :return: a string like this exampple: ``'
text
'`` """ - return '
' + text + '
' + return "
" + text + "
" @staticmethod def text_color(text: str, color: str = "black") -> str: @@ -64,11 +62,11 @@ def text_color(text: str, color: str = "black") -> str: :type color: str :rtype: str """ - return '' + text + '' + return '' + text + "" @staticmethod - def text_external_link(text: str, link: str = '') -> str: - """ Using this method can be created an external link of a file or a web page. + def text_external_link(text: str, link: str = "") -> str: + """Using this method can be created an external link of a file or a web page. :param text: Text to be displayed. :type text: str @@ -77,10 +75,10 @@ def text_external_link(text: str, link: str = '') -> str: :return: return a string like this: ``'[Text to be shown](https://write.link.com)'`` :rtype: str""" - return '[' + text + '](' + link + ')' + return "[" + text + "](" + link + ")" @staticmethod - def insert_code(code: str, language: str = '') -> str: + def insert_code(code: str, language: str = "") -> str: """This method allows to insert a peace of code. :param code: code string. @@ -90,13 +88,15 @@ def insert_code(code: str, language: str = '') -> str: :return: markdown style. :rtype: str """ - if language == '': - return '```\n' + code + '\n```' + if language == "": + return "```\n" + code + "\n```" else: - return '```' + language + '\n' + code + '\n```' + return "```" + language + "\n" + code + "\n```" @staticmethod - def text_format(text: str, bold_italics_code: str = '', color: str = 'black', align: str = '') -> str: + def text_format( + text: str, bold_italics_code: str = "", color: str = "black", align: str = "" + ) -> str: """Text format helps to write multiple text format such as bold, italics and color. :param text: it is a string in which will be added the mew format @@ -118,26 +118,38 @@ def text_format(text: str, bold_italics_code: str = '', color: str = 'black', al """ new_text_format = text if bold_italics_code: - if ('c' in bold_italics_code) or ('b' in bold_italics_code) or ('i' in bold_italics_code): - if 'c' in bold_italics_code: + if ( + ("c" in bold_italics_code) + or ("b" in bold_italics_code) + or ("i" in bold_italics_code) + ): + if "c" in bold_italics_code: new_text_format = TextUtils.inline_code(new_text_format) else: - raise ValueError("unexpected bold_italics_code value, options available: 'b', 'c' or 'i'.") + raise ValueError( + "unexpected bold_italics_code value, options available: 'b', 'c' or 'i'." + ) - if color != 'black': + if color != "black": new_text_format = TextUtils.text_color(new_text_format, color) - if align == 'center': + if align == "center": new_text_format = TextUtils.center_text(new_text_format) if bold_italics_code: - if ('c' in bold_italics_code) or ('b' in bold_italics_code) or ('i' in bold_italics_code): - if 'b' in bold_italics_code: + if ( + ("c" in bold_italics_code) + or ("b" in bold_italics_code) + or ("i" in bold_italics_code) + ): + if "b" in bold_italics_code: new_text_format = TextUtils.bold(new_text_format) - if 'i' in bold_italics_code: + if "i" in bold_italics_code: new_text_format = TextUtils.italics(new_text_format) else: - raise ValueError("unexpected bold_italics_code value, options available: 'b', 'c' or 'i'.") + raise ValueError( + "unexpected bold_italics_code value, options available: 'b', 'c' or 'i'." + ) return new_text_format diff --git a/tests/test_mdutils.py b/tests/test_mdutils.py index 4eb70fa..39cfa6d 100644 --- a/tests/test_mdutils.py +++ b/tests/test_mdutils.py @@ -16,64 +16,91 @@ class TestMdUtils(TestCase): - def setUp(self) -> None: - self.expected_list = "\n\n\n" \ - "\n- Item 1\n" \ - "- Item 2\n" \ - "- Item 3\n" \ - "- Item 4\n" \ - " - Item 4.1\n" \ - " - Item 4.2\n" \ - " - Item 4.2.1\n" \ - " - Item 4.2.2\n" \ - " - Item 4.3\n" \ - " - Item 4.3.1\n" \ - "- Item 5\n" - self.complex_items = ["Item 1", "Item 2", "Item 3", "Item 4", - ["Item 4.1", "Item 4.2", - ["Item 4.2.1", "Item 4.2.2"], - "Item 4.3", ["Item 4.3.1"]], - "Item 5"] + self.expected_list = ( + "\n\n\n" + "\n- Item 1\n" + "- Item 2\n" + "- Item 3\n" + "- Item 4\n" + " - Item 4.1\n" + " - Item 4.2\n" + " - Item 4.2.1\n" + " - Item 4.2.2\n" + " - Item 4.3\n" + " - Item 4.3.1\n" + "- Item 5\n" + ) + self.complex_items = [ + "Item 1", + "Item 2", + "Item 3", + "Item 4", + [ + "Item 4.1", + "Item 4.2", + ["Item 4.2.1", "Item 4.2.2"], + "Item 4.3", + ["Item 4.3.1"], + ], + "Item 5", + ] def tearDown(self): - md_file = Path('Test_file.md') + md_file = Path("Test_file.md") if md_file.is_file(): - os.remove('Test_file.md') + os.remove("Test_file.md") def test_create_md_file(self): md_file = MdUtils("Test_file") md_file.create_md_file() - md_file_expect = Path('Test_file.md') + md_file_expect = Path("Test_file.md") if md_file_expect.is_file(): - os.remove('Test_file.md') + os.remove("Test_file.md") pass else: self.fail() def test_new_header(self): - file_name = 'Test_file' + file_name = "Test_file" md_file = MdUtils(file_name) - string_headers_expected = "\n# Header 0\n\n## Header 1\n\n### Header 2\n\n#### Header 3\n\n" \ - "##### Header 4\n\n###### Header 5 {#header5}\n" + string_headers_expected = ( + "\n# Header 0\n\n## Header 1\n\n### Header 2\n\n#### Header 3\n\n" + "##### Header 4\n\n###### Header 5 {#header5}\n" + ) string_headers = "" for x in range(6): # The last header includes an ID if x == 5: - string_headers += md_file.new_header(level=(x + 1), title='Header ' + str(x), style='atx', header_id='header5') + string_headers += md_file.new_header( + level=(x + 1), + title="Header " + str(x), + style="atx", + header_id="header5", + ) else: - string_headers += md_file.new_header(level=(x + 1), title='Header ' + str(x), style='atx') + string_headers += md_file.new_header( + level=(x + 1), title="Header " + str(x), style="atx" + ) self.assertEqual(string_headers, string_headers_expected) md_file.create_md_file() file_result = md_file.read_md_file(file_name) - self.assertEqual(file_result, '\n\n\n' + string_headers_expected) + self.assertEqual(file_result, "\n\n\n" + string_headers_expected) def test_new_table_of_contents(self): # Create headers level 1 and 2. md_file = MdUtils(file_name="Test_file", title="Testing table of contents") - list_headers = ["Header 1", "Header 1.1", "Header 2", "Header 2.2", "Header 2.3"] - table_of_content_title = MdUtils(file_name='').new_header(level=1, title='Index', style='setext') + list_headers = [ + "Header 1", + "Header 1.1", + "Header 2", + "Header 2.2", + "Header 2.3", + ] + table_of_content_title = MdUtils(file_name="").new_header( + level=1, title="Index", style="setext" + ) md_file.new_header(level=1, title=list_headers[0]) md_file.new_header(level=2, title=list_headers[1]) md_file.new_header(level=1, title=list_headers[2]) @@ -81,97 +108,150 @@ def test_new_table_of_contents(self): md_file.new_header(level=2, title=list_headers[4]) # Testing Depth 1 - table_of_contents_result = md_file.new_table_of_contents(table_title="Index", depth=1) - table_of_content_expected = table_of_content_title \ - + '\n* [' + list_headers[0] + '](#' \ - + re.sub('[^a-z0-9_\-]', '', list_headers[0].lower().replace(' ', '-')) + ')' \ - + '\n* [' + list_headers[2] + '](#' \ - + re.sub('[^a-z0-9_\-]', '', list_headers[2].lower().replace(' ', '-')) + ')\n' + table_of_contents_result = md_file.new_table_of_contents( + table_title="Index", depth=1 + ) + table_of_content_expected = ( + table_of_content_title + + "\n* [" + + list_headers[0] + + "](#" + + re.sub("[^a-z0-9_\-]", "", list_headers[0].lower().replace(" ", "-")) + + ")" + + "\n* [" + + list_headers[2] + + "](#" + + re.sub("[^a-z0-9_\-]", "", list_headers[2].lower().replace(" ", "-")) + + ")\n" + ) self.assertEqual(table_of_contents_result, table_of_content_expected) # Testing created file md_file.create_md_file() - data_file_result = MdUtils('').read_md_file('Test_file') - data_file_expected = MdUtils('').new_header(1, "Testing table of contents", 'setext') \ - + md_file.table_of_contents \ - + md_file.file_data_text + data_file_result = MdUtils("").read_md_file("Test_file") + data_file_expected = ( + MdUtils("").new_header(1, "Testing table of contents", "setext") + + md_file.table_of_contents + + md_file.file_data_text + ) self.assertEqual(data_file_result, data_file_expected) - os.remove('Test_file.md') + os.remove("Test_file.md") # Testing Depth 2 md_file = MdUtils(file_name="Test_file", title="Testing table of contents") - list_headers = ["Header 1", "Header 1.1", "Header 2", "Header 2.2", "Header 2.3"] - table_of_content_title = MdUtils(file_name='').new_header(level=1, title='Index', style='setext') + list_headers = [ + "Header 1", + "Header 1.1", + "Header 2", + "Header 2.2", + "Header 2.3", + ] + table_of_content_title = MdUtils(file_name="").new_header( + level=1, title="Index", style="setext" + ) md_file.new_header(level=1, title=list_headers[0]) md_file.new_header(level=2, title=list_headers[1]) md_file.new_header(level=1, title=list_headers[2]) md_file.new_header(level=2, title=list_headers[3]) md_file.new_header(level=2, title=list_headers[4]) - table_of_contents_result = md_file.new_table_of_contents(table_title="Index", depth=2) + table_of_contents_result = md_file.new_table_of_contents( + table_title="Index", depth=2 + ) table_of_content_expected = table_of_content_title for x in range(len(list_headers)): if x in (0, 2): - table_of_content_expected += '\n* [' + list_headers[x] + '](#' \ - + re.sub('[^a-z0-9_\-]', '', list_headers[x].lower().replace(' ', '-')) \ - + ')' + table_of_content_expected += ( + "\n* [" + + list_headers[x] + + "](#" + + re.sub( + "[^a-z0-9_\-]", "", list_headers[x].lower().replace(" ", "-") + ) + + ")" + ) else: - table_of_content_expected += '\n\t* [' + list_headers[x] + '](#' \ - + re.sub('[^a-z0-9_\-]', '', list_headers[x].lower().replace(' ', '-')) \ - + ')' - table_of_content_expected += '\n' + table_of_content_expected += ( + "\n\t* [" + + list_headers[x] + + "](#" + + re.sub( + "[^a-z0-9_\-]", "", list_headers[x].lower().replace(" ", "-") + ) + + ")" + ) + table_of_content_expected += "\n" self.assertEqual(table_of_contents_result, table_of_content_expected) md_file.create_md_file() - data_file_result = MdUtils('').read_md_file('Test_file') - data_file_expected = MdUtils('').new_header(1, "Testing table of contents", 'setext') \ - + md_file.table_of_contents \ - + md_file.file_data_text + data_file_result = MdUtils("").read_md_file("Test_file") + data_file_expected = ( + MdUtils("").new_header(1, "Testing table of contents", "setext") + + md_file.table_of_contents + + md_file.file_data_text + ) self.assertEqual(data_file_result, data_file_expected) - os.remove('Test_file.md') + os.remove("Test_file.md") def test_new_paragraph(self): md_file = MdUtils(file_name="Test_file", title="") - created_value = md_file.new_paragraph("This is a new paragraph created using new_paragraph method.") - expected_value = '\n\nThis is a new paragraph created using new_paragraph method.' + created_value = md_file.new_paragraph( + "This is a new paragraph created using new_paragraph method." + ) + expected_value = ( + "\n\nThis is a new paragraph created using new_paragraph method." + ) self.assertEqual(created_value, expected_value) def test_new_line(self): md_file = MdUtils(file_name="Test_file", title="") - created_value = md_file.new_line("This is a new line created using new_line method.") - expected_value = ' \nThis is a new line created using new_line method.' + created_value = md_file.new_line( + "This is a new line created using new_line method." + ) + expected_value = " \nThis is a new line created using new_line method." self.assertEqual(created_value, expected_value) def test_wrap_text(self): md_file = MdUtils(file_name="Test_file", title="") - created_value = md_file.new_line("This is a new line created using new_line method with wrapping.", wrap_width=25) - expected_value = ' \nThis is a new line \ncreated using new_line \nmethod with wrapping.' - self.assertEqual(created_value, expected_value) + created_value = md_file.new_line( + "This is a new line created using new_line method with wrapping.", + wrap_width=25, + ) + expected_value = ( + " \nThis is a new line \ncreated using new_line \nmethod with wrapping." + ) + self.assertEqual(created_value, expected_value) def test_insert_code(self): - md_file = MdUtils(file_name='Test_file') - code = ("mdFile.new_header(level=1, title='Atx Header 1')\n" - "mdFile.new_header(level=2, title='Atx Header 2')\n" - "mdFile.new_header(level=3, title='Atx Header 3')\n" - "mdFile.new_header(level=4, title='Atx Header 4')\n" - "mdFile.new_header(level=5, title='Atx Header 5')\n" - "mdFile.new_header(level=6, title='Atx Header 6')\n") - expects = '\n\n```\n' + code + '\n```' + md_file = MdUtils(file_name="Test_file") + code = ( + "mdFile.new_header(level=1, title='Atx Header 1')\n" + "mdFile.new_header(level=2, title='Atx Header 2')\n" + "mdFile.new_header(level=3, title='Atx Header 3')\n" + "mdFile.new_header(level=4, title='Atx Header 4')\n" + "mdFile.new_header(level=5, title='Atx Header 5')\n" + "mdFile.new_header(level=6, title='Atx Header 6')\n" + ) + expects = "\n\n```\n" + code + "\n```" self.assertEqual(md_file.insert_code(code), expects) - language = 'python' - expects = '\n\n```' + language + '\n' + code + '\n```' + language = "python" + expects = "\n\n```" + language + "\n" + code + "\n```" self.assertEqual(md_file.insert_code(code, language), expects) def test_new_inline_link(self): md_file = MdUtils(file_name="Test_file", title="") - created_value = md_file.new_inline_link(link="https://github.com/didix21/mdutils", text="mdutils library") - expected_value = '[mdutils library](https://github.com/didix21/mdutils)' + created_value = md_file.new_inline_link( + link="https://github.com/didix21/mdutils", text="mdutils library" + ) + expected_value = "[mdutils library](https://github.com/didix21/mdutils)" self.assertEqual(expected_value, created_value) def test_new_inline_link_text_empty(self): link = "https://github.com/didix21/mdutils" md_file = MdUtils(file_name="Test_file", title="") created_value = md_file.new_inline_link(link=link, text=link) - expected_value = '[https://github.com/didix21/mdutils](https://github.com/didix21/mdutils)' + expected_value = ( + "[https://github.com/didix21/mdutils](https://github.com/didix21/mdutils)" + ) self.assertEqual(expected_value, created_value) @@ -188,7 +268,7 @@ def test_new_inline_link_bold_format(self): link = "https://github.com/didix21/mdutils" text = "mdutils" md_file = MdUtils(file_name="Test_file", title="") - expected_value = '[**' + text + '**](' + link + ')' + expected_value = "[**" + text + "**](" + link + ")" created_value = md_file.new_inline_link(link, text, bold_italics_code="b") self.assertEqual(expected_value, created_value) @@ -197,7 +277,7 @@ def test_new_inline_link_italic_format(self): link = "https://github.com/didix21/mdutils" text = "mdutils" md_file = MdUtils(file_name="Test_file", title="") - expected_value = '[*' + text + '*](' + link + ')' + expected_value = "[*" + text + "*](" + link + ")" created_value = md_file.new_inline_link(link, text, bold_italics_code="i") self.assertEqual(expected_value, created_value) @@ -206,7 +286,7 @@ def test_new_inline_link_code_format(self): link = "https://github.com/didix21/mdutils" text = "mdutils" md_file = MdUtils(file_name="Test_file", title="") - expected_value = '[``' + text + '``](' + link + ')' + expected_value = "[``" + text + "``](" + link + ")" created_value = md_file.new_inline_link(link, text, bold_italics_code="c") self.assertEqual(expected_value, created_value) @@ -215,7 +295,7 @@ def test_new_inline_link_bold_italic_format(self): link = "https://github.com/didix21/mdutils" text = "mdutils" md_file = MdUtils(file_name="Test_file", title="") - expected_value = '[***' + text + '***](' + link + ')' + expected_value = "[***" + text + "***](" + link + ")" created_value = md_file.new_inline_link(link, text, bold_italics_code="bi") self.assertEqual(expected_value, created_value) @@ -224,7 +304,7 @@ def test_new_inline_link_bold_italic_code_format(self): link = "https://github.com/didix21/mdutils" text = "mdutils" md_file = MdUtils(file_name="Test_file", title="") - expected_value = '[***``' + text + '``***](' + link + ')' + expected_value = "[***``" + text + "``***](" + link + ")" created_value = md_file.new_inline_link(link, text, bold_italics_code="bic") self.assertEqual(expected_value, created_value) @@ -233,8 +313,8 @@ def test_new_inline_link_align_format(self): link = "https://github.com/didix21/mdutils" text = "mdutils" md_file = MdUtils(file_name="Test_file", title="") - expected_value = '[
' + text + '
](' + link + ')' - created_value = md_file.new_inline_link(link, text, align='center') + expected_value = "[
" + text + "
](" + link + ")" + created_value = md_file.new_inline_link(link, text, align="center") self.assertEqual(expected_value, created_value) @@ -242,35 +322,40 @@ def test_new_reference_link(self): md_file = MdUtils(file_name="Test_file", title="") text = "mdutils library" reference_tag = "mdutils library" - expected_value = '[' + text + '][' + reference_tag + ']' + expected_value = "[" + text + "][" + reference_tag + "]" created_value = md_file.new_reference_link( link="https://github.com/didix21/mdutils", text=text, - reference_tag=reference_tag) + reference_tag=reference_tag, + ) self.assertEqual(expected_value, created_value) - def test_new_reference_link_when_reference_tag_not_defined_and_bold_italics_code_is_defined(self): + def test_new_reference_link_when_reference_tag_not_defined_and_bold_italics_code_is_defined( + self, + ): md_file = MdUtils(file_name="Test_file", title="") text = "mdutils library" try: md_file.new_reference_link( link="https://github.com/didix21/mdutils", text=text, - bold_italics_code='b') + bold_italics_code="b", + ) except TypeError: return self.fail() - def test_new_reference_link_when_reference_tag_not_defined_and_align_is_defined(self): + def test_new_reference_link_when_reference_tag_not_defined_and_align_is_defined( + self, + ): md_file = MdUtils(file_name="Test_file", title="") text = "mdutils library" try: md_file.new_reference_link( - link="https://github.com/didix21/mdutils", - text=text, - align='center') + link="https://github.com/didix21/mdutils", text=text, align="center" + ) except TypeError: return @@ -280,11 +365,13 @@ def test_new_bold_reference_link(self): md_file = MdUtils(file_name="Test_file", title="") text = "mdutils library" reference_tag = "mdutils library" - expected_value = '[**' + text + '**][' + reference_tag + ']' + expected_value = "[**" + text + "**][" + reference_tag + "]" created_value = md_file.new_reference_link( link="https://github.com/didix21/mdutils", text=text, - reference_tag=reference_tag, bold_italics_code='b') + reference_tag=reference_tag, + bold_italics_code="b", + ) self.assertEqual(expected_value, created_value) @@ -292,11 +379,13 @@ def test_new_italics_reference_link(self): md_file = MdUtils(file_name="Test_file", title="") text = "mdutils library" reference_tag = "mdutils library" - expected_value = '[*' + text + '*][' + reference_tag + ']' + expected_value = "[*" + text + "*][" + reference_tag + "]" created_value = md_file.new_reference_link( link="https://github.com/didix21/mdutils", text=text, - reference_tag=reference_tag, bold_italics_code='i') + reference_tag=reference_tag, + bold_italics_code="i", + ) self.assertEqual(expected_value, created_value) @@ -304,11 +393,13 @@ def test_new_code_reference_link(self): md_file = MdUtils(file_name="Test_file", title="") text = "mdutils library" reference_tag = "mdutils library" - expected_value = '[``' + text + '``][' + reference_tag + ']' + expected_value = "[``" + text + "``][" + reference_tag + "]" created_value = md_file.new_reference_link( link="https://github.com/didix21/mdutils", text=text, - reference_tag=reference_tag, bold_italics_code='c') + reference_tag=reference_tag, + bold_italics_code="c", + ) self.assertEqual(expected_value, created_value) @@ -319,56 +410,67 @@ def test_references_placed_in_markdown_file(self): reference_tag = "mdutils library" link = "https://github.com/didix21/mdutils" - expected_value = "\n\n\n[mdutils library0][mdutils library0]\n" \ - "[mdutils library1][mdutils library1]\n" \ - "[mdutils library2][mdutils library2]\n" \ - "[mdutils library3][mdutils library3]\n" \ - "\n\n\n" \ - "[mdutils library0]: https://github.com/didix21/mdutils0\n" \ - "[mdutils library1]: https://github.com/didix21/mdutils1\n" \ - "[mdutils library2]: https://github.com/didix21/mdutils2\n" \ - "[mdutils library3]: https://github.com/didix21/mdutils3\n" + expected_value = ( + "\n\n\n[mdutils library0][mdutils library0]\n" + "[mdutils library1][mdutils library1]\n" + "[mdutils library2][mdutils library2]\n" + "[mdutils library3][mdutils library3]\n" + "\n\n\n" + "[mdutils library0]: https://github.com/didix21/mdutils0\n" + "[mdutils library1]: https://github.com/didix21/mdutils1\n" + "[mdutils library2]: https://github.com/didix21/mdutils2\n" + "[mdutils library3]: https://github.com/didix21/mdutils3\n" + ) for i in range(4): - md_file.write(md_file.new_reference_link( - link=link + str(i), - text=text + str(i), - reference_tag=reference_tag + str(i))) - md_file.write('\n') + md_file.write( + md_file.new_reference_link( + link=link + str(i), + text=text + str(i), + reference_tag=reference_tag + str(i), + ) + ) + md_file.write("\n") md_file.create_md_file() - created_data = MarkDownFile.read_file('Test_file.md') + created_data = MarkDownFile.read_file("Test_file.md") self.assertEqual(expected_value, created_data) def test_new_inline_image(self): md_file = MdUtils(file_name="Test_file", title="") - expected_image = '![image](../image.png)' - created_image = md_file.new_inline_image(text='image', path='../image.png') + expected_image = "![image](../image.png)" + created_image = md_file.new_inline_image(text="image", path="../image.png") self.assertEqual(expected_image, created_image) def test_new_reference_image(self): md_file = MdUtils(file_name="Test_file", title="") - expected_image = '![image][reference]' - created_image = md_file.new_reference_image(text='image', path='../image.png', reference_tag="reference") + expected_image = "![image][reference]" + created_image = md_file.new_reference_image( + text="image", path="../image.png", reference_tag="reference" + ) self.assertEqual(expected_image, created_image) def test_new_reference_image_markdown_data(self): md_file = MdUtils(file_name="Test_file", title="") - expected_image_1 = '![image_1][reference]' - expected_image_2 = '![image_2]' - image_1 = md_file.new_reference_image(text='image_1', path='../image.png', reference_tag="reference") - image_2 = md_file.new_reference_image(text='image_2', path='../image_2.png') - - expected_created_data = "\n\n\n" \ - " \n{}".format(expected_image_1) + \ - " \n{}".format(expected_image_2) + \ - "\n\n\n" \ - "[image_2]: ../image_2.png\n" \ - "[reference]: ../image.png\n" + expected_image_1 = "![image_1][reference]" + expected_image_2 = "![image_2]" + image_1 = md_file.new_reference_image( + text="image_1", path="../image.png", reference_tag="reference" + ) + image_2 = md_file.new_reference_image(text="image_2", path="../image_2.png") + + expected_created_data = ( + "\n\n\n" + " \n{}".format(expected_image_1) + + " \n{}".format(expected_image_2) + + "\n\n\n" + "[image_2]: ../image_2.png\n" + "[reference]: ../image.png\n" + ) md_file.new_line(image_1) md_file.new_line(image_2) @@ -383,18 +485,24 @@ def test_new_list(self): md_file.new_list(self.complex_items) md_file.create_md_file() - self.assertEqual(self.expected_list, MarkDownFile.read_file('Test_file.md')) + self.assertEqual(self.expected_list, MarkDownFile.read_file("Test_file.md")) def test_new_checkbox_list(self): md_file = MdUtils(file_name="Test_file", title="") md_file.new_checkbox_list(self.complex_items) md_file.create_md_file() - self.assertEqual(self.expected_list.replace('-', '- [ ]'), MarkDownFile.read_file('Test_file.md')) + self.assertEqual( + self.expected_list.replace("-", "- [ ]"), + MarkDownFile.read_file("Test_file.md"), + ) def test_new_checkbox_checked_list(self): md_file = MdUtils(file_name="Test_file", title="") md_file.new_checkbox_list(self.complex_items, checked=True) md_file.create_md_file() - self.assertEqual(self.expected_list.replace('-', '- [x]'), MarkDownFile.read_file('Test_file.md')) + self.assertEqual( + self.expected_list.replace("-", "- [x]"), + MarkDownFile.read_file("Test_file.md"), + ) diff --git a/tests/test_tools/test_header.py b/tests/test_tools/test_header.py index 1c37e46..ecd7f53 100644 --- a/tests/test_tools/test_header.py +++ b/tests/test_tools/test_header.py @@ -11,76 +11,85 @@ class TestHeader(TestCase): - def test_atx_level_1(self): title = "Text Title Atx 1" header_id = "myheader" - result = '\n# ' + title + '\n' - result2 = '\n# ' + title + ' {#myheader}' + '\n' + result = "\n# " + title + "\n" + result2 = "\n# " + title + " {#myheader}" + "\n" self.assertEqual(Header().atx_level_1(title), result) self.assertEqual(Header().atx_level_1(title, header_id), result2) def test_atx_level_2(self): title = "Text Title Atx 2" header_id = "myheader" - result = '\n## ' + title + '\n' - result2 = '\n## ' + title + ' {#myheader}' + '\n' + result = "\n## " + title + "\n" + result2 = "\n## " + title + " {#myheader}" + "\n" self.assertEqual(Header().atx_level_2(title), result) self.assertEqual(Header().atx_level_2(title, header_id), result2) def test_atx_level_3(self): title = "Text Title Atx 3" header_id = "myheader" - result = '\n### ' + title + '\n' - result2 = '\n### ' + title + ' {#myheader}' + '\n' + result = "\n### " + title + "\n" + result2 = "\n### " + title + " {#myheader}" + "\n" self.assertEqual(Header().atx_level_3(title), result) self.assertEqual(Header().atx_level_3(title, header_id), result2) def test_atx_level_4(self): title = "Text Title Atx 4" header_id = "myheader" - result = '\n#### ' + title + '\n' - result2 = '\n#### ' + title + ' {#myheader}' + '\n' + result = "\n#### " + title + "\n" + result2 = "\n#### " + title + " {#myheader}" + "\n" self.assertEqual(Header().atx_level_4(title), result) self.assertEqual(Header().atx_level_4(title, header_id), result2) def test_atx_level_5(self): title = "Text Title Atx 5" header_id = "myheader" - result = '\n##### ' + title + '\n' - result2 = '\n##### ' + title + ' {#myheader}' + '\n' + result = "\n##### " + title + "\n" + result2 = "\n##### " + title + " {#myheader}" + "\n" self.assertEqual(Header().atx_level_5(title), result) self.assertEqual(Header().atx_level_5(title, header_id), result2) def test_atx_level_6(self): title = "Text Title Atx 6" header_id = "myheader" - result = '\n###### ' + title + '\n' - result2 = '\n###### ' + title + ' {#myheader}' + '\n' + result = "\n###### " + title + "\n" + result2 = "\n###### " + title + " {#myheader}" + "\n" self.assertEqual(Header().atx_level_6(title), result) self.assertEqual(Header().atx_level_6(title, header_id), result2) def test_setext_level_1(self): title = "Text Title Setext 1" - result = '\n' + title + '\n' + ''.join(['=' for _ in title]) + '\n' + result = "\n" + title + "\n" + "".join(["=" for _ in title]) + "\n" self.assertEqual(Header().setext_level_1(title), result) def test_setext_level_2(self): title = "Text Title Setext 2" - result = '\n' + title + '\n' + ''.join(['-' for _ in title]) + '\n' + result = "\n" + title + "\n" + "".join(["-" for _ in title]) + "\n" self.assertEqual(Header().setext_level_2(title), result) def test_choose_header(self): header = Header() - func_list = [header.atx_level_1('Atx Example'), header.atx_level_2('Atx Example'), - header.atx_level_3('Atx Example'), header.atx_level_4('Atx Example'), - header.atx_level_5('Atx Example'), header.atx_level_6('Atx Example'), - header.setext_level_1('Setext Example'), header.setext_level_2('Setext Example')] + func_list = [ + header.atx_level_1("Atx Example"), + header.atx_level_2("Atx Example"), + header.atx_level_3("Atx Example"), + header.atx_level_4("Atx Example"), + header.atx_level_5("Atx Example"), + header.atx_level_6("Atx Example"), + header.setext_level_1("Setext Example"), + header.setext_level_2("Setext Example"), + ] for x in range(8): if x < 6: - title = 'Atx Example' - chosen_header = header.choose_header(level=x + 1, title=title, style='atx') + title = "Atx Example" + chosen_header = header.choose_header( + level=x + 1, title=title, style="atx" + ) else: - title = 'Setext Example' - chosen_header = header.choose_header(level=x - 5, title=title, style='setext') + title = "Setext Example" + chosen_header = header.choose_header( + level=x - 5, title=title, style="setext" + ) self.assertEqual(chosen_header, func_list[x]) diff --git a/tests/test_tools/test_html.py b/tests/test_tools/test_html.py index 8d07dd6..decd0dc 100644 --- a/tests/test_tools/test_html.py +++ b/tests/test_tools/test_html.py @@ -11,13 +11,12 @@ class TestHtml(TestCase): - def setUp(self): self.text = "my text" self.path = "./my_path" def test_paragraph(self): - expected_paragraph = "

\n {}\n

".format("left", self.text) + expected_paragraph = '

\n {}\n

'.format("left", self.text) actual_paragraph = Html.paragraph(text=self.text, align="left") self.assertEqual(expected_paragraph, actual_paragraph) @@ -30,7 +29,7 @@ def test_paragraph_when_align_is_not_defined(self): def test_paragraph_when_invalid_align_is_passed(self): try: - Html.paragraph(text=self.text, align='') + Html.paragraph(text=self.text, align="") except KeyError: return @@ -43,7 +42,7 @@ def test_image_path(self): self.assertEqual(expected_image, actual_image) def test_image_size_width(self): - size = '200' + size = "200" expected_image = ''.format(self.path, size) actual_image = Html.image(path=self.path, size=size) @@ -51,38 +50,41 @@ def test_image_size_width(self): def test_image_size_height(self): expected_image = ''.format(self.path) - actual_image = Html.image(path=self.path, size='x200') + actual_image = Html.image(path=self.path, size="x200") self.assertEqual(expected_image, actual_image) def test_image_size_width_height(self): - size = '200' - expected_image = ''.format(self.path, size, size) - actual_image = Html.image(path=self.path, size='200x200') + size = "200" + expected_image = ''.format( + self.path, size, size + ) + actual_image = Html.image(path=self.path, size="200x200") self.assertEqual(expected_image, actual_image) def test_image_align_center(self): html_image = ''.format(self.path) - expected_image = "

\n {}\n

".format("center", html_image) - actual_image = Html.image(path=self.path, align='center') + expected_image = '

\n {}\n

'.format("center", html_image) + actual_image = Html.image(path=self.path, align="center") self.assertEqual(expected_image, actual_image) def test_image_align_center_width_height(self): - size = '200' - html_image = ''.format(self.path, size, size) - expected_image = "

\n {}\n

".format("center", html_image) - actual_image = Html.image(path=self.path, size='200x200', align='center') + size = "200" + html_image = ''.format( + self.path, size, size + ) + expected_image = '

\n {}\n

'.format("center", html_image) + actual_image = Html.image(path=self.path, size="200x200", align="center") self.assertEqual(expected_image, actual_image) class TestHtmlSize(TestCase): - def test_raise_exception(self): try: - HtmlSize.size_to_width_and_height(size='dd') + HtmlSize.size_to_width_and_height(size="dd") except SizeBadFormat: return @@ -90,19 +92,19 @@ def test_raise_exception(self): def test_size_to_width_height_when_providing_number(self): expected = 'width="200"' - actual = HtmlSize.size_to_width_and_height(size='200') + actual = HtmlSize.size_to_width_and_height(size="200") self.assertEqual(expected, actual) def test_size_to_width_height_when_providing_x_int(self): expected = 'height="200"' - actual = HtmlSize.size_to_width_and_height(size='x200') + actual = HtmlSize.size_to_width_and_height(size="x200") self.assertEqual(expected, actual) def test_size_to_width_height_when_providing_x_str_int(self): try: - HtmlSize.size_to_width_and_height(size='xD200') + HtmlSize.size_to_width_and_height(size="xD200") except SizeBadFormat: return @@ -110,19 +112,19 @@ def test_size_to_width_height_when_providing_x_str_int(self): def test_size_to_width_height_when_providing_int_x_int(self): expected = 'width="200" height="300"' - actual = HtmlSize.size_to_width_and_height(size='200x300') + actual = HtmlSize.size_to_width_and_height(size="200x300") self.assertEqual(expected, actual) def test_size_to_width_height_when_providing_int_whitespace_X_int(self): expected = 'width="200" height="300"' - actual = HtmlSize.size_to_width_and_height(size='200 X300') + actual = HtmlSize.size_to_width_and_height(size="200 X300") self.assertEqual(expected, actual) def test_size_to_width_height_when_providing_x_str_int(self): try: - HtmlSize.size_to_width_and_height(size='200dx200') + HtmlSize.size_to_width_and_height(size="200dx200") except SizeBadFormat: return @@ -130,7 +132,7 @@ def test_size_to_width_height_when_providing_x_str_int(self): def test_size_to_width_height_when_providing_x_str_int(self): try: - HtmlSize.size_to_width_and_height(size='fx200') + HtmlSize.size_to_width_and_height(size="fx200") except SizeBadFormat: return diff --git a/tests/test_tools/test_image.py b/tests/test_tools/test_image.py index 314b5ad..3f98de7 100644 --- a/tests/test_tools/test_image.py +++ b/tests/test_tools/test_image.py @@ -6,8 +6,8 @@ # # MIT License: (C) 2020 Dídac Coll -__author__ = 'didix21' -__project__ = 'MdUtils' +__author__ = "didix21" +__project__ = "MdUtils" from unittest import TestCase from mdutils.tools.Image import Image @@ -15,27 +15,28 @@ class TestLink(TestCase): - def setUp(self): - self.text = 'image' - self.path = '../some_image.png' - self.reference_tag = 'im' + self.text = "image" + self.path = "../some_image.png" + self.reference_tag = "im" def test_new_inline_image(self): - expected_image = '![{}]({})'.format(self.text, self.path) + expected_image = "![{}]({})".format(self.text, self.path) actual_image = Image.new_inline_image(text=self.text, path=self.path) self.assertEqual(expected_image, actual_image) def test_new_reference_image(self): - link = 'https://github.com' - link_text = 'github' + link = "https://github.com" + link_text = "github" reference = Reference() reference.new_link(link=link, text=link_text) image = Image(reference) - expected_image = '![{}][{}]'.format(self.text, self.reference_tag) - actual_image = image.new_reference_image(text=self.text, path=self.path, reference_tag=self.reference_tag) + expected_image = "![{}][{}]".format(self.text, self.reference_tag) + actual_image = image.new_reference_image( + text=self.text, path=self.path, reference_tag=self.reference_tag + ) expected_image_references = {self.reference_tag: self.path, link_text: link} actual_image_references = image.reference.get_references() @@ -47,40 +48,52 @@ def test_new_reference_when_reference_tag_is_not_defined(self): reference = Reference() image = Image(reference) - expected_image = '![{}]'.format(self.text) + expected_image = "![{}]".format(self.text) actual_image = image.new_reference_image(text=self.text, path=self.path) expected_image_references = {self.text: self.path} actual_image_references = image.reference.get_references() - expected_image_references_markdown = "\n\n\n[{}]: {}\n".format(self.text, self.path) + expected_image_references_markdown = "\n\n\n[{}]: {}\n".format( + self.text, self.path + ) actual_image_references_markdown = image.reference.get_references_as_markdown() self.assertEqual(expected_image, actual_image) self.assertEqual(expected_image_references, actual_image_references) - self.assertEqual(expected_image_references_markdown, actual_image_references_markdown) + self.assertEqual( + expected_image_references_markdown, actual_image_references_markdown + ) def test_inline_inline_tooltip(self): - tooltip = 'mytooltip' - expected_image = '![{}]({} \'{}\')'.format(self.text, self.path, tooltip) - actual_image = Image.new_inline_image(text=self.text, path=self.path, tooltip=tooltip) + tooltip = "mytooltip" + expected_image = "![{}]({} '{}')".format(self.text, self.path, tooltip) + actual_image = Image.new_inline_image( + text=self.text, path=self.path, tooltip=tooltip + ) self.assertEqual(expected_image, actual_image) def test_reference_image_tooltip(self): - tooltip = 'mytooltip' + tooltip = "mytooltip" reference = Reference() image = Image(reference) - expected_image = '![{}]'.format(self.text) - actual_image = image.new_reference_image(text=self.text, path=self.path, tooltip=tooltip) + expected_image = "![{}]".format(self.text) + actual_image = image.new_reference_image( + text=self.text, path=self.path, tooltip=tooltip + ) expected_image_references = {self.text: "{} '{}'".format(self.path, tooltip)} actual_image_references = image.reference.get_references() - expected_image_references_markdown = "\n\n\n[{}]: {} '{}'\n".format(self.text, self.path, tooltip) + expected_image_references_markdown = "\n\n\n[{}]: {} '{}'\n".format( + self.text, self.path, tooltip + ) actual_image_references_markdown = image.reference.get_references_as_markdown() self.assertEqual(expected_image, actual_image) self.assertEqual(expected_image_references, actual_image_references) - self.assertEqual(expected_image_references_markdown, actual_image_references_markdown) + self.assertEqual( + expected_image_references_markdown, actual_image_references_markdown + ) diff --git a/tests/test_tools/test_inline.py b/tests/test_tools/test_inline.py index bcbdae9..9ae71c6 100644 --- a/tests/test_tools/test_inline.py +++ b/tests/test_tools/test_inline.py @@ -11,7 +11,6 @@ class TestLink(TestCase): - def setUp(self): self.link = "https://github.com/didix21/mdutils" self.text = "mdutils library" @@ -19,14 +18,13 @@ def setUp(self): self.tooltip = "tooltip" def test_inline_link(self): - - expected_link = '[' + self.text + '](' + self.link + ')' + expected_link = "[" + self.text + "](" + self.link + ")" actual_link = Inline.new_link(link=self.link, text=self.text) self.assertEqual(expected_link, actual_link) def test_text_is_not_defined(self): - expected_link = '<' + self.link + '>' + expected_link = "<" + self.link + ">" actual_link = Inline.new_link(link=self.link) self.assertEqual(expected_link, actual_link) @@ -40,20 +38,19 @@ def test_link_is_not_defined(self): self.fail() def test_link_tooltip(self): - expected_link = '[' + self.text + '](' + self.link + " '{}'".format(self.tooltip) + ')' - actual_link = Inline.new_link(link=self.link, text=self.text, tooltip=self.tooltip) + expected_link = ( + "[" + self.text + "](" + self.link + " '{}'".format(self.tooltip) + ")" + ) + actual_link = Inline.new_link( + link=self.link, text=self.text, tooltip=self.tooltip + ) self.assertEqual(expected_link, actual_link) def test_link_without_text_tooltip(self): - expected_link = '[' + self.link + '](' + self.link + " '{}'".format(self.tooltip) + ')' + expected_link = ( + "[" + self.link + "](" + self.link + " '{}'".format(self.tooltip) + ")" + ) actual_link = Inline.new_link(link=self.link, tooltip=self.tooltip) self.assertEqual(expected_link, actual_link) - - - - - - - diff --git a/tests/test_tools/test_reference.py b/tests/test_tools/test_reference.py index 0c7e79b..aa7e772 100644 --- a/tests/test_tools/test_reference.py +++ b/tests/test_tools/test_reference.py @@ -11,12 +11,13 @@ class TestReference(TestCase): - def setUp(self): self.link = "https://github.com/didix21/mdutils" self.text = "mdutils library" self.reference_tag = "mdutils" - self.expected_reference_markdown = '[' + self.text + '][' + self.reference_tag + ']' + self.expected_reference_markdown = ( + "[" + self.text + "][" + self.reference_tag + "]" + ) self.expected_references = {self.reference_tag: self.link} def test_new_reference(self): @@ -28,7 +29,7 @@ def test_new_reference(self): def test_new_reference_without_defining_reference_tag(self): reference = Reference() - expected_link = '[' + self.text + ']' + expected_link = "[" + self.text + "]" expected_references = {self.text: self.link} actual_link = reference.new_link(self.link, self.text) @@ -60,13 +61,23 @@ def test_add_multiple_link_references(self): def test_get_references_in_markdown_format_check_they_are_sorted(self): reference = Reference() - expected_references_markdown = "\n\n\n" \ - "[1]: http://slashdot.org\n" \ - "[arbitrary case-insensitive reference text]: https://www.mozilla.org\n" \ - "[link text itself]: http://www.reddit.com\n" - - references_tags = ["arbitrary case-insensitive reference text", "1", "link text itself"] - references_links = ["https://www.mozilla.org", "http://slashdot.org", "http://www.reddit.com"] + expected_references_markdown = ( + "\n\n\n" + "[1]: http://slashdot.org\n" + "[arbitrary case-insensitive reference text]: https://www.mozilla.org\n" + "[link text itself]: http://www.reddit.com\n" + ) + + references_tags = [ + "arbitrary case-insensitive reference text", + "1", + "link text itself", + ] + references_links = [ + "https://www.mozilla.org", + "http://slashdot.org", + "http://www.reddit.com", + ] for i in range(3): reference.new_link(references_links[i], "text", references_tags[i]) @@ -84,23 +95,34 @@ def test_get_reference_when_references_are_empty(self): def test_tooltip_get_reference(self): reference = Reference() - references_tags = ["arbitrary case-insensitive reference text", "1", "link text itself"] - references_links = ["https://www.mozilla.org", "http://slashdot.org", "http://www.reddit.com"] - expected_references_markdown = "\n\n\n" \ - "[1]: http://slashdot.org\n" \ - "[arbitrary case-insensitive reference text]: https://www.mozilla.org\n" \ - "[link text itself]: http://www.reddit.com \'my tooltip\'\n" \ - "[my link text]: https://my.link.text.com \'my second tooltip\'\n" + references_tags = [ + "arbitrary case-insensitive reference text", + "1", + "link text itself", + ] + references_links = [ + "https://www.mozilla.org", + "http://slashdot.org", + "http://www.reddit.com", + ] + expected_references_markdown = ( + "\n\n\n" + "[1]: http://slashdot.org\n" + "[arbitrary case-insensitive reference text]: https://www.mozilla.org\n" + "[link text itself]: http://www.reddit.com 'my tooltip'\n" + "[my link text]: https://my.link.text.com 'my second tooltip'\n" + ) for i in range(2): reference.new_link(references_links[i], "text", references_tags[i]) - reference.new_link(references_links[2], "text", references_tags[2], tooltip='my tooltip') - reference.new_link('https://my.link.text.com', 'my link text', tooltip='my second tooltip') + reference.new_link( + references_links[2], "text", references_tags[2], tooltip="my tooltip" + ) + reference.new_link( + "https://my.link.text.com", "my link text", tooltip="my second tooltip" + ) actual_reference_markdown = reference.get_references_as_markdown() self.assertEqual(expected_references_markdown, actual_reference_markdown) - - - diff --git a/tests/test_tools/test_table.py b/tests/test_tools/test_table.py index 9995bae..a2c2e39 100644 --- a/tests/test_tools/test_table.py +++ b/tests/test_tools/test_table.py @@ -10,134 +10,206 @@ from mdutils.tools.Table import Table from mdutils.mdutils import MdUtils -__author__ = 'didix21' -__project__ = 'MdUtils' +__author__ = "didix21" +__project__ = "MdUtils" class TestTable(TestCase): def test_create_centered_table(self): md_file = MdUtils("file_name") table = Table() - result_table = '\n|**Test**|**Descripción**|**Estado**|\n| :---: | :---: | :---: ' \ - '|\n|Test 1|Carga de configuración correcta|OK|\n' \ - '|Test 2|Lectura de Configuración|NOK|\n' \ - '|Test 3|Lectura de Soporte|OK|\n' \ - '|Test 4|Modificación de entradas y lectura de salidas de cantón|' \ - 'OK|'\ - '\n|Test 5|Lectura de estados de Pedal de Rearme y Aviso|OK|\n' \ - '|Test 6|Actualización de datos de unidades de vía|OK|\n' \ - '|Test 7|Fallos en carga de configuración - Campo IdApp Erróneo|' \ - 'OK|' \ - '\n' \ - '|Test 8|Fallos en carga de configuración - Campo VersTAbla Erróneo' \ - '|NOK|'\ - '\n|Test 9|Fallos en carga de configuración - Campo IdUc Erróneo|' \ - 'NOK|' \ - '\n|Test 10|Fallos en carga de configuración - Campo Addresses Erróneo' \ - '|NOK|\n' \ - '|Test 11|Fallos en carga de configuración - Campo NumTc Erróneo' \ - '|NOK|\n' \ - '|Test 12|Fallos en carga de configuración - Campo NumUv Erróneo' \ - '|NOK|\n' \ - '|Test 13|Fallos en carga de configuración - Campo CRC Erróneo|NOK|\n' + result_table = ( + "\n|**Test**|**Descripción**|**Estado**|\n| :---: | :---: | :---: " + '|\n|Test 1|Carga de configuración correcta|OK|\n' + '|Test 2|Lectura de Configuración|NOK|\n' + '|Test 3|Lectura de Soporte|OK|\n' + '|Test 4|Modificación de entradas y lectura de salidas de cantón|' + "OK|" + '\n|Test 5|Lectura de estados de Pedal de Rearme y Aviso|OK|\n' + '|Test 6|Actualización de datos de unidades de vía|OK|\n' + '|Test 7|Fallos en carga de configuración - Campo IdApp Erróneo|' + "OK|" + "\n" + "|Test 8|Fallos en carga de configuración - Campo VersTAbla Erróneo" + '|NOK|' + '\n|Test 9|Fallos en carga de configuración - Campo IdUc Erróneo|' + "NOK|" + "\n|Test 10|Fallos en carga de configuración - Campo Addresses Erróneo" + '|NOK|\n' + "|Test 11|Fallos en carga de configuración - Campo NumTc Erróneo" + '|NOK|\n' + "|Test 12|Fallos en carga de configuración - Campo NumUv Erróneo" + '|NOK|\n' + '|Test 13|Fallos en carga de configuración - Campo CRC Erróneo|NOK|\n' + ) - text_array = ['**Test**', '**Descripción**', '**Estado**', - 'Test 1', 'Carga de configuración correcta', md_file.textUtils.text_color("OK", 'green'), - 'Test 2', 'Lectura de Configuración', md_file.textUtils.text_color("NOK", 'red'), - 'Test 3', 'Lectura de Soporte', md_file.textUtils.text_color("OK", 'green'), - 'Test 4', 'Modificación de entradas y lectura de salidas de cantón', - md_file.textUtils.text_color("OK", 'green'), - 'Test 5', 'Lectura de estados de Pedal de Rearme y Aviso', - md_file.textUtils.text_color("OK", 'green'), - 'Test 6', 'Actualización de datos de unidades de vía', - md_file.textUtils.text_color("OK", 'green'), - 'Test 7', 'Fallos en carga de configuración - Campo IdApp Erróneo', - md_file.textUtils.text_color("OK", 'green'), - 'Test 8', 'Fallos en carga de configuración - Campo VersTAbla Erróneo', - md_file.textUtils.text_color("NOK", 'red'), - 'Test 9', 'Fallos en carga de configuración - Campo IdUc Erróneo', - md_file.textUtils.text_color("NOK", 'red'), - 'Test 10', 'Fallos en carga de configuración - Campo Addresses Erróneo', - md_file.textUtils.text_color("NOK", 'red'), - 'Test 11', 'Fallos en carga de configuración - Campo NumTc Erróneo', - md_file.textUtils.text_color("NOK", 'red'), - 'Test 12', 'Fallos en carga de configuración - Campo NumUv Erróneo', - md_file.textUtils.text_color("NOK", 'red'), - 'Test 13', 'Fallos en carga de configuración - Campo CRC Erróneo', - md_file.textUtils.text_color("NOK", 'red')] + text_array = [ + "**Test**", + "**Descripción**", + "**Estado**", + "Test 1", + "Carga de configuración correcta", + md_file.textUtils.text_color("OK", "green"), + "Test 2", + "Lectura de Configuración", + md_file.textUtils.text_color("NOK", "red"), + "Test 3", + "Lectura de Soporte", + md_file.textUtils.text_color("OK", "green"), + "Test 4", + "Modificación de entradas y lectura de salidas de cantón", + md_file.textUtils.text_color("OK", "green"), + "Test 5", + "Lectura de estados de Pedal de Rearme y Aviso", + md_file.textUtils.text_color("OK", "green"), + "Test 6", + "Actualización de datos de unidades de vía", + md_file.textUtils.text_color("OK", "green"), + "Test 7", + "Fallos en carga de configuración - Campo IdApp Erróneo", + md_file.textUtils.text_color("OK", "green"), + "Test 8", + "Fallos en carga de configuración - Campo VersTAbla Erróneo", + md_file.textUtils.text_color("NOK", "red"), + "Test 9", + "Fallos en carga de configuración - Campo IdUc Erróneo", + md_file.textUtils.text_color("NOK", "red"), + "Test 10", + "Fallos en carga de configuración - Campo Addresses Erróneo", + md_file.textUtils.text_color("NOK", "red"), + "Test 11", + "Fallos en carga de configuración - Campo NumTc Erróneo", + md_file.textUtils.text_color("NOK", "red"), + "Test 12", + "Fallos en carga de configuración - Campo NumUv Erróneo", + md_file.textUtils.text_color("NOK", "red"), + "Test 13", + "Fallos en carga de configuración - Campo CRC Erróneo", + md_file.textUtils.text_color("NOK", "red"), + ] - self.assertEqual(table.create_table(columns=3, rows=14, text=text_array, text_align='center'), result_table) + self.assertEqual( + table.create_table( + columns=3, rows=14, text=text_array, text_align="center" + ), + result_table, + ) def test_create_default_table(self): md_file = MdUtils("file_name") table = Table() - result_table = '\n|**Test**|**Descripción**|**Estado**|\n| --- | --- | --- ' \ - '|\n|Test 1|Carga de configuración correcta|OK|\n' \ - '|Test 2|Lectura de Configuración|NOK|\n' \ - '|Test 3|Lectura de Soporte|OK|\n' \ - '|Test 4|Modificación de entradas y lectura de salidas de cantón|' \ - 'OK|'\ - '\n|Test 5|Lectura de estados de Pedal de Rearme y Aviso|OK|\n' \ - '|Test 6|Actualización de datos de unidades de vía|OK|\n' \ - '|Test 7|Fallos en carga de configuración - Campo IdApp Erróneo|' \ - 'OK|' \ - '\n' \ - '|Test 8|Fallos en carga de configuración - Campo VersTAbla Erróneo' \ - '|NOK|'\ - '\n|Test 9|Fallos en carga de configuración - Campo IdUc Erróneo|' \ - 'NOK|' \ - '\n|Test 10|Fallos en carga de configuración - Campo Addresses Erróneo' \ - '|NOK|\n' \ - '|Test 11|Fallos en carga de configuración - Campo NumTc Erróneo' \ - '|NOK|\n' \ - '|Test 12|Fallos en carga de configuración - Campo NumUv Erróneo' \ - '|NOK|\n' \ - '|Test 13|Fallos en carga de configuración - Campo CRC Erróneo|NOK|\n' + result_table = ( + "\n|**Test**|**Descripción**|**Estado**|\n| --- | --- | --- " + '|\n|Test 1|Carga de configuración correcta|OK|\n' + '|Test 2|Lectura de Configuración|NOK|\n' + '|Test 3|Lectura de Soporte|OK|\n' + '|Test 4|Modificación de entradas y lectura de salidas de cantón|' + "OK|" + '\n|Test 5|Lectura de estados de Pedal de Rearme y Aviso|OK|\n' + '|Test 6|Actualización de datos de unidades de vía|OK|\n' + '|Test 7|Fallos en carga de configuración - Campo IdApp Erróneo|' + "OK|" + "\n" + "|Test 8|Fallos en carga de configuración - Campo VersTAbla Erróneo" + '|NOK|' + '\n|Test 9|Fallos en carga de configuración - Campo IdUc Erróneo|' + "NOK|" + "\n|Test 10|Fallos en carga de configuración - Campo Addresses Erróneo" + '|NOK|\n' + "|Test 11|Fallos en carga de configuración - Campo NumTc Erróneo" + '|NOK|\n' + "|Test 12|Fallos en carga de configuración - Campo NumUv Erróneo" + '|NOK|\n' + '|Test 13|Fallos en carga de configuración - Campo CRC Erróneo|NOK|\n' + ) - text_array = ['**Test**', '**Descripción**', '**Estado**', - 'Test 1', 'Carga de configuración correcta', md_file.textUtils.text_color("OK", 'green'), - 'Test 2', 'Lectura de Configuración', md_file.textUtils.text_color("NOK", 'red'), - 'Test 3', 'Lectura de Soporte', md_file.textUtils.text_color("OK", 'green'), - 'Test 4', 'Modificación de entradas y lectura de salidas de cantón', - md_file.textUtils.text_color("OK", 'green'), - 'Test 5', 'Lectura de estados de Pedal de Rearme y Aviso', - md_file.textUtils.text_color("OK", 'green'), - 'Test 6', 'Actualización de datos de unidades de vía', - md_file.textUtils.text_color("OK", 'green'), - 'Test 7', 'Fallos en carga de configuración - Campo IdApp Erróneo', - md_file.textUtils.text_color("OK", 'green'), - 'Test 8', 'Fallos en carga de configuración - Campo VersTAbla Erróneo', - md_file.textUtils.text_color("NOK", 'red'), - 'Test 9', 'Fallos en carga de configuración - Campo IdUc Erróneo', - md_file.textUtils.text_color("NOK", 'red'), - 'Test 10', 'Fallos en carga de configuración - Campo Addresses Erróneo', - md_file.textUtils.text_color("NOK", 'red'), - 'Test 11', 'Fallos en carga de configuración - Campo NumTc Erróneo', - md_file.textUtils.text_color("NOK", 'red'), - 'Test 12', 'Fallos en carga de configuración - Campo NumUv Erróneo', - md_file.textUtils.text_color("NOK", 'red'), - 'Test 13', 'Fallos en carga de configuración - Campo CRC Erróneo', - md_file.textUtils.text_color("NOK", 'red')] + text_array = [ + "**Test**", + "**Descripción**", + "**Estado**", + "Test 1", + "Carga de configuración correcta", + md_file.textUtils.text_color("OK", "green"), + "Test 2", + "Lectura de Configuración", + md_file.textUtils.text_color("NOK", "red"), + "Test 3", + "Lectura de Soporte", + md_file.textUtils.text_color("OK", "green"), + "Test 4", + "Modificación de entradas y lectura de salidas de cantón", + md_file.textUtils.text_color("OK", "green"), + "Test 5", + "Lectura de estados de Pedal de Rearme y Aviso", + md_file.textUtils.text_color("OK", "green"), + "Test 6", + "Actualización de datos de unidades de vía", + md_file.textUtils.text_color("OK", "green"), + "Test 7", + "Fallos en carga de configuración - Campo IdApp Erróneo", + md_file.textUtils.text_color("OK", "green"), + "Test 8", + "Fallos en carga de configuración - Campo VersTAbla Erróneo", + md_file.textUtils.text_color("NOK", "red"), + "Test 9", + "Fallos en carga de configuración - Campo IdUc Erróneo", + md_file.textUtils.text_color("NOK", "red"), + "Test 10", + "Fallos en carga de configuración - Campo Addresses Erróneo", + md_file.textUtils.text_color("NOK", "red"), + "Test 11", + "Fallos en carga de configuración - Campo NumTc Erróneo", + md_file.textUtils.text_color("NOK", "red"), + "Test 12", + "Fallos en carga de configuración - Campo NumUv Erróneo", + md_file.textUtils.text_color("NOK", "red"), + "Test 13", + "Fallos en carga de configuración - Campo CRC Erróneo", + md_file.textUtils.text_color("NOK", "red"), + ] - self.assertEqual(table.create_table(columns=3, rows=14, text=text_array), result_table) + self.assertEqual( + table.create_table(columns=3, rows=14, text=text_array), result_table + ) def test_column_row_does_not_much_text_length_array(self): md_file = MdUtils("file_name") table = Table() - text_array = ['**Test**', '**Descripción**', '**Estado**', - 'Test 1', 'Carga de configuración correcta', md_file.textUtils.text_color("OK", 'green'), - 'Test 2', 'Lectura de Configuración', md_file.textUtils.text_color("NOK", 'red'), - 'Test 3', 'Lectura de Soporte', md_file.textUtils.text_color("OK", 'green')] + text_array = [ + "**Test**", + "**Descripción**", + "**Estado**", + "Test 1", + "Carga de configuración correcta", + md_file.textUtils.text_color("OK", "green"), + "Test 2", + "Lectura de Configuración", + md_file.textUtils.text_color("NOK", "red"), + "Test 3", + "Lectura de Soporte", + md_file.textUtils.text_color("OK", "green"), + ] self.assertRaises(ValueError, table.create_table, 3, 14, text_array) def test_invalid_text_align(self): md_file = MdUtils("file_name") table = Table() - text_array = ['**Test**', '**Descripción**', '**Estado**', - 'Test 1', 'Carga de configuración correcta', md_file.textUtils.text_color("OK", 'green'), - 'Test 2', 'Lectura de Configuración', md_file.textUtils.text_color("NOK", 'red'), - 'Test 3', 'Lectura de Soporte', md_file.textUtils.text_color("OK", 'green')] - - self.assertRaises(ValueError, table.create_table, 3, 14, text_array, 'invalid_align') + text_array = [ + "**Test**", + "**Descripción**", + "**Estado**", + "Test 1", + "Carga de configuración correcta", + md_file.textUtils.text_color("OK", "green"), + "Test 2", + "Lectura de Configuración", + md_file.textUtils.text_color("NOK", "red"), + "Test 3", + "Lectura de Soporte", + md_file.textUtils.text_color("OK", "green"), + ] + self.assertRaises( + ValueError, table.create_table, 3, 14, text_array, "invalid_align" + ) diff --git a/tests/test_tools/test_table_of_contents.py b/tests/test_tools/test_table_of_contents.py index 780b65c..81c864d 100644 --- a/tests/test_tools/test_table_of_contents.py +++ b/tests/test_tools/test_table_of_contents.py @@ -9,45 +9,61 @@ from unittest import TestCase from mdutils.tools.TableOfContents import TableOfContents -__author__ = 'didix21' -__project__ = 'MdUtils' +__author__ = "didix21" +__project__ = "MdUtils" class TestTableOfContents(TestCase): - def test_create_table_of_contents(self): - array_of_contents = ['Results Tests', [], 'Test Details', ['Test 1', [], 'Test 2', [], - 'Test 3', [], 'Test 4', []]] - expects = '\n* [Results Tests](#results-tests)\n' \ - '* [Test Details](#test-details)\n\t' \ - '* [Test 1](#test-1)\n\t' \ - '* [Test 2](#test-2)\n\t' \ - '* [Test 3](#test-3)\n\t' \ - '* [Test 4](#test-4)\n' + array_of_contents = [ + "Results Tests", + [], + "Test Details", + ["Test 1", [], "Test 2", [], "Test 3", [], "Test 4", []], + ] + expects = ( + "\n* [Results Tests](#results-tests)\n" + "* [Test Details](#test-details)\n\t" + "* [Test 1](#test-1)\n\t" + "* [Test 2](#test-2)\n\t" + "* [Test 3](#test-3)\n\t" + "* [Test 4](#test-4)\n" + ) table_of_contents = TableOfContents() - self.assertEqual(table_of_contents.create_table_of_contents(array_of_contents, depth=2), expects) + self.assertEqual( + table_of_contents.create_table_of_contents(array_of_contents, depth=2), + expects, + ) def test_table_of_contents_with_colon(self): - array_of_contents = ['My header: 1'] - expects = '\n* [My header: 1](#my-header-1)\n' + array_of_contents = ["My header: 1"] + expects = "\n* [My header: 1](#my-header-1)\n" - self.assertEqual(TableOfContents().create_table_of_contents(array_of_contents), expects) + self.assertEqual( + TableOfContents().create_table_of_contents(array_of_contents), expects + ) def test_table_of_contents_with_dot(self): - array_of_contents = ['My.header 1.1'] - expects = '\n* [My.header 1.1](#myheader-11)\n' + array_of_contents = ["My.header 1.1"] + expects = "\n* [My.header 1.1](#myheader-11)\n" - self.assertEqual(TableOfContents().create_table_of_contents(array_of_contents), expects) + self.assertEqual( + TableOfContents().create_table_of_contents(array_of_contents), expects + ) def test_table_of_contents_with_back_slash(self): - array_of_contents = ['My\header 1'] - expects = '\n* [My\header 1](#myheader-1)\n' + array_of_contents = ["My\header 1"] + expects = "\n* [My\header 1](#myheader-1)\n" - self.assertEqual(TableOfContents().create_table_of_contents(array_of_contents), expects) + self.assertEqual( + TableOfContents().create_table_of_contents(array_of_contents), expects + ) def test_table_of_contents_with_hyphen(self): - array_of_contents = ['My-header-1 pop'] - expects = '\n* [My-header-1 pop](#my-header-1-pop)\n' + array_of_contents = ["My-header-1 pop"] + expects = "\n* [My-header-1 pop](#my-header-1-pop)\n" - self.assertEqual(TableOfContents().create_table_of_contents(array_of_contents), expects) + self.assertEqual( + TableOfContents().create_table_of_contents(array_of_contents), expects + ) diff --git a/tests/test_tools/test_textutils.py b/tests/test_tools/test_textutils.py index 096258c..2bfae00 100644 --- a/tests/test_tools/test_textutils.py +++ b/tests/test_tools/test_textutils.py @@ -9,53 +9,57 @@ from unittest import TestCase from mdutils.tools.TextUtils import TextUtils -__author__ = 'didix21' -__project__ = 'MdUtils' +__author__ = "didix21" +__project__ = "MdUtils" class TestTextUtils(TestCase): def test_bold(self): - expects = '**Bold Example**' - self.assertEqual(expects, TextUtils.bold('Bold Example')) + expects = "**Bold Example**" + self.assertEqual(expects, TextUtils.bold("Bold Example")) def test_italics(self): - expects = '*Italics Example*' - self.assertEqual(expects, TextUtils.italics('Italics Example')) + expects = "*Italics Example*" + self.assertEqual(expects, TextUtils.italics("Italics Example")) def test_inline_code(self): - expects = '``Inline Code Example``' - self.assertEqual(expects, TextUtils.inline_code('Inline Code Example')) + expects = "``Inline Code Example``" + self.assertEqual(expects, TextUtils.inline_code("Inline Code Example")) def test_center_text(self): - expects = '
Text Center Alignment Example
' - self.assertEqual(expects, TextUtils.center_text('Text Center Alignment Example')) + expects = "
Text Center Alignment Example
" + self.assertEqual( + expects, TextUtils.center_text("Text Center Alignment Example") + ) def test_text_color(self): expects = 'Red Color Example' - self.assertEqual(expects, TextUtils.text_color('Red Color Example', 'red')) + self.assertEqual(expects, TextUtils.text_color("Red Color Example", "red")) def test_text_external_link(self): - text = 'Text Example' - link = 'https://link.example.org' - expects = '[' + text + '](' + link + ')' + text = "Text Example" + link = "https://link.example.org" + expects = "[" + text + "](" + link + ")" self.assertEqual(expects, TextUtils.text_external_link(text, link)) def test_insert_code(self): - code = ("mdFile.new_header(level=1, title='Atx Header 1')\n" - "mdFile.new_header(level=2, title='Atx Header 2')\n" - "mdFile.new_header(level=3, title='Atx Header 3')\n" - "mdFile.new_header(level=4, title='Atx Header 4')\n" - "mdFile.new_header(level=5, title='Atx Header 5')\n" - "mdFile.new_header(level=6, title='Atx Header 6')\n") - expects = '```\n' + code + '\n```' + code = ( + "mdFile.new_header(level=1, title='Atx Header 1')\n" + "mdFile.new_header(level=2, title='Atx Header 2')\n" + "mdFile.new_header(level=3, title='Atx Header 3')\n" + "mdFile.new_header(level=4, title='Atx Header 4')\n" + "mdFile.new_header(level=5, title='Atx Header 5')\n" + "mdFile.new_header(level=6, title='Atx Header 6')\n" + ) + expects = "```\n" + code + "\n```" self.assertEqual(TextUtils.insert_code(code), expects) - language = 'python' - expects = '```' + language + '\n' + code + '\n```' + language = "python" + expects = "```" + language + "\n" + code + "\n```" self.assertEqual(expects, TextUtils.insert_code(code, language)) def test_text_format(self): - color = 'red' - text = 'Text Format' + color = "red" + text = "Text Format" text_color_center_c = TextUtils.inline_code(text) text_color = TextUtils.text_color(text_color_center_c, color) text_color_center = TextUtils.center_text(text_color) @@ -63,11 +67,15 @@ def test_text_format(self): text_color_center_cbi = TextUtils.italics(text_color_center_cb) expects = text_color_center_cbi - actual = TextUtils.text_format(text, bold_italics_code='bci', color='red', align='center') + actual = TextUtils.text_format( + text, bold_italics_code="bci", color="red", align="center" + ) self.assertEqual(expects, actual) def test_add_tooltip(self): expects = "https://link.com 'tooltip'" - self.assertEqual(expects, TextUtils.add_tooltip(link='https://link.com', tip='tooltip')) + self.assertEqual( + expects, TextUtils.add_tooltip(link="https://link.com", tip="tooltip") + )