From 27085ad53c86dcf23f769a86bd830106c8a8b09c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Mond=C3=A9jar=20Rubio?= Date: Mon, 12 Sep 2022 20:42:09 +0200 Subject: [PATCH 1/5] Configurable default values for directive arguments --- mkdocs_include_markdown_plugin/config.py | 57 ++++++++++++++++++++++ mkdocs_include_markdown_plugin/event.py | 61 +++++++++++++++++------- mkdocs_include_markdown_plugin/plugin.py | 9 ++-- tests/{test_tags.py => test_config.py} | 21 ++++---- 4 files changed, 115 insertions(+), 33 deletions(-) create mode 100644 mkdocs_include_markdown_plugin/config.py rename tests/{test_tags.py => test_config.py} (83%) diff --git a/mkdocs_include_markdown_plugin/config.py b/mkdocs_include_markdown_plugin/config.py new file mode 100644 index 0000000..8d7e10d --- /dev/null +++ b/mkdocs_include_markdown_plugin/config.py @@ -0,0 +1,57 @@ +import mkdocs.config.config_options + + +CONFIG_DEFAULTS = { + 'opening_tag': '{%', + 'closing_tag': '%}', + 'encoding': 'utf-8', + 'preserve_includer_indent': True, + 'dedent': False, + 'trailing_newlines': True, + 'comments': True, +} + +CONFIG_SCHEME = ( + ( + 'opening_tag', + mkdocs.config.config_options.Type( + str, default=CONFIG_DEFAULTS['opening_tag'], + ), + ), + ( + 'closing_tag', + mkdocs.config.config_options.Type( + str, default=CONFIG_DEFAULTS['closing_tag'], + ), + ), + ( + 'encoding', + mkdocs.config.config_options.Type( + str, default=CONFIG_DEFAULTS['encoding'], + ), + ), + ( + 'preserve_includer_indent', + mkdocs.config.config_options.Type( + bool, default=CONFIG_DEFAULTS['preserve_includer_indent'], + ), + ), + ( + 'dedent', + mkdocs.config.config_options.Type( + bool, default=CONFIG_DEFAULTS['dedent'], + ), + ), + ( + 'trailing_newlines', + mkdocs.config.config_options.Type( + bool, default=CONFIG_DEFAULTS['trailing_newlines'], + ), + ), + ( + 'comments', + mkdocs.config.config_options.Type( + bool, default=CONFIG_DEFAULTS['comments'], + ), + ), +) diff --git a/mkdocs_include_markdown_plugin/event.py b/mkdocs_include_markdown_plugin/event.py index 41d210d..11b06fa 100644 --- a/mkdocs_include_markdown_plugin/event.py +++ b/mkdocs_include_markdown_plugin/event.py @@ -8,6 +8,7 @@ import textwrap from mkdocs_include_markdown_plugin import process +from mkdocs_include_markdown_plugin.config import CONFIG_DEFAULTS logger = logging.getLogger('mkdocs.plugins.mkdocs_include_markdown_plugin') @@ -64,11 +65,11 @@ 'encoding': str_arg('encoding'), # bool - 'rewrite-relative-urls': bool_arg('rewrite-relative-urls'), 'comments': bool_arg('comments'), 'preserve-includer-indent': bool_arg('preserve-includer-indent'), 'dedent': bool_arg('dedent'), 'trailing-newlines': bool_arg('trailing-newlines'), + 'rewrite-relative-urls': bool_arg('rewrite-relative-urls'), # int 'heading-offset': re.compile(r'heading-offset=(-?\d+)'), @@ -114,6 +115,11 @@ def get_file_content( docs_dir, include_tag_regex, include_markdown_tag_regex, + default_encoding, + default_preserve_includer_indent, + default_dedent, + default_trailing_newlines, + default_comments=CONFIG_DEFAULTS['comments'], cumulative_heading_offset=0, ): @@ -195,15 +201,15 @@ def found_include_tag(match): bool_options = { 'preserve-includer-indent': { - 'value': True, + 'value': default_preserve_includer_indent, 'regex': ARGUMENT_REGEXES['preserve-includer-indent'], }, 'dedent': { - 'value': False, + 'value': default_dedent, 'regex': ARGUMENT_REGEXES['dedent'], }, 'trailing-newlines': { - 'value': True, + 'value': default_trailing_newlines, 'regex': ARGUMENT_REGEXES['trailing-newlines'], }, } @@ -275,7 +281,7 @@ def found_include_tag(match): f'{os.path.relpath(page_src_path, docs_dir)}:{lineno}', ) else: - encoding = 'utf-8' + encoding = default_encoding text_to_include = '' expected_but_any_found = [start is not None, end is not None] @@ -301,6 +307,10 @@ def found_include_tag(match): docs_dir, include_tag_regex, include_markdown_tag_regex, + default_encoding, + default_preserve_includer_indent, + default_dedent, + default_trailing_newlines, ) # trailing newlines right stripping @@ -427,19 +437,19 @@ def found_include_markdown_tag(match): 'regex': ARGUMENT_REGEXES['rewrite-relative-urls'], }, 'comments': { - 'value': True, + 'value': default_comments, 'regex': ARGUMENT_REGEXES['comments'], }, 'preserve-includer-indent': { - 'value': True, + 'value': default_preserve_includer_indent, 'regex': ARGUMENT_REGEXES['preserve-includer-indent'], }, 'dedent': { - 'value': False, + 'value': default_dedent, 'regex': ARGUMENT_REGEXES['dedent'], }, 'trailing-newlines': { - 'value': True, + 'value': default_trailing_newlines, 'regex': ARGUMENT_REGEXES['trailing-newlines'], }, } @@ -515,7 +525,7 @@ def found_include_markdown_tag(match): f'{os.path.relpath(page_src_path, docs_dir)}:{lineno}', ) else: - encoding = 'utf-8' + encoding = default_encoding # heading offset offset = 0 @@ -556,6 +566,11 @@ def found_include_markdown_tag(match): docs_dir, include_tag_regex, include_markdown_tag_regex, + default_encoding, + default_preserve_includer_indent, + default_dedent, + default_trailing_newlines, + default_comments=default_comments, ) # trailing newlines right stripping @@ -645,16 +660,18 @@ def on_page_markdown( markdown, page, docs_dir, - opening_tag='{%', - closing_tag='%}', + config={}, ): + escaped_opening_tag = re.escape( + config.get('opening_tag', CONFIG_DEFAULTS['opening_tag']), + ) + escaped_closing_tag = re.escape( + config.get('closing_tag', CONFIG_DEFAULTS['closing_tag']), + ) - escaped_opening_tag = re.escape(opening_tag) - escaped_closing_tag = re.escape(closing_tag) - - # Replace the substrings "$OPENING_TAG" and "$CLOSING_TAG" from - # "INCLUDE_TAG_REGEX" and "INCLUDE_MARKDOWN_TAG_REGEX" by the effective - # tags + # Replace the substrings OPENING_TAG and CLOSING_TAG from + # INCLUDE_TAG_REGEX and INCLUDE_MARKDOWN_TAG_REGEX by the + # effective tags include_tag_regex = re.compile( INCLUDE_TAG_REGEX.pattern.replace( '$OPENING_TAG', escaped_opening_tag, @@ -675,4 +692,12 @@ def on_page_markdown( docs_dir, include_tag_regex, include_markdown_tag_regex, + config.get('encoding', CONFIG_DEFAULTS['encoding']), + config.get( + 'preserve_includer_indent', + CONFIG_DEFAULTS['preserve_includer_indent'], + ), + config.get('dedent', CONFIG_DEFAULTS['dedent']), + config.get('trailing_newlines', CONFIG_DEFAULTS['trailing_newlines']), + default_comments=config.get('comments', CONFIG_DEFAULTS['comments']), ) diff --git a/mkdocs_include_markdown_plugin/plugin.py b/mkdocs_include_markdown_plugin/plugin.py index 3180dfa..7640e35 100644 --- a/mkdocs_include_markdown_plugin/plugin.py +++ b/mkdocs_include_markdown_plugin/plugin.py @@ -1,21 +1,18 @@ import mkdocs +from mkdocs_include_markdown_plugin.config import CONFIG_SCHEME from mkdocs_include_markdown_plugin.event import ( on_page_markdown as _on_page_markdown, ) class IncludeMarkdownPlugin(mkdocs.plugins.BasePlugin): - config_scheme = ( - ('opening_tag', mkdocs.config.config_options.Type(str, default='{%')), - ('closing_tag', mkdocs.config.config_options.Type(str, default='%}')), - ) + config_scheme = CONFIG_SCHEME def on_page_markdown(self, markdown, page, **kwargs): return _on_page_markdown( markdown, page, kwargs['config']['docs_dir'], - self.config['opening_tag'], - self.config['closing_tag'], + config=self.config, ) diff --git a/tests/test_tags.py b/tests/test_config.py similarity index 83% rename from tests/test_tags.py rename to tests/test_config.py index 2f71779..2dedf08 100644 --- a/tests/test_tags.py +++ b/tests/test_config.py @@ -10,44 +10,48 @@ 'includer_schema', 'content_to_include', 'expected_result', - 'tags', + 'config', ), ( + # opening_tag and closing_tag pytest.param( '# Header\n\n{! include "{filepath}" !}\n', 'This must be included.', '# Header\n\nThis must be included.\n', - ('{!', '!}'), + {'opening_tag': '{!', 'closing_tag': '!}'}, id='custom-tag {! ... !}', ), pytest.param( '# Header\n\n{* include "{filepath}" *}\n', 'This must be included.', '# Header\n\nThis must be included.\n', - ('{*', '*}'), + {'opening_tag': '{*', 'closing_tag': '*}'}, id='custom-tag {* ... *}', ), pytest.param( '# Header\n\n#INC[ include "{filepath}" ]\n', 'This must be included.', '# Header\n\nThis must be included.\n', - ('#INC[', ']'), + {'opening_tag': '#INC[', 'closing_tag': ']'}, id='custom-tag #INC[ ...]', ), pytest.param( '# Header\n\n.^$*+-?{}[]\\|():<>=!/#%,; include "{filepath}" }\n', 'This must be included.', '# Header\n\nThis must be included.\n', - ('.^$*+-?{}[]\\|():<>=!/#%,;', '}'), + {'opening_tag': '.^$*+-?{}[]\\|():<>=!/#%,;', 'closing_tag': '}'}, id='custom-tag-all-escaped-char', ), + + # encoding + ), ) -def test_include( +def test_config( includer_schema, content_to_include, expected_result, - tags, + config, page, caplog, tmp_path, @@ -72,8 +76,7 @@ def test_include( page_content, page(includer_filepath), tmp_path, - opening_tag=tags[0], - closing_tag=tags[1], + config, ) == expected_result ) From d0292d3f8347b03aaae2107e90eb42153ae90994 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Mond=C3=A9jar=20Rubio?= Date: Thu, 15 Sep 2022 12:01:52 +0200 Subject: [PATCH 2/5] Add tests and documentation --- .bumpversion.cfg | 2 +- README.md | 17 ++++- locale/es/README.md | 17 +++-- locale/es/README.md.po | 37 +++++++--- locale/fr/README.md | 17 +++-- locale/fr/README.md.po | 36 +++++++--- mkdocs_include_markdown_plugin/__init__.py | 2 +- setup.cfg | 2 +- tests/test_config.py | 82 ++++++++++++++++++++++ tests/test_encoding.py | 2 +- 10 files changed, 177 insertions(+), 37 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 2fb9c7a..b722d5d 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 3.7.1 +current_version = 3.8.0 [bumpversion:file:mkdocs_include_markdown_plugin/__init__.py] diff --git a/README.md b/README.md index 7ebbe90..91f28e6 100644 --- a/README.md +++ b/README.md @@ -38,16 +38,27 @@ plugins: > Make sure that you define `include-markdown` before other plugins that could conflict, like [`mkdocs-macros-plugin`][mkdocs-macros-plugin-link]. -### Custom opening and closing tags +### Configuration -The default opening and closing tags are `{%` and `%}`. You can change this -default with the configuration fields `opening_tag` and `closing_tag`: +The global behaviour of the plugin can be customized in the configuration. + +- # **opening_tag** and + **closing_tag**: The default opening and closing tags. By default are + `{%` and `%}`. + +The rest of the options will define the default values passed to arguments +of directives and are documented in the [reference](#reference). ```yaml plugins: - include-markdown: opening_tag: "{!" closing_tag: "!}" + encoding: ascii + preserve_includer_indent: false + dedent: true + trailing_newlines: false + comments: false ``` ### Reference diff --git a/locale/es/README.md b/locale/es/README.md index 835803e..9af7275 100644 --- a/locale/es/README.md +++ b/locale/es/README.md @@ -31,17 +31,26 @@ plugins: > Asegúrate que defines `include-markdown` antes de otros plugins que pudieran entrar en conflicto, como [`mkdocs-macros-plugin`][mkdocs-macros-plugin-link]. -### Etiquetas de apertura y cierre personalizadas +### Configuración -Las etiquetas de apertura y cierre por defecto son `{%` y `%}`. Se puede cambiar -este valor por defecto con los campos de configuración `opening_tag` y -`closing_tag`. +El comportamiento global del plugin puede ser personalizado en la configuración. + +- # **opening_tag** and **closing_tag**: +Las etiquetas de apertura y cierre. Por defecto son `{%` y `%}`. + +El resto de las opciones definirán los valores por defecto pasados a los +argumentos de las directivas y están documentados en la [referencia](#reference). ```yaml plugins: - include-markdown: opening_tag: "{!" closing_tag: "!}" + encoding: ascii + preserve_includer_indent: false + dedent: true + trailing_newlines: false + comments: false ``` ### Referencia diff --git a/locale/es/README.md.po b/locale/es/README.md.po index bbadaf5..ed15914 100644 --- a/locale/es/README.md.po +++ b/locale/es/README.md.po @@ -305,17 +305,6 @@ msgstr "" "envolver con comillas dobles `\"` o simples `'`, que se pueden escapar " "anteponiendo un carácter `\\` como `\\\"` y `\\'`." -msgid "Custom opening and closing tags" -msgstr "Etiquetas de apertura y cierre personalizadas" - -msgid "" -"The default opening and closing tags are `{%` and `%}`. You can change this " -"default with the configuration fields `opening_tag` and `closing_tag`:" -msgstr "" -"Las etiquetas de apertura y cierre por defecto son `{%` y `%}`. Se puede " -"cambiar este valor por defecto con los campos de configuración `opening_tag`" -" y `closing_tag`." - msgid "" "# **encoding** (*utf-8*): Specify the encoding of " @@ -333,3 +322,29 @@ msgstr "" "# **encoding** " "(*utf-8*): Especifica la codificación del archivo incluído. Si no se define," " se usará `utf-8`." + +msgid "Configuration" +msgstr "Configuración" + +msgid "" +"The global behaviour of the plugin can be customized in the configuration." +msgstr "" +"El comportamiento global del plugin puede ser personalizado en la " +"configuración." + +msgid "" +"# **opening_tag** and " +"**closing_tag**: The default opening and closing tags. By default are `{%` " +"and `%}`." +msgstr "" +"# **opening_tag** and " +"**closing_tag**: Las etiquetas de apertura y cierre. Por defecto son `{%` y " +"`%}`." + +msgid "" +"The rest of the options will define the default values passed to arguments " +"of directives and are documented in the [reference](#reference)." +msgstr "" +"El resto de las opciones definirán los valores por defecto pasados a los " +"argumentos de las directivas y están documentados en la " +"[referencia](#reference)." diff --git a/locale/fr/README.md b/locale/fr/README.md index 05d5cdf..944cd55 100644 --- a/locale/fr/README.md +++ b/locale/fr/README.md @@ -31,17 +31,26 @@ plugins: > Assurez-vous de définir `include-markdown` avant d'autres plugins qui pourraient entrer en conflit, comme [`mkdocs-macros-plugin`][mkdocs-macros-plugin-link]. -### Balises d'ouverture et de fermeture personnalisées +### Configuration -Les balises d'ouverture et de fermeture par défaut sont `{%` et `%}`. Vous -pouvez changer ces balises avec les paramètres de configuration `opening_tag` et -`closing_tag`: +Le comportement global du plugin peut être personnalisé dans la configuration. + +- # **opening_tag** and **closing_tag**: +Les balises d'ouverture et de fermeture par défaut. Par défaut sont `{%` et `%}`. + +Le reste des options définira les valeurs par défaut passées aux arguments des +directives et sont documentées dans la [référence](#reference). ```yaml plugins: - include-markdown: opening_tag: "{!" closing_tag: "!}" + encoding: ascii + preserve_includer_indent: false + dedent: true + trailing_newlines: false + comments: false ``` ### Référence diff --git a/locale/fr/README.md.po b/locale/fr/README.md.po index 8b20afc..d39f711 100644 --- a/locale/fr/README.md.po +++ b/locale/fr/README.md.po @@ -305,17 +305,6 @@ msgstr "" "peuvent être entourés de guillemets doubles `\"` ou simples `'`, qui peuvent" " être échappés en leur ajoutant un caractère `\\` comme `\\\"` et `\\'`." -msgid "Custom opening and closing tags" -msgstr "Balises d'ouverture et de fermeture personnalisées" - -msgid "" -"The default opening and closing tags are `{%` and `%}`. You can change this " -"default with the configuration fields `opening_tag` and `closing_tag`:" -msgstr "" -"Les balises d'ouverture et de fermeture par défaut sont `{%` et `%}`. Vous " -"pouvez changer ces balises avec les paramètres de configuration " -"`opening_tag` et `closing_tag`:" - msgid "" "# **encoding** (*utf-8*): Specify the encoding of " @@ -333,3 +322,28 @@ msgstr "" "# **encoding** " "(*utf-8*): Spécifiez l'encodage du fichier inclus. S'il n'est pas défini, " "`utf-8` sera utilisé." + +msgid "Configuration" +msgstr "Configuration" + +msgid "" +"# **opening_tag** and " +"**closing_tag**: The default opening and closing tags. By default are `{%` " +"and `%}`." +msgstr "" +"# **opening_tag** and " +"**closing_tag**: Les balises d'ouverture et de fermeture par défaut. Par " +"défaut sont `{%` et `%}`." + +msgid "" +"The global behaviour of the plugin can be customized in the configuration." +msgstr "" +"Le comportement global du plugin peut être personnalisé dans la " +"configuration." + +msgid "" +"The rest of the options will define the default values passed to arguments " +"of directives and are documented in the [reference](#reference)." +msgstr "" +"Le reste des options définira les valeurs par défaut passées aux arguments " +"des directives et sont documentées dans la [référence](#reference)." diff --git a/mkdocs_include_markdown_plugin/__init__.py b/mkdocs_include_markdown_plugin/__init__.py index a5f51ca..345f426 100644 --- a/mkdocs_include_markdown_plugin/__init__.py +++ b/mkdocs_include_markdown_plugin/__init__.py @@ -1,2 +1,2 @@ __title__ = 'mkdocs_include_markdown_plugin' -__version__ = '3.7.1' +__version__ = '3.8.0' diff --git a/setup.cfg b/setup.cfg index eb9750c..88aded5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,6 @@ [metadata] name = mkdocs_include_markdown_plugin -version = 3.7.1 +version = 3.8.0 description = Mkdocs Markdown includer plugin. long_description = file: README.md long_description_content_type = text/markdown diff --git a/tests/test_config.py b/tests/test_config.py index 2dedf08..cfa45d9 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -44,7 +44,84 @@ ), # encoding + pytest.param( + '# Header\n\n{% include "{filepath}" %}', + 'bóg wąż wąską dróżką', + '# Header\n\nbóg wąż wąską dróżką', + {}, + id='default-encoding', + ), + pytest.param( + '# Header\n\n{% include "{filepath}" %}', + 'bóg wąż wąską dróżką', + '# Header\n\nbĂłg wÄ…ĹĽ wÄ…skÄ… dróżkÄ…', + {'encoding': 'cp1250'}, + id='custom-encoding', + ), + + # preserve_includer_indent + pytest.param( + ' {% include "{filepath}" %}', + 'foo\nbar\n', + ' foo\n bar\n', + {}, + id='default-preserve_includer_indent', + ), + pytest.param( + ' {% include "{filepath}" %}', + 'foo\nbar\n', + ' foo\nbar\n', + {'preserve_includer_indent': False}, + id='custom-preserve_includer_indent', + ), + + # dedent + pytest.param( + '{% include "{filepath}" %}', + 'foo\n bar\n', + 'foo\n bar\n', + {}, + id='default-dedent', + ), + pytest.param( + '{% include "{filepath}" %}', + ' foo\n bar\n', + 'foo\nbar\n', + {'dedent': True}, + id='custom-dedent', + ), + # trailing_newlines + pytest.param( + '{% include "{filepath}" %}', + 'foo\n\n\n', + 'foo\n\n\n', + {}, + id='default-trailing_newlines', + ), + pytest.param( + '{% include "{filepath}" %}', + 'foo\n\n\n', + 'foo', + {'trailing_newlines': False}, + id='custom-trailing_newlines', + ), + + # comments + pytest.param( + '{% include-markdown "{filepath}" %}', + 'foo\n', + '\nfoo\n\n', + {}, + id='default-comments', + ), + pytest.param( + '{% include-markdown "{filepath}" %}', + 'foo\n', + 'foo\n', + {'comments': False}, + id='custom-comments', + ), ), ) def test_config( @@ -71,6 +148,11 @@ def test_config( ) includer_filepath.write_text(page_content) + expected_result = expected_result.replace( + '{filepath}', + included_filepath.as_posix(), + ) + assert ( on_page_markdown( page_content, diff --git a/tests/test_encoding.py b/tests/test_encoding.py index 7681cdb..af25be9 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -49,7 +49,7 @@ def test_default_encoding(directive, page, tmp_path): f'''{{% {directive} "{page_to_include_file}" comments=false - start='' + start="" end="" %}}''', page(tmp_path / 'includer.md'), From 24d0ea91346f814e055137510b25ae1da456e2b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Mond=C3=A9jar=20Rubio?= Date: Thu, 15 Sep 2022 12:10:26 +0200 Subject: [PATCH 3/5] Add test for 100% code coverage --- tests/test_arguments.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/test_arguments.py b/tests/test_arguments.py index d4f83ab..e97fa02 100644 --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -191,6 +191,29 @@ def test_invalid_exclude_argument(directive, page, tmp_path, caplog): ) +@parametrize_directives +def test_empty_encoding_argument(directive, page, tmp_path, caplog): + page_to_include_filepath = tmp_path / 'included.md' + page_to_include_filepath.write_text('Content to include') + + result = on_page_markdown( + f'''{{% + {directive} "{page_to_include_filepath}" + comments=false + encoding= +%}}''', + page(tmp_path / 'includer.md'), + tmp_path, + ) + assert result == 'Content to include' + + assert len(caplog.records) == 1 + assert caplog.records[0].msg == ( + f"Invalid empty 'encoding' argument in '{directive}'" + ' directive at includer.md:1' + ) + + class TestFilename: double_quoted_filenames = [ 'inc"luded.md', 'inc"lude"d.md', 'included.md"', '"included.md', From 00e0263bb840bcb27cb72caf590c83ab882d8e1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Mond=C3=A9jar=20Rubio?= Date: Thu, 15 Sep 2022 12:23:10 +0200 Subject: [PATCH 4/5] Skip test on Windows --- tests/test_arguments.py | 24 ++----- tests/test_config.py | 138 ++++++++++++++++++++++----------------- tests/test_encoding.py | 14 +--- tests/testing_helpers.py | 6 ++ 4 files changed, 94 insertions(+), 88 deletions(-) diff --git a/tests/test_arguments.py b/tests/test_arguments.py index e97fa02..7208a31 100644 --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -1,22 +1,12 @@ import functools import os import re -import sys import pytest from mkdocs_include_markdown_plugin.event import on_page_markdown -from testing_helpers import parametrize_directives - - -double_quotes_windows_path_skip = pytest.mark.skipif( - sys.platform.startswith('win'), - reason=( - 'Double quotes are reserved characters not allowed for' - ' paths under Windows' - ), -) +from testing_helpers import parametrize_directives, unix_only @pytest.mark.parametrize( @@ -129,7 +119,7 @@ def test_invalid_start_end_arguments(directive, page, caplog, tmp_path): assert len(records_messages) == len(expected_args) -@double_quotes_windows_path_skip +@unix_only @parametrize_directives def test_exclude_double_quote_escapes(directive, page, tmp_path): drectory_to_include = tmp_path / 'exclude_double_quote_escapes' @@ -157,7 +147,7 @@ def test_exclude_double_quote_escapes(directive, page, tmp_path): assert result == 'Content that should be included\n' -@double_quotes_windows_path_skip +@unix_only @parametrize_directives def test_invalid_exclude_argument(directive, page, tmp_path, caplog): drectory_to_include = tmp_path / 'exclude_double_quote_escapes' @@ -222,7 +212,7 @@ class TestFilename: fname.replace('"', "'") for fname in double_quoted_filenames ] - @double_quotes_windows_path_skip + @unix_only @parametrize_directives @pytest.mark.parametrize('filename', double_quoted_filenames) def test_not_escaped_double_quotes( @@ -244,7 +234,7 @@ def test_not_escaped_double_quotes( caplog.records[0].msg, ) - @double_quotes_windows_path_skip + @unix_only @parametrize_directives @pytest.mark.parametrize('filename', double_quoted_filenames) def test_escaped_double_quotes( @@ -291,7 +281,7 @@ def test_escaped_single_quotes( ) assert result == included_content - @double_quotes_windows_path_skip + @unix_only @parametrize_directives @pytest.mark.parametrize('filename', double_quoted_filenames) def test_unescaped_double_quotes( @@ -330,7 +320,7 @@ def test_unescaped_single_quotes( ) assert result == included_content - @double_quotes_windows_path_skip + @unix_only @parametrize_directives @pytest.mark.parametrize( 'filename', ["inc'luded\".md", "''i\"nc\"lude'd.md"], diff --git a/tests/test_config.py b/tests/test_config.py index cfa45d9..c782abf 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -4,14 +4,61 @@ from mkdocs_include_markdown_plugin.event import on_page_markdown +from testing_helpers import unix_only + + +TESTS_ARGUMENTS = ( + 'includer_schema', + 'content_to_include', + 'expected_result', + 'config', +) + + +def _run_test( + includer_schema, + content_to_include, + expected_result, + config, + page, + caplog, + tmp_path, +): + included_filepath = tmp_path / 'included.md' + includer_filepath = tmp_path / 'includer.md' + + included_filepath.write_text(content_to_include) + includer_filepath.write_text( + content_to_include.replace('{filepath}', included_filepath.as_posix()), + ) + + # assert content + page_content = includer_schema.replace( + '{filepath}', + included_filepath.as_posix(), + ) + includer_filepath.write_text(page_content) + + expected_result = expected_result.replace( + '{filepath}', + included_filepath.as_posix(), + ) + + assert ( + on_page_markdown( + page_content, + page(includer_filepath), + tmp_path, + config, + ) + == expected_result + ) + + assert len(caplog.records) == 0 + @pytest.mark.parametrize( - ( - 'includer_schema', - 'content_to_include', - 'expected_result', - 'config', - ), + TESTS_ARGUMENTS, ( # opening_tag and closing_tag pytest.param( @@ -43,22 +90,6 @@ id='custom-tag-all-escaped-char', ), - # encoding - pytest.param( - '# Header\n\n{% include "{filepath}" %}', - 'bóg wąż wąską dróżką', - '# Header\n\nbóg wąż wąską dróżką', - {}, - id='default-encoding', - ), - pytest.param( - '# Header\n\n{% include "{filepath}" %}', - 'bóg wąż wąską dróżką', - '# Header\n\nbĂłg wÄ…ĹĽ wÄ…skÄ… dróżkÄ…', - {'encoding': 'cp1250'}, - id='custom-encoding', - ), - # preserve_includer_indent pytest.param( ' {% include "{filepath}" %}', @@ -124,43 +155,30 @@ ), ), ) -def test_config( - includer_schema, - content_to_include, - expected_result, - config, - page, - caplog, - tmp_path, -): - included_filepath = tmp_path / 'included.md' - includer_filepath = tmp_path / 'includer.md' - - included_filepath.write_text(content_to_include) - includer_filepath.write_text( - content_to_include.replace('{filepath}', included_filepath.as_posix()), - ) +def test_config_options(*args): + return _run_test(*args) - # assert content - page_content = includer_schema.replace( - '{filepath}', - included_filepath.as_posix(), - ) - includer_filepath.write_text(page_content) - expected_result = expected_result.replace( - '{filepath}', - included_filepath.as_posix(), - ) - - assert ( - on_page_markdown( - page_content, - page(includer_filepath), - tmp_path, - config, - ) - == expected_result - ) - - assert len(caplog.records) == 0 +@unix_only +@pytest.mark.parametrize( + TESTS_ARGUMENTS, + ( + # encoding + pytest.param( + '# Header\n\n{% include "{filepath}" %}', + 'bóg wąż wąską dróżką', + '# Header\n\nbóg wąż wąską dróżką', + {}, + id='default-encoding', + ), + pytest.param( + '# Header\n\n{% include "{filepath}" %}', + 'bóg wąż wąską dróżką', + '# Header\n\nbĂłg wÄ…ĹĽ wÄ…skÄ… dróżkÄ…', + {'encoding': 'cp1250'}, + id='custom-encoding', + ), + ), +) +def test_config_encoding_option(*args): + return _run_test(*args) diff --git a/tests/test_encoding.py b/tests/test_encoding.py index af25be9..8bd8f1b 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -1,10 +1,8 @@ -import sys - import pytest from mkdocs_include_markdown_plugin.event import on_page_markdown -from testing_helpers import parametrize_directives +from testing_helpers import parametrize_directives, unix_only @parametrize_directives @@ -31,10 +29,7 @@ def test_encoding(directive, page, tmp_path): ) -@pytest.mark.skipif( - sys.platform != 'linux', - reason='On Windows CI the utf-8 encoding does not work', -) +@unix_only @parametrize_directives def test_default_encoding(directive, page, tmp_path): page_to_include_file = tmp_path / 'included.md' @@ -58,10 +53,7 @@ def test_default_encoding(directive, page, tmp_path): assert result == '\nContent to include\n' -@pytest.mark.skipif( - sys.platform != 'linux', - reason='On Windows CI the utf-8 encoding does not work', -) +@unix_only @parametrize_directives def test_explicit_default_encoding(directive, page, tmp_path): page_to_include_file = tmp_path / 'included.md' diff --git a/tests/testing_helpers.py b/tests/testing_helpers.py index 87c1cb2..de0a666 100644 --- a/tests/testing_helpers.py +++ b/tests/testing_helpers.py @@ -1,4 +1,5 @@ import os +import sys import pytest @@ -9,4 +10,9 @@ ids=('directive=include', 'directive=include-markdown'), ) +unix_only = pytest.mark.skipif( + sys.platform.startswith('win'), + reason='Test only supported on Unix systems', +) + rootdir = os.path.join(os.path.dirname(__file__), '..') From 42fe9de58174be9db060e7f763f07476ef1f8838 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Mond=C3=A9jar=20Rubio?= Date: Thu, 15 Sep 2022 12:26:35 +0200 Subject: [PATCH 5/5] Fix error in tests --- tests/test_config.py | 40 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/tests/test_config.py b/tests/test_config.py index c782abf..40280be 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -155,8 +155,24 @@ def _run_test( ), ), ) -def test_config_options(*args): - return _run_test(*args) +def test_config_options( + includer_schema, + content_to_include, + expected_result, + config, + page, + caplog, + tmp_path, +): + return _run_test( + includer_schema, + content_to_include, + expected_result, + config, + page, + caplog, + tmp_path, + ) @unix_only @@ -180,5 +196,21 @@ def test_config_options(*args): ), ), ) -def test_config_encoding_option(*args): - return _run_test(*args) +def test_config_encoding_option( + includer_schema, + content_to_include, + expected_result, + config, + page, + caplog, + tmp_path, +): + return _run_test( + includer_schema, + content_to_include, + expected_result, + config, + page, + caplog, + tmp_path, + )