Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: marimo export ipynb with outputs (#3048)

Myles Scolnickda7a49938fb0
diff --git a/.github/workflows/test_be.yaml b/.github/workflows/test_be.yaml
index 543c2e5883..6a3f2b6039 100644
--- a/.github/workflows/test_be.yaml
+++ b/.github/workflows/test_be.yaml
@@ -89,10 +89,10 @@ jobs:
- name: Test with minimal dependencies
if: ${{ matrix.dependencies == 'core' }}
run: |
- hatch run +py=${{ matrix.python-version }} test:test -v tests/ -k "not test_cli"
+ hatch run +py=${{ matrix.python-version }} test:test -v tests/ -k "not test_cli" --durations=10
# Test with optional dependencies
- name: Test with optional dependencies
if: ${{ matrix.dependencies == 'core,optional' }}
run: |
- hatch run +py=${{ matrix.python-version }} test-optional:test -v tests/ -k "not test_cli"
+ hatch run +py=${{ matrix.python-version }} test-optional:test -v tests/ -k "not test_cli" --durations=10
diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.py
index 8af8a7c19f..b08a1cb2ad 100644
--- a/marimo/_cli/export/commands.py
+++ b/marimo/_cli/export/commands.py
@@ -14,6 +14,7 @@ from marimo._server.export import (
export_as_md,
export_as_script,
run_app_then_export_as_html,
+ run_app_then_export_as_ipynb,
)
from marimo._server.utils import asyncio_run
from marimo._utils.file_watcher import FileWatcher
@@ -295,18 +296,32 @@ Requires nbformat to be installed.
will be printed to stdout.
""",
)
+ "--include-outputs/--no-include-outputs",
+ default=False,
+ show_default=True,
+ type=bool,
+ help="Run the notebook and include outputs in the exported ipynb file.",
+)
@click.argument("name", required=True)
def ipynb(
name: str,
output: str,
watch: bool,
sort: Literal["top-down", "topological"],
+ include_outputs: bool,
) -> None:
"""
Export a marimo notebook as a Jupyter notebook in topological order.
"""
def export_callback(file_path: MarimoPath) -> str:
+ if include_outputs:
+ return asyncio_run(
+ run_app_then_export_as_ipynb(
+ file_path, sort_mode=sort, cli_args={}
+ )
+ )[0]
return export_as_ipynb(file_path, sort_mode=sort)[0]
DependencyManager.nbformat.require(
diff --git a/marimo/_config/manager.py b/marimo/_config/manager.py
index df5c940df3..4d4b7121a4 100644
--- a/marimo/_config/manager.py
+++ b/marimo/_config/manager.py
@@ -25,7 +25,7 @@ LOGGER = _loggers.marimo_logger()
class UserConfigManager:
def __init__(self, config_path: Optional[str] = None) -> None:
self._config_path = config_path
- self.config = load_config()
+ self._config = load_config()
def save_config(
self, config: MarimoConfig | PartialMarimoConfig
@@ -37,13 +37,13 @@ class UserConfigManager:
# Remove the secret placeholders from the incoming config
config = remove_secret_placeholders(config)
# Merge the current config with the new config
- merged = merge_config(self.config, config)
+ merged = merge_config(self._config, config)
with open(config_path, "w", encoding="utf-8") as f:
tomlkit.dump(merged, f)
- self.config = merge_default_config(merged)
- return self.config
+ self._config = merge_default_config(merged)
+ return self._config
def save_config_if_missing(self) -> None:
try:
@@ -55,8 +55,21 @@ class UserConfigManager:
def get_config(self, hide_secrets: bool = True) -> MarimoConfig:
if hide_secrets:
- return mask_secrets(self.config)
- return self.config
+ return mask_secrets(self._config)
+ return self._config
def get_config_path(self) -> str:
return get_or_create_config_path()
+
+
+class UserConfigManagerWithOverride(UserConfigManager):
+ def __init__(
+ self, delegate: UserConfigManager, override_config: PartialMarimoConfig
+ ) -> None:
+ self.delegate = delegate
+ self.override_config = override_config
+
+ def get_config(self, hide_secrets: bool = True) -> MarimoConfig:
+ return merge_config(
+ self.delegate.get_config(hide_secrets), self.override_config
+ )
diff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.py
index 741b1aaa55..032b347b46 100644
--- a/marimo/_output/hypertext.py
+++ b/marimo/_output/hypertext.py
@@ -1,8 +1,10 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import os
import weakref
-from typing import TYPE_CHECKING, Any, Literal, Optional, final
+from contextlib import contextmanager
+from typing import TYPE_CHECKING, Any, Iterator, Literal, Optional, cast, final
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.mime import MIME
@@ -68,8 +70,6 @@ class Html(MIME):
- `right`: right-justify this element in the output area
"""
- _text: str
-
def __init__(self, text: str) -> None:
"""Initialize the HTML element.
@@ -116,6 +116,21 @@ class Html(MIME):
@final
def _mime_(self) -> tuple[KnownMimeType, str]:
+ no_js = os.getenv("MARIMO_NO_JS", "false").lower() == "true"
+ if no_js and hasattr(self, "_repr_png_"):
+ return (
+ "image/png",
+ cast(
+ str, cast(Any, self)._repr_png_().decode()
+ ), # ignore[no-untyped-call]
+ )
+ if no_js and hasattr(self, "_repr_markdown_"):
+ return (
+ "text/markdown",
+ cast(
+ str, cast(Any, self)._repr_markdown_()
+ ), # ignore[no-untyped-call]
+ )
return ("text/html", self.text)
def __format__(self, spec: str) -> str:
@@ -264,3 +279,21 @@ class Html(MIME):
def _js(text: str) -> Html:
# TODO: interpolation of Python values to javascript
return Html("<script>" + text + "</script>")
+
+
+@contextmanager
+def patch_html_for_non_interactive_output() -> Iterator[None]:
+ """
+ Patch Html to return text/markdown for simpler non-interactive outputs,
+ that can be rendered without JS/CSS (just as in the GitHub viewer).
+ """
+ # HACK: we must set MARIMO_NO_JS since the rendering may happen in another
+ # thread
+ # This won't work when we are running a marimo server and are auto-exporting
+ # with this enabled.
+ old_no_js = os.getenv("MARIMO_NO_JS", "false")
+ try:
+ os.environ["MARIMO_NO_JS"] = "true"
+ yield
+ finally:
+ os.environ["MARIMO_NO_JS"] = old_no_js
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index c37736d22c..7bb6bd24f8 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -10,6 +10,7 @@ import types
import uuid
import weakref
from dataclasses import dataclass, fields
+from html import escape
from typing import (
TYPE_CHECKING,
Any,
@@ -528,3 +529,8 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
"probably want to call `.value` instead."
)
return True
+
+ def _repr_markdown_(self) -> str:
+ # When rendering to markdown, remove the marimo-ui-element tag
+ # and render the inner-text escaped.
+ return escape(self._inner_text)
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 2885884bf8..f9d8019866 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -590,5 +590,15 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):
total_rows=result.get_num_rows(force=True) or 0,
)
+ def _repr_markdown_(self) -> str:
+ """
+ Return a markdown representation of the table.
+ Useful for rendering in the GitHub viewer.
+ """
+ df = self.data
+ if hasattr(df, "_repr_html_"):
+ return df._repr_html_() # type: ignore[attr-defined,no-any-return]
+ return str(df)
+
def __hash__(self) -> int:
return id(self)
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index 538d566c3f..2e47e9ac0b 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -4,9 +4,13 @@ from __future__ import annotations
import asyncio
from typing import Callable, Literal
-from marimo._config.manager import UserConfigManager
+from marimo._config.manager import (
+ UserConfigManager,
+ UserConfigManagerWithOverride,
+)
from marimo._messaging.ops import MessageOperation
from marimo._messaging.types import KernelMessage
+from marimo._output.hypertext import patch_html_for_non_interactive_output
from marimo._runtime.requests import AppMetadata, SerializedCLIArgs
from marimo._server.export.exporter import Exporter
from marimo._server.file_manager import AppFileManager
@@ -52,6 +56,24 @@ def export_as_ipynb(
return Exporter().export_as_ipynb(file_manager, sort_mode=sort_mode)
+async def run_app_then_export_as_ipynb(
+ path: MarimoPath,
+ sort_mode: Literal["top-down", "topological"],
+ cli_args: SerializedCLIArgs,
+) -> tuple[str, str]:
+ file_router = AppFileRouter.from_filename(path)
+ file_key = file_router.get_unique_file_key()
+ assert file_key is not None
+ file_manager = file_router.get_file_manager(file_key)
+
+ with patch_html_for_non_interactive_output():
+ session_view = await run_app_until_completion(file_manager, cli_args)
+
+ return Exporter().export_as_ipynb(
+ file_manager, sort_mode=sort_mode, session_view=session_view
+ )
+
+
async def run_app_then_export_as_html(
path: MarimoPath,
include_code: bool,
@@ -125,7 +147,16 @@ async def run_app_until_completion(
def connection_state(self) -> ConnectionState:
return ConnectionState.OPEN
- config = UserConfigManager()
+ config_manager = UserConfigManagerWithOverride(
+ UserConfigManager(),
+ {
+ "runtime": {
+ "on_cell_change": "autorun",
+ "auto_instantiate": True,
+ "auto_reload": "off",
+ }
+ },
+ )
# Create a session
session = Session.create(
@@ -140,7 +171,7 @@ async def run_app_until_completion(
cli_args=cli_args,
),
app_file_manager=file_manager,
- user_config_manager=config,
+ user_config_manager=config_manager,
virtual_files_supported=False,
redirect_console_to_browser=False,
)
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 3a4760e71a..77c5391a50 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -5,7 +5,7 @@ import base64
import io
import mimetypes
import os
-from typing import Literal, Optional, cast
+from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from marimo import __version__
from marimo._ast.cell import Cell, CellConfig, CellImpl
@@ -15,6 +15,7 @@ from marimo._config.config import (
_deep_copy,
)
from marimo._dependencies.dependencies import DependencyManager
+from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.utils import build_data_url
from marimo._runtime import dataflow
@@ -35,6 +36,9 @@ from marimo._utils.paths import import_files
# Root directory for static assets
root = os.path.realpath(str(import_files("marimo").joinpath("_static")))
+if TYPE_CHECKING:
+ import nbformat # type:ignore
+
class Exporter:
def export_as_html(
@@ -141,40 +145,47 @@ class Exporter:
self,
file_manager: AppFileManager,
sort_mode: Literal["top-down", "topological"],
+ session_view: Optional[SessionView] = None,
) -> tuple[str, str]:
+ """Export notebook as .ipynb, optionally including outputs if session_view provided."""
DependencyManager.nbformat.require(
"to convert marimo notebooks to ipynb"
)
- import nbformat # type: ignore
+ import nbformat
- def create_notebook_cell(cell: CellImpl) -> nbformat.NotebookNode:
- markdown_string = get_markdown_from_cell(
- Cell(_name="__", _cell=cell), cell.code
- )
- if markdown_string is not None:
- return nbformat.v4.new_markdown_cell( # type: ignore
- markdown_string, id=cell.cell_id
- )
- else:
- return nbformat.v4.new_code_cell(cell.code, id=cell.cell_id) # type: ignore
-
- notebook = nbformat.v4.new_notebook() # type: ignore
+ notebook = nbformat.v4.new_notebook()
graph = file_manager.app.graph
+ # Sort cells based on sort_mode
if sort_mode == "top-down":
- # Get cells in document order
cell_ids = list(file_manager.app.cell_manager.cell_ids())
else:
- # Get cells in topological order
cell_ids = dataflow.topological_sort(graph, graph.cells.keys())
- notebook["cells"] = [
- create_notebook_cell(graph.cells[cid]) # type: ignore
- for cid in cell_ids
- ]
+ notebook["cells"] = []
+ for cid in cell_ids:
+ cell = graph.cells[cid]
+ outputs: list[nbformat.NotebookNode] = []
+
+ if session_view is not None:
+ # Get outputs for this cell and convert to IPython format
+ cell_output = session_view.get_cell_outputs([cid]).get(
+ cid, None
+ )
+ cell_console_outputs = session_view.get_cell_console_outputs(
+ [cid]
+ ).get(cid, [])
+ outputs = _convert_marimo_output_to_ipynb(
+ cell_output, cell_console_outputs
+ )
+
+ notebook_cell = _create_notebook_cell(cell, outputs)
+ notebook["cells"].append(notebook_cell)
+
+ # notebook.metadata["marimo-version"] = __version__
stream = io.StringIO()
- nbformat.write(notebook, stream) # type: ignore
+ nbformat.write(notebook, stream)
stream.seek(0)
download_filename = get_download_filename(file_manager, "ipynb")
return stream.read(), download_filename
@@ -321,3 +332,92 @@ def hash_code(code: str) -> str:
import hashlib
return hashlib.sha256(code.encode("utf-8")).hexdigest()
+
+
+def _create_notebook_cell(
+ cell: CellImpl, outputs: list["nbformat.NotebookNode"]
+) -> "nbformat.NotebookNode":
+ import nbformat # ignore
+
+ markdown_string = get_markdown_from_cell(
+ Cell(_name="__", _cell=cell), cell.code
+ )
+ if markdown_string is not None:
+ return nbformat.v4.new_markdown_cell(markdown_string, id=cell.cell_id)
+
+ node = nbformat.v4.new_code_cell(cell.code, id=cell.cell_id)
+ if outputs:
+ node.outputs = outputs
+ return node
+
+
+def _convert_marimo_output_to_ipynb(
+ output: Optional[CellOutput], console_outputs: list[CellOutput]
+) -> list["nbformat.NotebookNode"]:
+ """Convert marimo output format to IPython notebook format."""
+ import nbformat
+
+ ipynb_outputs: list[nbformat.NotebookNode] = []
+
+ # Handle stdout/stderr
+ for output in console_outputs:
+ if output.channel == CellChannel.STDOUT:
+ ipynb_outputs.append(
+ nbformat.v4.new_output(
+ "stream",
+ name="stdout",
+ text=output.data,
+ )
+ )
+ if output.channel == CellChannel.STDERR:
+ ipynb_outputs.append(
+ nbformat.v4.new_output(
+ "stream",
+ name="stderr",
+ text=output.data,
+ )
+ )
+
+ if not output:
+ return ipynb_outputs
+
+ if output.data is None:
+ return ipynb_outputs
+
+ if output.channel not in (CellChannel.OUTPUT, CellChannel.MEDIA):
+ return ipynb_outputs
+
+ if output.mimetype == "text/plain" and (
+ output.data == [] or output.data == ""
+ ):
+ return ipynb_outputs
+
+ # Handle rich output
+ data: dict[str, Any] = {}
+
+ if output.mimetype == "application/vnd.marimo+error":
+ # Captured by stdout/stderr
+ return ipynb_outputs
+ elif output.mimetype == "application/vnd.marimo+mimebundle":
+ for mime, content in cast(dict[str, Any], output.data).items():
+ data[mime] = content
+ else:
+ if (
+ isinstance(output.data, str)
+ and output.data.startswith("data:")
+ and ";base64," in output.data
+ ):
+ data[output.mimetype] = output.data.split(";base64,")[1]
+ else:
+ data[output.mimetype] = output.data
+
+ if data:
+ ipynb_outputs.append(
+ nbformat.v4.new_output(
+ "display_data",
+ data=data,
+ metadata={},
+ )
+ )
+
+ return ipynb_outputs
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 4f0ea5c6f8..945ad62553 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -200,7 +200,7 @@ class KernelManager:
is_edit_mode,
self.configs,
self.app_metadata,
- self.user_config_manager.config,
+ self.user_config_manager.get_config(hide_secrets=False),
self._virtual_files_supported,
self.redirect_console_to_browser,
self.queue_manager.win32_interrupt_queue,
@@ -226,7 +226,7 @@ class KernelManager:
# threads (in edit mode, the single kernel process installs
# formatters ...)
register_formatters(
- theme=self.user_config_manager.config["display"]["theme"]
+ theme=self.user_config_manager.get_config()["display"]["theme"]
)
assert self.queue_manager.stream_queue is not None
@@ -245,7 +245,7 @@ class KernelManager:
is_edit_mode,
self.configs,
self.app_metadata,
- self.user_config_manager.config,
+ self.user_config_manager.get_config(hide_secrets=False),
self._virtual_files_supported,
self.redirect_console_to_browser,
# win32 interrupt queue
diff --git a/pyproject.toml b/pyproject.toml
index f4cfa95c67..f5cf641333 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -398,7 +398,7 @@ minversion = "6.0"
addopts = "-ra -q -v --ignore tests/_cli/ipynb_data --ignore tests/_ast/codegen_data --ignore tests/_ast/app_data"
testpaths = ["tests"]
asyncio_mode = "auto"
-timeout = 30 # seconds, per test
+timeout = 30 # seconds, per test
[tool.coverage.run]
omit = ["marimo/_tutorials/*"]
diff --git a/tests/_cli/snapshots/ipynb.txt b/tests/_cli/snapshots/ipynb.txt
index 24ee1a7364..f7fa45ac19 100644
--- a/tests/_cli/snapshots/ipynb.txt
+++ b/tests/_cli/snapshots/ipynb.txt
@@ -21,14 +21,6 @@
"mo.md(\"markdown\")"
]
},
- {
- "cell_type": "markdown",
- "id": "vblA",
- "metadata": {},
- "source": [
- "plain markdown"
- ]
- },
{
"cell_type": "code",
"execution_count": null,
@@ -39,6 +31,14 @@
"control_dep\n",
"mo.md(f\"parameterized markdown {123}\")"
]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "vblA",
+ "metadata": {},
+ "source": [
+ "plain markdown"
+ ]
}
],
"metadata": {},
diff --git a/tests/_cli/snapshots/ipynb_with_outputs.txt b/tests/_cli/snapshots/ipynb_with_outputs.txt
new file mode 100644
index 0000000000..72d1b8094f
--- /dev/null
+++ b/tests/_cli/snapshots/ipynb_with_outputs.txt
@@ -0,0 +1,68 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bkHC",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import marimo as mo"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "markdown"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "control_dep = None\n",
+ "mo.md(\"markdown\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "parameterized markdown 123"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "control_dep\n",
+ "mo.md(f\"parameterized markdown {123}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "vblA",
+ "metadata": {},
+ "source": [
+ "plain markdown"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
+
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index ac546fa26a..5cb6fe8b67 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -442,12 +442,10 @@ class TestExportMarkdown:
class TestExportIpynb:
- # @pytest.mark.skipif(
- # not DependencyManager.nbformat.has(),
- # reason="This test requires nbformat.",
- # )
- # Flaky on CI
- @pytest.mark.skip
+ @pytest.mark.skipif(
+ not DependencyManager.nbformat.has(),
+ reason="This test requires nbformat.",
+ )
def test_export_ipynb(self, temp_marimo_file_with_md: str) -> None:
p = subprocess.run(
["marimo", "export", "ipynb", temp_marimo_file_with_md],
@@ -491,3 +489,36 @@ class TestExportIpynb:
# Outputs should be different since sorting is different
assert topo_output != topdown_output
+
+ @pytest.mark.skipif(
+ not DependencyManager.nbformat.has(),
+ reason="This test requires nbformat.",
+ )
+ def test_export_ipynb_with_outputs(
+ self, temp_marimo_file_with_md: str
+ ) -> None:
+ # Test without outputs (default)
+ p = subprocess.run(
+ ["marimo", "export", "ipynb", temp_marimo_file_with_md],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+ no_outputs = p.stdout.decode()
+
+ # Test with outputs
+ p = subprocess.run(
+ [
+ "marimo",
+ "export",
+ "ipynb",
+ temp_marimo_file_with_md,
+ "--include-outputs",
+ ],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+ with_outputs = p.stdout.decode()
+ snapshot("ipynb_with_outputs.txt", with_outputs)
+
+ # Outputs should be different since one includes execution results
+ assert no_outputs != with_outputs
diff --git a/tests/_config/test_manager.py b/tests/_config/test_manager.py
index af56a87f8b..3daa5e371d 100644
--- a/tests/_config/test_manager.py
+++ b/tests/_config/test_manager.py
@@ -6,7 +6,10 @@ from typing import Any, Callable, TypeVar
from unittest.mock import patch
from marimo._config.config import PartialMarimoConfig, merge_default_config
-from marimo._config.manager import UserConfigManager
+from marimo._config.manager import (
+ UserConfigManager,
+ UserConfigManagerWithOverride,
+)
from marimo._config.utils import load_config
F = TypeVar("F", bound=Callable[..., Any])
@@ -37,7 +40,7 @@ class TestUserConfigManager(unittest.TestCase):
result = manager.save_config(mock_config)
mock_load.assert_called_once()
- assert result == manager.config
+ assert result == manager._config
assert mock_dump.mock_calls[0][1][0] == result
@@ -98,4 +101,21 @@ class TestUserConfigManager(unittest.TestCase):
result = manager.get_config()
mock_load.assert_called_once()
- assert result == manager.config
+ assert result == manager._config
+
+ @restore_config
+ @patch("marimo._config.manager.load_config")
+ def test_get_config_with_override(self, mock_load: Any) -> None:
+ mock_config = merge_default_config(PartialMarimoConfig())
+ mock_load.return_value = mock_config
+ manager = UserConfigManagerWithOverride(
+ UserConfigManager(),
+ {
+ "runtime": {
+ "on_cell_change": "autorun",
+ "auto_instantiate": True,
+ "auto_reload": "lazy",
+ }
+ },
+ )
+ assert manager.get_config()["runtime"]["auto_reload"] == "lazy"
diff --git a/tests/_output/test_hypertext.py b/tests/_output/test_hypertext.py
index 6a0ce002c2..6d03d01c86 100644
--- a/tests/_output/test_hypertext.py
+++ b/tests/_output/test_hypertext.py
@@ -1,6 +1,10 @@
from __future__ import annotations
-from marimo._output.hypertext import Html, _js
+from marimo._output.hypertext import (
+ Html,
+ _js,
+ patch_html_for_non_interactive_output,
+)
from marimo._plugins.ui._impl.batch import batch as batch_plugin
from marimo._plugins.ui._impl.input import button
@@ -126,3 +130,37 @@ def test_js_multiple_lines():
def test_html_repr_html():
html = Html("<p>Hello</p>")
assert html._repr_html_() == "<p>Hello</p>"
+
+
+def test_html_patch_for_non_interactive_output():
+ class ReprMarkdown(Html):
+ def _repr_markdown_(self) -> str:
+ return "Hello"
+
+ class ReprPng(Html):
+ def _repr_png_(self) -> bytes:
+ return b"Hello"
+
+ html = ReprMarkdown("<web-component>Hello</web-component>")
+ png = ReprPng("<web-component>Hello</web-component>")
+
+ assert html._mime_() == (
+ "text/html",
+ "<web-component>Hello</web-component>",
+ )
+ assert png._mime_() == (
+ "text/html",
+ "<web-component>Hello</web-component>",
+ )
+ with patch_html_for_non_interactive_output():
+ assert html._mime_() == ("text/markdown", "Hello")
+ assert png._mime_() == ("image/png", "Hello")
+
+ assert html._mime_() == (
+ "text/html",
+ "<web-component>Hello</web-component>",
+ )
+ assert png._mime_() == (
+ "text/html",
+ "<web-component>Hello</web-component>",
+ )
diff --git a/tests/_server/export/snapshots/notebook_with_outputs.ipynb.txt b/tests/_server/export/snapshots/notebook_with_outputs.ipynb.txt
new file mode 100644
index 0000000000..809f4079a5
--- /dev/null
+++ b/tests/_server/export/snapshots/notebook_with_outputs.ipynb.txt
@@ -0,0 +1,94 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(\"hello\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "x = 10"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "vblA",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<pre style='font-size: 12px'>22</pre>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "y = x + 1\n",
+ "y * 2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bkHC",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import marimo as mo"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "lEQa",
+ "metadata": {},
+ "source": [
+ "hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "PKri",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "hello 10"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "mo.md(f\"hello {x}\")"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index e090ef0795..dee88cf17c 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -1,9 +1,13 @@
from __future__ import annotations
+import asyncio
+
import pytest
from marimo._ast.app import App, InternalApp
from marimo._dependencies.dependencies import DependencyManager
+from marimo._output.hypertext import patch_html_for_non_interactive_output
+from marimo._server.export import run_app_until_completion
from marimo._server.export.exporter import Exporter
from marimo._server.file_manager import AppFileManager
from tests.mocks import snapshotter
@@ -75,3 +79,142 @@ def test_export_ipynb_sort_modes():
file_manager, sort_mode="topological"
)
snapshot("notebook_topological.ipynb.txt", content)
+
+
+HAS_DEPS = (
+ HAS_NBFORMAT
+ and DependencyManager.polars.has()
+ and DependencyManager.altair.has()
+ and DependencyManager.matplotlib.has()
+)
+
+
+# ruff: noqa: B018
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_export_ipynb_with_outputs():
+ app = App()
+
+ # stdout
+ @app.cell()
+ def cell_1():
+ print("hello")
+ return ()
+
+ # Hangs in CI
+ # stdout
+ # @app.cell()
+ # def cell_2():
+ # import sys
+
+ # sys.stdout.write("world\n")
+ # return (sys,)
+
+ # # stderr
+ # @app.cell()
+ # def cell_3(sys):
+ # sys.stderr.write("error\n")
+ # return ()
+
+ # This includes the filepath in the error message, which is not
+ # good for snapshots
+ # @app.cell()
+ # def cell_3():
+ # raise Exception("error")
+ # return ()
+
+ # display
+ @app.cell()
+ def cell_4():
+ x = 10
+ return (x,)
+
+ # dependency
+ @app.cell()
+ def cell_5(x):
+ y = x + 1
+ y * 2
+ return (y,)
+
+ # dependency
+ @app.cell()
+ def cell_6():
+ import marimo as mo
+
+ return (mo,)
+
+ # pure markdown
+ @app.cell()
+ def cell_7(mo):
+ mo.md("hello")
+ return ()
+
+ # interpolated markdown
+ @app.cell()
+ def cell_8(mo, x):
+ mo.md(f"hello {x}")
+ return ()
+
+ # Hangs in CI
+ # # polars
+ # @app.cell()
+ # def cell_9():
+ # import polars as pl
+
+ # df = pl.DataFrame({"a": [1, 2, 3]})
+ # df
+ # return (df,)
+
+ # # mo.ui.table
+ # @app.cell()
+ # def cell_10(df, mo):
+ # mo.ui.table(df)
+ # return ()
+
+ # # slider
+ # @app.cell()
+ # def cell_11(mo):
+ # mo.ui.slider(start=0, stop=10)
+ # return ()
+
+ # # hstack
+ # @app.cell()
+ # def cell_12(mo, df):
+ # mo.vstack([mo.md("hello"), mo.md("world"), df])
+ # return ()
+
+ # # altair chart
+ # @app.cell()
+ # def cell_13(df):
+ # import altair as alt
+
+ # chart = alt.Chart(df).mark_point().encode(x="a")
+ # chart
+ # return (chart,)
+
+ # # matplotlib
+ # @app.cell()
+ # def cell_14():
+ # import matplotlib.pyplot as plt
+
+ # plt.plot([1, 2])
+ # return (plt,)
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ exporter = Exporter()
+
+ content, filename = exporter.export_as_ipynb(
+ file_manager, sort_mode="top-down", session_view=None
+ )
+ assert filename == "notebook.ipynb"
+
+ # Create a session view with outputs
+ with patch_html_for_non_interactive_output():
+ session_view = asyncio.run(
+ run_app_until_completion(file_manager, cli_args={})
+ )
+ content, filename = exporter.export_as_ipynb(
+ file_manager, sort_mode="top-down", session_view=session_view
+ )
+ assert filename == "notebook.ipynb"
+ snapshot("notebook_with_outputs.ipynb.txt", content)
diff --git a/tests/_server/test_session_manager.py b/tests/_server/test_session_manager.py
index 95878274bf..ccafd7d0df 100644
--- a/tests/_server/test_session_manager.py
+++ b/tests/_server/test_session_manager.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import asyncio
from unittest.mock import MagicMock, Mock
import pytest
@@ -41,14 +40,12 @@ def session_manager():
)
-def test_start_lsp_server(session_manager: SessionManager) -> None:
- asyncio.get_event_loop().run_until_complete(
- session_manager.start_lsp_server()
- )
+async def test_start_lsp_server(session_manager: SessionManager) -> None:
+ await session_manager.start_lsp_server()
session_manager.lsp_server.start.assert_called_once()
-def test_create_session_new(
+async def test_create_session_new(
session_manager: SessionManager, mock_session_consumer: SessionConsumer
) -> None:
session_id = "test_session_id"
@@ -64,7 +61,7 @@ def test_create_session_new(
session.close()
-def test_create_session_absolute_url(
+async def test_create_session_absolute_url(
session_manager: SessionManager,
mock_session_consumer: SessionConsumer,
temp_marimo_file: str,