From 3028dcd4f20f94b578995c326fd68d53a6dc3638 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timoth=C3=A9e=20Mazzucotelli?= Date: Sun, 13 Nov 2022 15:50:34 +0100 Subject: [PATCH] fix: Render source for non-HTML output (regression) --- src/markdown_exec/formatters/base.py | 29 ++++++++++++++++------------ tests/test_base_formatter.py | 14 +++++++++++++- 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/src/markdown_exec/formatters/base.py b/src/markdown_exec/formatters/base.py index 66c15af..7590670 100644 --- a/src/markdown_exec/formatters/base.py +++ b/src/markdown_exec/formatters/base.py @@ -43,22 +43,27 @@ def base_format( # noqa: WPS231 """ markdown = MarkdownConverter(md) extra = options.get("extra", {}) + try: output = run(code, **extra) except RuntimeError as error: logger.warning(f"Execution of {language} code block exited with non-zero status") return markdown.convert(str(error)) - if html and source: - placeholder = str(uuid4()) + + if html: + if source: + placeholder = str(uuid4()) + wrapped_output = add_source( + source=code, location=source, output=placeholder, language=language, tabs=tabs, **extra + ) + return markdown.convert(wrapped_output, stash={placeholder: output}) + return Markup(output) + + wrapped_output = output + if result: + wrapped_output = code_block(result, output) + if source: wrapped_output = add_source( - source=code, location=source, output=placeholder, language=language, tabs=tabs, **extra + source=code, location=source, output=wrapped_output, language=language, tabs=tabs, **extra ) - markup = markdown.convert(wrapped_output, stash={placeholder: output}) - elif html: - markup = Markup(output) - elif result: - wrapped_output = code_block(result, output) - markup = markdown.convert(wrapped_output) - else: - markup = markdown.convert(output) - return markup + return markdown.convert(wrapped_output) diff --git a/tests/test_base_formatter.py b/tests/test_base_formatter.py index b203b48..96520ae 100644 --- a/tests/test_base_formatter.py +++ b/tests/test_base_formatter.py @@ -1,6 +1,6 @@ """Tests for the base formatter.""" - +import pytest from markdown import Markdown from markdown_exec.formatters.base import base_format @@ -15,3 +15,15 @@ def test_no_p_around_html(md: Markdown) -> None: code = "
hello
" html = base_format("whatever", lambda _: _, code, md, html=True, source="", result="", tabs=("", "")) assert html == code + + +@pytest.mark.parametrize("html", [True, False]) +def test_render_source(md: Markdown, html: bool) -> None: + """Assert source is rendered. + + Parameters: + md: A Markdown instance (fixture). + html: Whether output is HTML or not. + """ + markup = base_format("python", lambda _: _, "hello", md, html, "tabbed-left", "", ("Source", "Output")) + assert "Source" in markup