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.

refactor: move more tests around, ipynb-with-outputs test fixtures (#7860)

Myles Scolnick6aea4b69b4b6
diff --git a/tests/_cli/snapshots/ipynb_with_errors.txt b/tests/_cli/snapshots/ipynb_with_errors.txt
index a7fb9853b9..3909c57aef 100644
--- a/tests/_cli/snapshots/ipynb_with_errors.txt
+++ b/tests/_cli/snapshots/ipynb_with_errors.txt
@@ -32,6 +32,7 @@
"output_type": "error",
"traceback": [
"Traceback (most recent call last):",
+ " File \"\", line 1, in <module>",
" 1 / 0",
" ~~^~~",
"ZeroDivisionError: division by zero",
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index 7dd7f91063..d7c6347c8c 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -18,7 +18,7 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._utils import async_path
from marimo._utils.platform import is_windows
from tests._server.templates.utils import normalize_index_html
-from tests.mocks import snapshotter
+from tests.mocks import delete_lines_with_files, snapshotter
if TYPE_CHECKING:
import pathlib
@@ -947,7 +947,7 @@ class TestExportIpynb:
# Jupyter error output, not printed to stderr
output = p.stdout.decode()
assert "division by zero" in output
- output = _delete_lines_with_files(output)
+ output = delete_lines_with_files(output)
snapshot("ipynb_with_errors.txt", output)
@staticmethod
@@ -1016,9 +1016,3 @@ class TestExportIpynb:
capture_output=True,
)
assert p.returncode == 0, p.stderr.decode()
-
-
-def _delete_lines_with_files(output: str) -> str:
- return "\n".join(
- line for line in output.splitlines() if "File " not in line
- )
diff --git a/tests/_server/export/snapshots/notebook_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/notebook_top_down.ipynb.txt
similarity index 100%
rename from tests/_server/export/snapshots/notebook_top_down.ipynb.txt
rename to tests/_convert/ipynb/snapshots/notebook_top_down.ipynb.txt
diff --git a/tests/_server/export/snapshots/notebook_topological.ipynb.txt b/tests/_convert/ipynb/snapshots/notebook_topological.ipynb.txt
similarity index 100%
rename from tests/_server/export/snapshots/notebook_topological.ipynb.txt
rename to tests/_convert/ipynb/snapshots/notebook_topological.ipynb.txt
diff --git a/tests/_convert/ipynb/test_from_ir.py b/tests/_convert/ipynb/test_from_ir.py
new file mode 100644
index 0000000000..35fa31438c
--- /dev/null
+++ b/tests/_convert/ipynb/test_from_ir.py
@@ -0,0 +1,351 @@
+from __future__ import annotations
+
+import json
+import pathlib
+from typing import Any
+
+import pytest
+
+from marimo._ast.app import App, InternalApp
+from marimo._ast.load import load_app
+from marimo._convert.ipynb import convert_from_ir_to_ipynb
+from marimo._convert.ipynb.from_ir import (
+ _convert_marimo_output_to_ipynb,
+ _maybe_extract_dataurl,
+)
+from marimo._messaging.cell_output import CellChannel, CellOutput
+from tests.mocks import snapshotter
+
+SELF_DIR = pathlib.Path(__file__).parent
+snapshot_test = snapshotter(__file__)
+
+pytest.importorskip("nbformat")
+
+
+ "py_path", (SELF_DIR / "fixtures" / "py").glob("*.py")
+)
+def test_convert_from_ir_to_ipynb_snapshots(py_path: pathlib.Path) -> None:
+ """Test convert_from_ir_to_ipynb against all Python fixtures using snapshots."""
+ # Load the marimo app from file
+ app = load_app(py_path)
+ assert app
+ internal_app = InternalApp(app)
+
+ # Convert
+ sort_mode = "top-down"
+ ipynb_str = convert_from_ir_to_ipynb(internal_app, sort_mode=sort_mode)
+
+ # Parse as JSON to validate and format consistently
+ ipynb_json = json.loads(ipynb_str)
+ formatted_ipynb = json.dumps(ipynb_json, indent=2, sort_keys=True)
+
+ base_name = py_path.name.replace(".py", "")
+ snapshot_name = f"{base_name}_{sort_mode.replace('-', '_')}.ipynb.txt"
+
+ snapshot_test(snapshot_name, formatted_ipynb)
+
+
+def test_export_ipynb_sort_modes() -> None:
+ app = App()
+
+ @app.cell()
+ def result(x, y):
+ z = x + y
+ return (z,)
+
+ @app.cell()
+ def __():
+ x = 1
+ return (x,)
+
+ @app.cell()
+ def __():
+ y = 1
+ return (y,)
+
+ internal_app = InternalApp(app)
+
+ # Test top-down mode preserves document order
+ content = convert_from_ir_to_ipynb(internal_app, sort_mode="top-down")
+ snapshot_test("notebook_top_down.ipynb.txt", content)
+
+ # Test topological mode respects dependencies
+ content = convert_from_ir_to_ipynb(internal_app, sort_mode="topological")
+ snapshot_test("notebook_topological.ipynb.txt", content)
+
+
+ ("input_data", "expected"),
+ [
+ # Base64 data URL extraction
+ (
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA",
+ "iVBORw0KGgoAAAANSUhEUgAAAAUA",
+ ),
+ # Non-data-URL string passes through
+ ("hello world", "hello world"),
+ # Dict passes through
+ ({"key": "value"}, {"key": "value"}),
+ # Int passes through
+ (123, 123),
+ # Data URL without base64 passes through
+ ("data:text/plain,hello", "data:text/plain,hello"),
+ ],
+ ids=[
+ "base64_data_url",
+ "regular_string",
+ "dict_passthrough",
+ "int_passthrough",
+ "data_url_no_base64",
+ ],
+)
+def test_maybe_extract_dataurl(input_data: Any, expected: Any) -> None:
+ """Test _maybe_extract_dataurl with various inputs."""
+ result = _maybe_extract_dataurl(input_data)
+ assert result == expected
+
+
+ ("mimebundle", "expected_data", "expected_metadata"),
+ [
+ # Known mimetypes
+ (
+ {
+ "text/plain": "Hello",
+ "text/html": "<p>Hello</p>",
+ "image/png": "data:image/png;base64,iVBORw0KGgo=",
+ },
+ {
+ "text/plain": "Hello",
+ "text/html": "<p>Hello</p>",
+ "image/png": "iVBORw0KGgo=",
+ },
+ {},
+ ),
+ # Multiple formats
+ (
+ {
+ "text/plain": "Figure(640x480)",
+ "text/html": "<div>Chart</div>",
+ "image/png": "data:image/png;base64,PNG_BASE64_DATA",
+ "image/svg+xml": "<svg>...</svg>",
+ "application/json": {"data": [1, 2, 3]},
+ },
+ {
+ "text/plain": "Figure(640x480)",
+ "text/html": "<div>Chart</div>",
+ "image/png": "PNG_BASE64_DATA",
+ "image/svg+xml": "<svg>...</svg>",
+ "application/json": {"data": [1, 2, 3]},
+ },
+ {},
+ ),
+ # With metadata
+ (
+ {
+ "text/plain": "Figure",
+ "image/png": "PNG_DATA",
+ "__metadata__": {"width": 640, "height": 480, "dpi": 100},
+ },
+ {"text/plain": "Figure", "image/png": "PNG_DATA"},
+ {"width": 640, "height": 480, "dpi": 100},
+ ),
+ # Nested metadata
+ (
+ {
+ "text/plain": "Figure",
+ "image/png": "PNG_DATA",
+ "__metadata__": {
+ "figure": {"width": 640, "height": 480},
+ "plot": {"type": "line", "color": "blue"},
+ "tags": ["important", "experiment-1"],
+ },
+ },
+ {"text/plain": "Figure", "image/png": "PNG_DATA"},
+ {
+ "figure": {"width": 640, "height": 480},
+ "plot": {"type": "line", "color": "blue"},
+ "tags": ["important", "experiment-1"],
+ },
+ ),
+ ],
+ ids=[
+ "known_mimetypes",
+ "multiple_formats",
+ "with_metadata",
+ "nested_metadata",
+ ],
+)
+def test_convert_marimo_mimebundle_to_ipynb(
+ mimebundle: dict[str, Any],
+ expected_data: dict[str, Any],
+ expected_metadata: dict[str, Any],
+) -> None:
+ """Test marimo mimebundle conversion to ipynb format."""
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=json.dumps(mimebundle),
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ assert result[0]["data"] == expected_data
+ assert result[0]["metadata"] == expected_metadata
+
+
+def test_convert_marimo_mimebundle_with_non_dict_metadata() -> None:
+ """Test that non-dict metadata is ignored."""
+ mimebundle_data = json.dumps(
+ {
+ "text/plain": "Figure",
+ "image/png": "PNG_DATA",
+ "__metadata__": "not a dict",
+ }
+ )
+
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ # Verify metadata is empty when non-dict value is provided
+ assert "metadata" in result[0]
+ assert result[0]["metadata"] == {}
+
+
+def test_convert_marimo_mimebundle_empty() -> None:
+ """Test that empty marimo mimebundle produces no output."""
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=json.dumps({}),
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+ assert len(result) == 0
+
+
+def test_convert_marimo_mimebundle_dict() -> None:
+ """Handle the case when the mimebundle is a dict, not JSON-dumped string."""
+ mimebundle_data = {
+ "text/plain": "Figure",
+ "image/png": "PNG_DATA",
+ "__metadata__": {"width": 640, "height": 480},
+ }
+
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ assert "__metadata__" not in result[0]["data"]
+ assert result[0]["data"]["text/plain"] == "Figure"
+ assert result[0]["data"]["image/png"] == "PNG_DATA"
+ assert result[0]["metadata"] == {"width": 640, "height": 480}
+
+
+ ("mimetype", "data", "expected_data"),
+ [
+ # Data URL extraction
+ (
+ "image/png",
+ "data:image/png;base64,REGULAR_PNG_DATA",
+ {"image/png": "REGULAR_PNG_DATA"},
+ ),
+ # No data URL
+ (
+ "text/plain",
+ "Hello World",
+ {"text/plain": "Hello World"},
+ ),
+ ],
+ ids=["with_dataurl", "without_dataurl"],
+)
+def test_convert_regular_output(
+ mimetype: str, data: str, expected_data: dict[str, str]
+) -> None:
+ """Test regular output conversion."""
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype=mimetype,
+ data=data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ assert result[0]["data"] == expected_data
+ assert result[0]["metadata"] == {}
+
+
+def test_convert_console_outputs() -> None:
+ """Test that console outputs (stdout/stderr) are converted correctly."""
+ console_outputs = [
+ CellOutput(
+ channel=CellChannel.STDOUT,
+ mimetype="text/plain",
+ data="Console output\n",
+ ),
+ CellOutput(
+ channel=CellChannel.STDERR,
+ mimetype="text/plain",
+ data="Warning message\n",
+ ),
+ ]
+
+ result = _convert_marimo_output_to_ipynb(None, console_outputs)
+
+ assert len(result) == 2
+ assert result[0]["output_type"] == "stream"
+ assert result[0]["name"] == "stdout"
+ assert result[0]["text"] == "Console output\n"
+ assert result[1]["output_type"] == "stream"
+ assert result[1]["name"] == "stderr"
+ assert result[1]["text"] == "Warning message\n"
+
+
+def test_convert_marimo_mimebundle_with_both_output_and_console() -> None:
+ """Test marimo mimebundle with both cell output and console outputs."""
+ main_output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=json.dumps({"text/plain": "Result", "image/png": "PNG_DATA"}),
+ )
+
+ console_outputs = [
+ CellOutput(
+ channel=CellChannel.STDOUT,
+ mimetype="text/plain",
+ data="Console output\n",
+ ),
+ ]
+
+ # Convert console outputs
+ console_result = _convert_marimo_output_to_ipynb(None, console_outputs)
+ # Convert main output
+ main_result = _convert_marimo_output_to_ipynb(main_output, [])
+
+ assert len(console_result) == 1
+ assert console_result[0]["output_type"] == "stream"
+ assert console_result[0]["name"] == "stdout"
+
+ assert len(main_result) == 1
+ assert main_result[0]["output_type"] == "display_data"
+ assert main_result[0]["data"]["text/plain"] == "Result"
+ assert main_result[0]["data"]["image/png"] == "PNG_DATA"
diff --git a/tests/_convert/ipynb/test_iypnb_from_marimo.py b/tests/_convert/ipynb/test_iypnb_from_marimo.py
deleted file mode 100644
index 2a8a4bc10b..0000000000
--- a/tests/_convert/ipynb/test_iypnb_from_marimo.py
+++ /dev/null
@@ -1,40 +0,0 @@
-from __future__ import annotations
-
-import json
-import pathlib
-
-import pytest
-
-from marimo._ast.app import InternalApp
-from marimo._ast.load import load_app
-from marimo._convert.ipynb import convert_from_ir_to_ipynb
-from tests.mocks import snapshotter
-
-SELF_DIR = pathlib.Path(__file__).parent
-snapshot_test = snapshotter(__file__)
-
-pytest.importorskip("nbformat")
-
-
- "py_path", (SELF_DIR / "fixtures" / "py").glob("*.py")
-)
-def test_convert_from_ir_to_ipynb_snapshots(py_path: pathlib.Path) -> None:
- """Test convert_from_ir_to_ipynb against all Python fixtures using snapshots."""
- # Load the marimo app from file
- app = load_app(py_path)
- assert app
- internal_app = InternalApp(app)
-
- # Convert
- sort_mode = "top-down"
- ipynb_str = convert_from_ir_to_ipynb(internal_app, sort_mode=sort_mode)
-
- # Parse as JSON to validate and format consistently
- ipynb_json = json.loads(ipynb_str)
- formatted_ipynb = json.dumps(ipynb_json, indent=2, sort_keys=True)
-
- base_name = py_path.name.replace(".py", "")
- snapshot_name = f"{base_name}_{sort_mode.replace('-', '_')}.ipynb.txt"
-
- snapshot_test(snapshot_name, formatted_ipynb)
diff --git a/tests/_server/export/fixtures/apps/basic.py b/tests/_server/export/fixtures/apps/basic.py
new file mode 100644
index 0000000000..906044e92e
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/basic.py
@@ -0,0 +1,26 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+def _():
+ x = 10
+ return (x,)
+
+
+def _(x, y):
+ z = y + x
+ return (z,)
+
+
+def _(x):
+ y = x + 1
+ return (y,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/empty_notebook.py b/tests/_server/export/fixtures/apps/empty_notebook.py
new file mode 100644
index 0000000000..3b8714d962
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/empty_notebook.py
@@ -0,0 +1,8 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/error_ancestor.py b/tests/_server/export/fixtures/apps/error_ancestor.py
new file mode 100644
index 0000000000..82d4ca4c05
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/error_ancestor.py
@@ -0,0 +1,19 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+def _():
+ raise ValueError("ancestor error")
+
+
+def _(x):
+ y = x + 1
+ return (y,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/error_complex.py b/tests/_server/export/fixtures/apps/error_complex.py
new file mode 100644
index 0000000000..a2dabf6d06
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/error_complex.py
@@ -0,0 +1,39 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+def _(y): # noqa: F811
+ x = y
+ return (x,)
+
+
+def _():
+ Y = 0 # noqa: N806
+ return (Y,)
+
+
+def _(z):
+ Z = z # noqa: N806
+ return (Z,)
+
+
+def _():
+ z = 1 / 0
+ return (z,)
+
+
+def _(x, Y): # noqa: N803
+ y = x
+ y = Y # noqa: F841
+ return (y,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/error_cycle.py b/tests/_server/export/fixtures/apps/error_cycle.py
new file mode 100644
index 0000000000..b1107f0a50
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/error_cycle.py
@@ -0,0 +1,20 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+def _(y):
+ x = y
+ return (x,)
+
+
+def _(x):
+ y = x
+ return (y,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/error_redefinition.py b/tests/_server/export/fixtures/apps/error_redefinition.py
new file mode 100644
index 0000000000..21e3f79557
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/error_redefinition.py
@@ -0,0 +1,20 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+def _():
+ x = 1
+ return (x,)
+
+
+def _():
+ x = 2 # Redefines x
+ return (x,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/error_undefined.py b/tests/_server/export/fixtures/apps/error_undefined.py
new file mode 100644
index 0000000000..78cbe4f113
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/error_undefined.py
@@ -0,0 +1,14 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+def _():
+ x = undefined_variable # noqa: F821
+ return (x,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/error_value_with_stdout.py b/tests/_server/export/fixtures/apps/error_value_with_stdout.py
new file mode 100644
index 0000000000..a92642a8d2
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/error_value_with_stdout.py
@@ -0,0 +1,14 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+def _():
+ print("hello before error")
+ raise ValueError("test error")
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/with_console_output.py b/tests/_server/export/fixtures/apps/with_console_output.py
new file mode 100644
index 0000000000..5f0dfd26ba
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/with_console_output.py
@@ -0,0 +1,22 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+def _():
+ import sys
+
+ sys.stdout.write("hello stdout")
+ return (sys,)
+
+
+def _(sys):
+ sys.stderr.write("hello stderr")
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/with_dependencies.py b/tests/_server/export/fixtures/apps/with_dependencies.py
new file mode 100644
index 0000000000..76ee48db01
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/with_dependencies.py
@@ -0,0 +1,26 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+def _():
+ x = 1
+ return (x,)
+
+
+def _(x):
+ y = x + 1
+ return (y,)
+
+
+def _(y):
+ z = y + 1
+ return (z,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/with_layout.py b/tests/_server/export/fixtures/apps/with_layout.py
new file mode 100644
index 0000000000..4a818102e9
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/with_layout.py
@@ -0,0 +1,14 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App(layout_file="layouts/layout.json")
+
+
+def _():
+ x = 1
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/with_outputs.py b/tests/_server/export/fixtures/apps/with_outputs.py
new file mode 100644
index 0000000000..2414f98ee4
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/with_outputs.py
@@ -0,0 +1,48 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+def _():
+ import marimo as mo
+
+ return (mo,)
+
+
+def _(mo):
+ import altair as alt
+ import polars as pl
+
+ df = pl.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
+ chart = alt.Chart(df).mark_point().encode(x="x", y="y")
+ mo.ui.altair_chart(chart)
+ return alt, chart, df, pl
+
+
+def _():
+ import matplotlib.pyplot as plt
+
+ fig, ax = plt.subplots()
+ ax.plot([1, 2, 3], [4, 5, 6])
+ plt.gca()
+ return ax, fig, plt
+
+
+def _(mo):
+ mo.md("# Hello World")
+ return
+
+
+def _():
+ print("hello stdout")
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/fixtures/apps/with_stop.py b/tests/_server/export/fixtures/apps/with_stop.py
new file mode 100644
index 0000000000..5d905f5962
--- /dev/null
+++ b/tests/_server/export/fixtures/apps/with_stop.py
@@ -0,0 +1,28 @@
+import marimo
+
+__generated_with = "0.19.2"
+app = marimo.App()
+
+
+def _():
+ import marimo as mo
+
+ mo.stop(True, "Stopped early")
+ return (mo,)
+
+
+def _():
+ x = 10
+ return (x,)
+
+
+def _(x):
+ y = x + 1
+ return (y,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/snapshots/empty_notebook.ipynb.txt b/tests/_server/export/snapshots/empty_notebook.ipynb.txt
deleted file mode 100644
index 363fcab7ed..0000000000
--- a/tests/_server/export/snapshots/empty_notebook.ipynb.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "cells": [],
- "metadata": {},
- "nbformat": 4,
- "nbformat_minor": 5
-}
diff --git a/tests/_server/export/snapshots/ipynb/basic.ipynb.txt b/tests/_server/export/snapshots/ipynb/basic.ipynb.txt
new file mode 100644
index 0000000000..0f53ffd66c
--- /dev/null
+++ b/tests/_server/export/snapshots/ipynb/basic.ipynb.txt
@@ -0,0 +1,37 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "x = 10"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "z = y + x"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "vblA",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "y = x + 1"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/ipynb/empty_notebook.ipynb.txt b/tests/_server/export/snapshots/ipynb/empty_notebook.ipynb.txt
new file mode 100644
index 0000000000..2ccb5c4d67
--- /dev/null
+++ b/tests/_server/export/snapshots/ipynb/empty_notebook.ipynb.txt
@@ -0,0 +1,15 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/ipynb/error_ancestor.ipynb.txt b/tests/_server/export/snapshots/ipynb/error_ancestor.ipynb.txt
new file mode 100644
index 0000000000..4adc6e2e92
--- /dev/null
+++ b/tests/_server/export/snapshots/ipynb/error_ancestor.ipynb.txt
@@ -0,0 +1,54 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "ValueError",
+ "evalue": "ancestor error",
+ "output_type": "error",
+ "traceback": [
+ "Traceback (most recent call last):",
+ " File \"\", line 1, in <module>",
+ " raise ValueError(\"ancestor error\")",
+ "ValueError: ancestor error",
+ ""
+ ]
+ }
+ ],
+ "source": [
+ "raise ValueError(\"ancestor error\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "NameError",
+ "evalue": "name 'x' is not defined",
+ "output_type": "error",
+ "traceback": [
+ "Traceback (most recent call last):",
+ " File \"\", line 1, in <module>",
+ " y = x + 1",
+ " ^",
+ "NameError: name 'x' is not defined",
+ ""
+ ]
+ }
+ ],
+ "source": [
+ "y = x + 1"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/notebook_with_error.ipynb.txt b/tests/_server/export/snapshots/ipynb/error_complex.ipynb.txt
similarity index 92%
rename from tests/_server/export/snapshots/notebook_with_error.ipynb.txt
rename to tests/_server/export/snapshots/ipynb/error_complex.ipynb.txt
index 25e3f4167d..bd43650ae7 100644
--- a/tests/_server/export/snapshots/notebook_with_error.ipynb.txt
+++ b/tests/_server/export/snapshots/ipynb/error_complex.ipynb.txt
@@ -31,11 +31,7 @@
"cell_type": "code",
"execution_count": null,
"id": "vblA",
- "metadata": {
- "marimo": {
- "name": "_b"
- }
- },
+ "metadata": {},
"outputs": [
{
"ename": "Ancestor raised",
@@ -52,11 +48,7 @@
"cell_type": "code",
"execution_count": null,
"id": "bkHC",
- "metadata": {
- "marimo": {
- "name": "_a"
- }
- },
+ "metadata": {},
"outputs": [
{
"ename": "ZeroDivisionError",
diff --git a/tests/_server/export/snapshots/ipynb/error_cycle.ipynb.txt b/tests/_server/export/snapshots/ipynb/error_cycle.ipynb.txt
new file mode 100644
index 0000000000..f9f8c00a49
--- /dev/null
+++ b/tests/_server/export/snapshots/ipynb/error_cycle.ipynb.txt
@@ -0,0 +1,41 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "cycle",
+ "evalue": "This cell is in a cycle",
+ "output_type": "error",
+ "traceback": []
+ }
+ ],
+ "source": [
+ "x = y"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "cycle",
+ "evalue": "This cell is in a cycle",
+ "output_type": "error",
+ "traceback": []
+ }
+ ],
+ "source": [
+ "y = x"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/ipynb/error_redefinition.ipynb.txt b/tests/_server/export/snapshots/ipynb/error_redefinition.ipynb.txt
new file mode 100644
index 0000000000..8d8611bd28
--- /dev/null
+++ b/tests/_server/export/snapshots/ipynb/error_redefinition.ipynb.txt
@@ -0,0 +1,41 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "multiple-defs",
+ "evalue": "The variable 'x' was defined by another cell",
+ "output_type": "error",
+ "traceback": []
+ }
+ ],
+ "source": [
+ "x = 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "multiple-defs",
+ "evalue": "The variable 'x' was defined by another cell",
+ "output_type": "error",
+ "traceback": []
+ }
+ ],
+ "source": [
+ "x = 2 # Redefines x"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/ipynb/error_undefined.ipynb.txt b/tests/_server/export/snapshots/ipynb/error_undefined.ipynb.txt
new file mode 100644
index 0000000000..0bf81d71cf
--- /dev/null
+++ b/tests/_server/export/snapshots/ipynb/error_undefined.ipynb.txt
@@ -0,0 +1,31 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "NameError",
+ "evalue": "name 'undefined_variable' is not defined",
+ "output_type": "error",
+ "traceback": [
+ "Traceback (most recent call last):",
+ " File \"\", line 1, in <module>",
+ " x = undefined_variable # noqa: F821",
+ " ^^^^^^^^^^^^^^^^^^",
+ "NameError: name 'undefined_variable' is not defined",
+ ""
+ ]
+ }
+ ],
+ "source": [
+ "x = undefined_variable # noqa: F821"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/ipynb/error_value_with_stdout.ipynb.txt b/tests/_server/export/snapshots/ipynb/error_value_with_stdout.ipynb.txt
new file mode 100644
index 0000000000..edd0996748
--- /dev/null
+++ b/tests/_server/export/snapshots/ipynb/error_value_with_stdout.ipynb.txt
@@ -0,0 +1,38 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello before error\n"
+ ]
+ },
+ {
+ "ename": "ValueError",
+ "evalue": "test error",
+ "output_type": "error",
+ "traceback": [
+ "Traceback (most recent call last):",
+ " File \"\", line 2, in <module>",
+ " raise ValueError(\"test error\")",
+ "ValueError: test error",
+ ""
+ ]
+ }
+ ],
+ "source": [
+ "print(\"hello before error\")\n",
+ "raise ValueError(\"test error\")"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/ipynb/with_console_output.ipynb.txt b/tests/_server/export/snapshots/ipynb/with_console_output.ipynb.txt
new file mode 100644
index 0000000000..893f1bb418
--- /dev/null
+++ b/tests/_server/export/snapshots/ipynb/with_console_output.ipynb.txt
@@ -0,0 +1,63 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello stdout"
+ ]
+ },
+ {
+ "data": {
+ "text/html": [
+ "<pre class='text-xs'>12</pre>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "import sys\n",
+ "\n",
+ "sys.stdout.write(\"hello stdout\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "hello stderr"
+ ]
+ },
+ {
+ "data": {
+ "text/html": [
+ "<pre class='text-xs'>12</pre>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "sys.stderr.write(\"hello stderr\")"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/ipynb/with_dependencies.ipynb.txt b/tests/_server/export/snapshots/ipynb/with_dependencies.ipynb.txt
new file mode 100644
index 0000000000..749efbc9d3
--- /dev/null
+++ b/tests/_server/export/snapshots/ipynb/with_dependencies.ipynb.txt
@@ -0,0 +1,37 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "x = 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "y = x + 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "vblA",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "z = y + 1"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/notebook_with_cells.ipynb.txt b/tests/_server/export/snapshots/ipynb/with_layout.ipynb.txt
similarity index 67%
rename from tests/_server/export/snapshots/notebook_with_cells.ipynb.txt
rename to tests/_server/export/snapshots/ipynb/with_layout.ipynb.txt
index 132a5ebd0f..5bc7bac4c2 100644
--- a/tests/_server/export/snapshots/notebook_with_cells.ipynb.txt
+++ b/tests/_server/export/snapshots/ipynb/with_layout.ipynb.txt
@@ -4,18 +4,14 @@
"cell_type": "code",
"execution_count": null,
"id": "Hbol",
- "metadata": {
- "marimo": {
- "name": "cell_1"
- }
- },
+ "metadata": {},
"outputs": [],
"source": [
- "print(\"hello\")"
+ "x = 1"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
-}
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/ipynb/with_outputs.ipynb.txt b/tests/_server/export/snapshots/ipynb/with_outputs.ipynb.txt
new file mode 100644
index 0000000000..76cb008735
--- /dev/null
+++ b/tests/_server/export/snapshots/ipynb/with_outputs.ipynb.txt
@@ -0,0 +1,95 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import marimo as mo"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "&lt;marimo-vega data-initial-value=&#x27;{}&#x27; data-label=&#x27;null&#x27; data-spec=&#x27;{&amp;quot;config&amp;quot;:{&amp;quot;view&amp;quot;:{&amp;quot;continuousWidth&amp;quot;:300,&amp;quot;continuousHeight&amp;quot;:300}},&amp;quot;data&amp;quot;:{&amp;quot;url&amp;quot;:&amp;quot;data:text/plain;base64,QVJST1cxAAD/////qAAAAAQAAADy////FAAAAAQAAQAAAAoACwAIAAoABAD4////DAAAAAgACAAAAAQAAgAAADQAAAAEAAAAwP///yAAAAAQAAAACAAAAAECAAAAAAAAuP///0AAAAABAAAAAQAAAHkAAADs////OAAAACAAAAAYAAAAAQIAABAAEgAEABAAEQAIAAAADAAAAAAA9P///0AAAAABAAAACAAJAAQACAABAAAAeAAAAP////+wAAAABAAAAOz///+AAAAAAAAAABQAAAAEAAMADAATABAAEgAMAAQA6v///wMAAAAAAAAAXAAAABAAAAAAAAoAFAAEAAwAEAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAYAAAAAAAAAAAAAAACAAAAAwAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAIAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAFAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////8AAAAABAAAAOz///9AAAAAOAAAABQAAAAEAAAADAASABAABAAIAAwAAQAAALgAAAAAAAAAuAAAAAAAAACAAAAAAAAAAAAAAAAAAAAA+P///wwAAAAIAAgAAAAEAAIAAAA0AAAABAAAAMD///8gAAAAEAAAAAgAAAABAgAAAAAAALj///9AAAAAAQAAAAEAAAB5AAAA7P///zgAAAAgAAAAGAAAAAECAAAQABIABAAQABEACAAAAAwAAAAAAPT///9AAAAAAQAAAAgACQAEAAgAAQAAAHgA0gAAAEFSUk9XMQ==&amp;quot;,&amp;quot;format&amp;quot;:{&amp;quot;type&amp;quot;:&amp;quot;arrow&amp;quot;}},&amp;quot;mark&amp;quot;:{&amp;quot;type&amp;quot;:&amp;quot;point&amp;quot;},&amp;quot;encoding&amp;quot;:{&amp;quot;x&amp;quot;:{&amp;quot;field&amp;quot;:&amp;quot;x&amp;quot;,&amp;quot;type&amp;quot;:&amp;quot;quantitative&amp;quot;},&amp;quot;y&amp;quot;:{&amp;quot;field&amp;quot;:&amp;quot;y&amp;quot;,&amp;quot;type&amp;quot;:&amp;quot;quantitative&amp;quot;}},&amp;quot;width&amp;quot;:&amp;quot;container&amp;quot;,&amp;quot;&amp;#36;schema&amp;quot;:&amp;quot;https://vega.github.io/schema/vega-lite/v6.1.0.json&amp;quot;}&#x27; data-chart-selection=&#x27;true&#x27; data-field-selection=&#x27;true&#x27; data-embed-options=&#x27;{}&#x27;&gt;&lt;/marimo-vega&gt;"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "import altair as alt\n",
+ "import polars as pl\n",
+ "\n",
+ "df = pl.DataFrame({\"x\": [1, 2, 3], \"y\": [4, 5, 6]})\n",
+ "chart = alt.Chart(df).mark_point().encode(x=\"x\", y=\"y\")\n",
+ "mo.ui.altair_chart(chart)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "vblA",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "image/png": "IMAGE_BASE64_DATA"
+ },
+ "metadata": {
+ "image/png": {
+ "height": 413,
+ "width": 556
+ }
+ },
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "fig, ax = plt.subplots()\n",
+ "ax.plot([1, 2, 3], [4, 5, 6])\n",
+ "plt.gca()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bkHC",
+ "metadata": {},
+ "source": [
+ "# Hello World"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "lEQa",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello stdout\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(\"hello stdout\")"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/ipynb/with_stop.ipynb.txt b/tests/_server/export/snapshots/ipynb/with_stop.ipynb.txt
new file mode 100644
index 0000000000..682c7d37cf
--- /dev/null
+++ b/tests/_server/export/snapshots/ipynb/with_stop.ipynb.txt
@@ -0,0 +1,49 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<pre class='text-xs'>&#x27;Stopped early&#x27;</pre>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "import marimo as mo\n",
+ "\n",
+ "mo.stop(True, \"Stopped early\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "x = 10"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "vblA",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "y = x + 1"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/snapshots/notebook_with_outputs.ipynb.txt b/tests/_server/export/snapshots/notebook_with_outputs.ipynb.txt
deleted file mode 100644
index f7f53128cc..0000000000
--- a/tests/_server/export/snapshots/notebook_with_outputs.ipynb.txt
+++ /dev/null
@@ -1,181 +0,0 @@
-{
- "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": {
- "marimo": {
- "config": {
- "hide_code": true
- },
- "name": "cell_4"
- }
- },
- "outputs": [],
- "source": [
- "x = 10"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "vblA",
- "metadata": {
- "marimo": {
- "config": {
- "disabled": true
- }
- }
- },
- "outputs": [],
- "source": [
- "print(\"disabled\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "bkHC",
- "metadata": {
- "marimo": {
- "name": "cell_5"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "<pre class='text-xs'>22</pre>"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "y = x + 1\n",
- "y * 2"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "lEQa",
- "metadata": {
- "marimo": {
- "name": "cell_6"
- }
- },
- "outputs": [],
- "source": [
- "import marimo as mo"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "PKri",
- "metadata": {
- "marimo": {
- "name": "cell_7"
- }
- },
- "source": [
- "hello"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "Xref",
- "metadata": {
- "marimo": {
- "name": "cell_8"
- }
- },
- "outputs": [
- {
- "data": {
- "text/markdown": [
- "hello 10"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "mo.md(f\"hello {x}\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "SFPL",
- "metadata": {
- "marimo": {
- "name": "cell_11"
- }
- },
- "outputs": [
- {
- "data": {
- "text/markdown": [
- "&lt;marimo-slider data-initial-value=&#x27;0&#x27; data-label=&#x27;null&#x27; data-start=&#x27;0&#x27; data-stop=&#x27;10&#x27; data-steps=&#x27;[]&#x27; data-debounce=&#x27;false&#x27; data-disabled=&#x27;false&#x27; data-orientation=&#x27;&amp;quot;horizontal&amp;quot;&#x27; data-show-value=&#x27;false&#x27; data-include-input=&#x27;false&#x27; data-full-width=&#x27;false&#x27;&gt;&lt;/marimo-slider&gt;"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "mo.ui.slider(start=0, stop=10)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "BYtC",
- "metadata": {
- "marimo": {
- "name": "cell_12"
- }
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "<div style='display: flex;flex: 1;flex-direction: column;justify-content: flex-start;align-items: normal;flex-wrap: nowrap;gap: 0.5rem'><span class=\"markdown prose dark:prose-invert contents\"><span class=\"paragraph\">hello</span></span><span class=\"markdown prose dark:prose-invert contents\"><span class=\"paragraph\">world</span></span></div>"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "mo.vstack([mo.md(\"hello\"), mo.md(\"world\")])"
- ]
- }
- ],
- "metadata": {},
- "nbformat": 4,
- "nbformat_minor": 5
-}
diff --git a/tests/_server/export/snapshots/run_until_completion_with_console_output.txt b/tests/_server/export/snapshots/run_until_completion_with_console_output.txt
index 61816158d2..88ddf84b34 100644
--- a/tests/_server/export/snapshots/run_until_completion_with_console_output.txt
+++ b/tests/_server/export/snapshots/run_until_completion_with_console_output.txt
@@ -1,15 +1,15 @@
[
{
- "output": "",
+ "output": "<pre class='text-xs'>12</pre>",
"console": [
- "hello stderr"
+ "hello stdout"
],
"status": "idle"
},
{
- "output": "",
+ "output": "<pre class='text-xs'>12</pre>",
"console": [
- "hello stdout"
+ "hello stderr"
],
"status": "idle"
}
diff --git a/tests/_server/export/snapshots/run_until_completion_with_stop.txt b/tests/_server/export/snapshots/run_until_completion_with_stop.txt
index 1cab18710d..11c26b9ff2 100644
--- a/tests/_server/export/snapshots/run_until_completion_with_stop.txt
+++ b/tests/_server/export/snapshots/run_until_completion_with_stop.txt
@@ -1,6 +1,6 @@
[
{
- "output": "",
+ "output": "<pre class='text-xs'>&#x27;Stopped early&#x27;</pre>",
"console": [],
"status": "idle"
},
@@ -10,13 +10,7 @@
"status": "idle"
},
{
- "output": [
- {
- "type": "ancestor-stopped",
- "msg": "This cell wasn't run because an ancestor was stopped with `mo.stop`: ",
- "raising_cell": "MJUe"
- }
- ],
+ "output": "",
"console": [],
"status": "idle"
}
diff --git a/tests/_server/export/test_export_ipynb.py b/tests/_server/export/test_export_ipynb.py
new file mode 100644
index 0000000000..dbe31ec4ed
--- /dev/null
+++ b/tests/_server/export/test_export_ipynb.py
@@ -0,0 +1,78 @@
+"""Snapshot tests for ipynb export functionality."""
+
+from __future__ import annotations
+
+import pathlib
+import sys
+from pathlib import Path
+
+import pytest
+
+from marimo._ast.app import InternalApp
+from marimo._ast.load import load_app
+from marimo._convert.ipynb.from_ir import convert_from_ir_to_ipynb
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._server.export import run_app_then_export_as_ipynb
+from marimo._utils.marimo_path import MarimoPath
+from tests.mocks import delete_lines_with_files, simplify_images, snapshotter
+
+SELF_DIR = pathlib.Path(__file__).parent
+FIXTURES_DIR = SELF_DIR / "fixtures" / "apps"
+snapshot = snapshotter(__file__)
+
+HAS_DEPS = (
+ DependencyManager.polars.has()
+ and DependencyManager.altair.has()
+ and DependencyManager.matplotlib.has()
+)
+
+pytest.importorskip("nbformat")
+
+
+def _load_fixture_app(path: Path | str) -> InternalApp:
+ """Load a fixture app by name."""
+ if isinstance(path, str):
+ path = FIXTURES_DIR / f"{path}.py"
+ app = load_app(path)
+ assert app is not None
+ return InternalApp(app)
+
+
+# Apps with heavy dependencies (matplotlib, pandas, polars, etc) that timeout in CI
+HEAVY_DEPENDENCY_APPS = {"with_outputs"}
+
+
+ "app_path",
+ [
+ path
+ for path in FIXTURES_DIR.glob("*.py")
+ if path.stem not in HEAVY_DEPENDENCY_APPS
+ ],
+ ids=lambda path: path.stem,
+)
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ sys.version_info < (3, 11), reason="3.10 has different stack trace format"
+)
+async def test_export_ipynb(app_path: Path) -> None:
+ """Test ipynb export with actual execution outputs."""
+ internal_app = _load_fixture_app(app_path)
+
+ # Test without session view
+ content = convert_from_ir_to_ipynb(
+ internal_app, sort_mode="top-down", session_view=None
+ )
+ assert content is not None
+
+ # Test with actual run
+ result = await run_app_then_export_as_ipynb(
+ MarimoPath(app_path),
+ sort_mode="top-down",
+ cli_args={},
+ argv=None,
+ )
+ assert result.download_filename == f"{app_path.stem}.ipynb"
+ content = delete_lines_with_files(result.contents)
+ content = simplify_images(content)
+ snapshot(f"ipynb/{app_path.stem}.ipynb.txt", content)
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index c63a250261..2b075c2c69 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -1,7 +1,9 @@
from __future__ import annotations
import asyncio
+import base64
import json
+import pathlib
import sys
from typing import TYPE_CHECKING, Any
from unittest.mock import ANY, MagicMock, patch
@@ -9,18 +11,14 @@ from unittest.mock import ANY, MagicMock, patch
import pytest
from marimo._ast.app import App, InternalApp
+from marimo._ast.load import load_app
from marimo._config.config import DEFAULT_CONFIG
-from marimo._convert.ipynb.from_ir import (
- _convert_marimo_output_to_ipynb,
- _maybe_extract_dataurl,
-)
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.msgspec_encoder import encode_json_str
from marimo._messaging.notification import CellNotification
from marimo._server.export import (
export_as_wasm,
- run_app_then_export_as_ipynb,
run_app_until_completion,
)
from marimo._server.export.exporter import Exporter
@@ -28,72 +26,16 @@ from marimo._server.models.export import ExportAsHTMLRequest
from marimo._session.notebook import AppFileManager
from marimo._session.state.session_view import SessionView
from marimo._utils.marimo_path import MarimoPath
-from tests.mocks import snapshotter
+from tests.mocks import delete_lines_with_files, snapshotter
if TYPE_CHECKING:
from pathlib import Path
+SELF_DIR = pathlib.Path(__file__).parent
+FIXTURES_DIR = SELF_DIR / "fixtures" / "apps"
snapshot = snapshotter(__file__)
HAS_NBFORMAT = DependencyManager.nbformat.has()
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_export_ipynb_empty():
- app = App()
- internal_app = InternalApp(app)
- exporter = Exporter()
-
- content = exporter.export_as_ipynb(internal_app, sort_mode="top-down")
- snapshot("empty_notebook.ipynb.txt", content)
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_export_ipynb_with_cells():
- app = App()
-
- @app.cell()
- def cell_1():
- print("hello")
-
- internal_app = InternalApp(app)
- exporter = Exporter()
-
- content = exporter.export_as_ipynb(internal_app, sort_mode="top-down")
- snapshot("notebook_with_cells.ipynb.txt", content)
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_export_ipynb_sort_modes():
- app = App()
-
- @app.cell()
- def result(x, y):
- z = x + y
- return (z,)
-
- @app.cell()
- def __():
- x = 1
- return (x,)
-
- @app.cell()
- def __():
- y = 1
- return (y,)
-
- internal_app = InternalApp(app)
- exporter = Exporter()
-
- # Test top-down mode preserves document order
- content = exporter.export_as_ipynb(internal_app, sort_mode="top-down")
- snapshot("notebook_top_down.ipynb.txt", content)
-
- # Test topological mode respects dependencies
- content = exporter.export_as_ipynb(internal_app, sort_mode="topological")
- snapshot("notebook_topological.ipynb.txt", content)
-
-
HAS_DEPS = (
HAS_NBFORMAT
and DependencyManager.polars.has()
@@ -102,164 +44,50 @@ HAS_DEPS = (
)
-# ruff: noqa: B018
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
-async def test_export_ipynb_with_outputs(tmp_path: Path):
- app = App()
-
- # stdout
- @app.cell()
- def __():
- print("hello")
- return
-
- # # 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(hide_code=True)
- def cell_4():
- x = 10
- return (x,)
-
- # disabled
- @app.cell(disabled=True)
- def __():
- print("disabled")
- return
-
- # 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 ()
-
- # # 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):
- mo.vstack([mo.md("hello"), mo.md("world")])
- 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,)
-
- internal_app = InternalApp(app)
- exporter = Exporter()
-
- content = exporter.export_as_ipynb(
- internal_app, sort_mode="top-down", session_view=None
- )
- assert content is not None
-
- test_file = tmp_path / "notebook.py"
- test_file.write_text(InternalApp(app).to_py())
+def _print_messages(messages: list[CellNotification]) -> str:
+ result: list[dict[str, Any]] = []
+ for message in messages:
+ result.append(
+ {
+ "output": (
+ message.output.data if message.output is not None else None
+ ),
+ "console": (
+ [
+ output.data if output else None
+ for output in _as_list(message.console)
+ ]
+ if message.console is not None
+ else None
+ ),
+ "status": message.status,
+ }
+ )
+ # Use msgspec for encoding, then format with json for readable snapshots
+ encoded = encode_json_str(result)
+ return json.dumps(json.loads(encoded), indent=2)
- result = await run_app_then_export_as_ipynb(
- MarimoPath(test_file),
- sort_mode="top-down",
- cli_args={},
- argv=None,
- )
- assert not result.did_error
- assert result.download_filename == "notebook.ipynb"
- snapshot("notebook_with_outputs.ipynb.txt", result.contents)
+def _as_list(data: Any) -> list[Any]:
+ if isinstance(data, list):
+ return data # type: ignore
+ return [data]
-async def test_run_until_completion_with_stop():
- app = App()
- @app.cell()
- def cell_1():
- import marimo as mo
+def _load_fixture_app(name: str) -> InternalApp:
+ """Load a fixture app by name."""
+ app = load_app(FIXTURES_DIR / f"{name}.py")
+ assert app is not None
+ return InternalApp(app)
- return (mo,)
- @app.cell()
- def cell_2(mo):
- mo.stop(True)
- x = 10
- return (x,)
+# run_until_completion
- @app.cell()
- def cell_3(x):
- y = x + 1
- y
- return (y,)
- file_manager = AppFileManager.from_app(InternalApp(app))
+async def test_run_until_completion_with_stop() -> None:
+ """Test run until completion with mo.stop()."""
+ internal_app = _load_fixture_app("with_stop")
+ file_manager = AppFileManager.from_app(internal_app)
session_view, did_error = await run_app_until_completion(
file_manager,
@@ -282,7 +110,9 @@ async def test_run_until_completion_with_stop():
sys.version_info >= (3, 13), reason="3.13 has different stack trace format"
)
@pytest.mark.xfail(reason="flakey", strict=False)
-async def test_run_until_completion_with_stack_trace():
+async def test_run_until_completion_with_stack_trace() -> None:
+ """Test run until completion with stack trace from exception."""
+
app = App()
@app.cell()
@@ -308,7 +138,6 @@ async def test_run_until_completion_with_stack_trace():
file_manager = AppFileManager.from_app(InternalApp(app))
- # When not redirected, the stack trace is not included in the output
session_view, did_error = await run_app_until_completion(
file_manager, cli_args={}, argv=None
)
@@ -322,81 +151,94 @@ async def test_run_until_completion_with_stack_trace():
messages = _print_messages(cell_notifications)
snapshot(
"run_until_completion_with_stack_trace.txt",
- _delete_lines_with_files(messages),
+ delete_lines_with_files(messages),
)
-async def test_export_wasm_edit():
- app = App()
+@patch("marimo._server.export.echo")
+async def test_run_until_completion_with_console_output(
+ mock_echo: MagicMock,
+) -> None:
+ """Test run until completion with console output."""
+ internal_app = _load_fixture_app("with_console_output")
+ file_manager = AppFileManager.from_app(internal_app)
- @app.cell()
- def cell_1():
- print("hello wasm")
- return
+ session_view, did_error = await run_app_until_completion(
+ file_manager,
+ cli_args={},
+ argv=None,
+ )
+ assert did_error is False
- file_manager = AppFileManager.from_app(InternalApp(app))
- exporter = Exporter()
+ def _assert_contents() -> None:
+ mock_echo.assert_any_call("hello stdout", file=ANY, nl=False)
+ mock_echo.assert_any_call("hello stderr", file=ANY, nl=False)
- content, filename = exporter.export_as_wasm(
- filename=file_manager.filename,
- app=file_manager.app,
- display_config=DEFAULT_CONFIG["display"],
- mode="edit",
- code=file_manager.app.to_py(),
- show_code=True,
- )
+ # Console output notifications arrive asynchronously after CompletedRun.
+ n_tries = 0
+ limit = 50
+ while n_tries <= limit:
+ try:
+ _assert_contents()
+ break
+ except Exception:
+ n_tries += 1
+ await asyncio.sleep(0.1)
+ if n_tries > limit:
+ _assert_contents()
- assert filename == "notebook.wasm.html"
- assert "alert(" in content
- assert '"mode": "edit"' in content
+ cell_notifications = [
+ op
+ for op in session_view.notifications
+ if isinstance(op, CellNotification)
+ ]
+ snapshot(
+ "run_until_completion_with_console_output.txt",
+ _print_messages(cell_notifications),
+ )
-async def test_export_wasm_run():
- app = App()
+# WASM export
- @app.cell()
- def cell_1():
- print("hello wasm")
- return
- file_manager = AppFileManager.from_app(InternalApp(app))
+ ("mode", "expected_mode_in_content"),
+ [
+ ("edit", '"mode": "edit"'),
+ ("run", '"mode": "read"'),
+ ],
+)
+async def test_export_wasm(mode: str, expected_mode_in_content: str) -> None:
+ """Test WASM export in edit and run modes."""
+ internal_app = _load_fixture_app("basic")
+ file_manager = AppFileManager.from_app(internal_app)
exporter = Exporter()
content, filename = exporter.export_as_wasm(
filename=file_manager.filename,
app=file_manager.app,
display_config=DEFAULT_CONFIG["display"],
- mode="run",
+ mode=mode,
code=file_manager.app.to_py(),
show_code=True,
)
assert filename == "notebook.wasm.html"
assert "alert(" in content
- assert '"mode": "read"' in content
+ assert expected_mode_in_content in content
-async def test_export_html_with_layout(tmp_path: Path):
+async def test_export_html_with_layout(tmp_path: Path) -> None:
+ """Test HTML export with layout file."""
test_file = tmp_path / "test.py"
- test_file.write_text(
- """
-import marimo
-
-app = marimo.App(layout_file="layouts/layout.json")
-
-def __():
- x = 1
- return
-"""
- )
+ test_file.write_text((FIXTURES_DIR / "with_layout.py").read_text())
# Create the layout file
layout_file = tmp_path / "layouts" / "layout.json"
layout_file.parent.mkdir(parents=True, exist_ok=True)
layout_file.write_text('{"type": "slides", "data": {}}')
- # Export the app
result = export_as_wasm(
path=MarimoPath(test_file),
mode="edit",
@@ -407,174 +249,64 @@ def __():
assert "data:application/json" in result.contents
-def _print_messages(messages: list[CellNotification]) -> str:
- result: list[dict[str, Any]] = []
- for message in messages:
- result.append(
- {
- "output": (
- message.output.data if message.output is not None else None
- ),
- "console": (
- [
- output.data if output else None
- for output in _as_list(message.console)
- ]
- if message.console is not None
- else None
- ),
- "status": message.status,
- }
- )
- # Use msgspec for encoding, then format with json for readable snapshots
- encoded = encode_json_str(result)
- return json.dumps(json.loads(encoded), indent=2)
-
-
-def _as_list(data: Any) -> list[Any]:
- if isinstance(data, list):
- return data # type: ignore
- return [data]
-
+# HTML export
-def _delete_lines_with_files(output: str) -> str:
- # Remove any line that contains "File " up until a .py ending
- # Note: temp paths are already stripped in the exporter, so this may be
- # a no-op for most cases now
- def remove_file_name(line: str) -> str:
- if "File " not in line:
- return line
- start = line.index("File ")
- # Check if there's a .py extension to strip
- if ".py" in line[start:]:
- end = line.rindex(".py") + 3
- return line[0:start] + line[end:]
- return line
-
- return "\n".join(remove_file_name(line) for line in output.splitlines())
-
-
-@patch("marimo._server.export.echo")
-async def test_run_until_completion_with_console_output(mock_echo: MagicMock):
- app = App()
-
- @app.cell()
- def _():
- sys.stdout.write("hello stdout")
- None
- return
-
- @app.cell()
- def _():
- import sys
-
- sys.stderr.write("hello stderr")
- None
- return (sys,)
-
- file_manager = AppFileManager.from_app(InternalApp(app))
-
- session_view, did_error = await run_app_until_completion(
- file_manager,
- cli_args={},
- argv=None,
- )
- assert did_error is False
-
- def _assert_contents():
- # File should be sys.stderr, but it can change during CI execution
- # So, we use ANY for the file parameter.
- mock_echo.assert_any_call("hello stdout", file=ANY, nl=False)
- mock_echo.assert_any_call("hello stderr", file=ANY, nl=False)
-
- # Console output notifications arrive asynchronously after CompletedRun.
- # In slow CI environments, we need to wait longer for all notifications.
- n_tries = 0
- limit = 50
- while n_tries <= limit:
- try:
- _assert_contents()
- break
- except Exception:
- n_tries += 1
- await asyncio.sleep(0.1)
- if n_tries > limit:
- _assert_contents()
-
- cell_notifications = [
- op
- for op in session_view.notifications
- if isinstance(op, CellNotification)
- ]
- snapshot(
- "run_until_completion_with_console_output.txt",
- _print_messages(cell_notifications),
- )
+ ("include_code", "check_code_present", "check_code_absent"),
+ [
+ (True, ["return secret_value"], []),
+ (False, [], ["secret_value", "should_not_appear"]),
+ ],
+ ids=["with_code", "without_code"],
+)
+def test_export_as_html_code_inclusion(
+ session_view: SessionView,
+ include_code: bool,
+ check_code_present: list[str],
+ check_code_absent: list[str],
+) -> None:
+ """Test HTML export with and without code inclusion."""
-def test_export_as_html_with_serialization(session_view: SessionView):
- """Test HTML export uses new serialization approach correctly."""
app = App()
@app.cell()
- def cell_1():
- print("Hello World")
- return 10
-
- @app.cell()
- def cell_2():
- import marimo as mo
-
- mo.md("# Markdown Cell")
- return (mo,)
+ def test_cell():
+ secret_value = "should_not_appear"
+ print("visible output")
+ return secret_value
file_manager = AppFileManager.from_app(InternalApp(app))
-
- # Add some test data to session view
cell_ids = list(file_manager.app.cell_manager.cell_ids())
+
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
- data="10",
+ data="visible output",
),
console=[
CellOutput(
channel=CellChannel.STDOUT,
mimetype="text/plain",
- data="Hello World",
+ data="console message",
)
],
timestamp=0,
)
session_view.last_executed_code[cell_ids[0]] = (
- "print('Hello World')\nreturn 10"
- )
-
- session_view.cell_notifications[cell_ids[1]] = CellNotification(
- cell_id=cell_ids[1],
- status="idle",
- output=CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="text/html",
- data="<h1>Markdown Cell</h1>",
- ),
- console=[],
- timestamp=0,
- )
- session_view.last_executed_code[cell_ids[1]] = (
- "import marimo as mo\nmo.md('# Markdown Cell')\nreturn (mo,)"
+ "secret_value = 'should_not_appear'\n"
+ "print('visible output')\n"
+ "return secret_value"
)
exporter = Exporter()
-
request = ExportAsHTMLRequest(
- download=True,
+ download=not include_code,
files=[],
- include_code=True,
+ include_code=include_code,
)
html, filename = exporter.export_as_html(
@@ -586,23 +318,35 @@ def test_export_as_html_with_serialization(session_view: SessionView):
)
assert filename == "notebook.html"
- assert "Hello World" in html
- assert "Markdown Cell" in html
- assert 'data-marimo="true"' in html
+ # Output should always be visible
+ assert "visible output" in html
+
+ for text in check_code_present:
+ assert text in html
+ for text in check_code_absent:
+ assert text not in html
+
+def test_export_as_html_with_serialization(session_view: SessionView) -> None:
+ """Test HTML export uses new serialization approach correctly."""
-def test_export_as_html_without_code(session_view: SessionView):
- """Test HTML export clears code when include_code=False."""
app = App()
- @app.cell()
- def test_cell():
- secret_value = "should_not_appear"
- print("visible output")
- return secret_value
+ @app.cell()
+ def cell_1():
+ print("Hello World")
+ return 10
+
+ @app.cell()
+ def cell_2():
+ import marimo as mo
+
+ mo.md("# Markdown Cell")
+ return (mo,)
file_manager = AppFileManager.from_app(InternalApp(app))
+ # Add some test data to session view
cell_ids = list(file_manager.app.cell_manager.cell_ids())
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
@@ -610,27 +354,41 @@ def test_export_as_html_without_code(session_view: SessionView):
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
- data="visible output",
+ data="10",
),
console=[
CellOutput(
channel=CellChannel.STDOUT,
mimetype="text/plain",
- data="console message",
+ data="Hello World",
)
],
timestamp=0,
)
session_view.last_executed_code[cell_ids[0]] = (
- "secret_value = 'should_not_appear'\nprint('visible output')\nreturn secret_value"
+ "print('Hello World')\nreturn 10"
)
- exporter = Exporter()
+ session_view.cell_notifications[cell_ids[1]] = CellNotification(
+ cell_id=cell_ids[1],
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/html",
+ data="<h1>Markdown Cell</h1>",
+ ),
+ console=[],
+ timestamp=0,
+ )
+ session_view.last_executed_code[cell_ids[1]] = (
+ "import marimo as mo\nmo.md('# Markdown Cell')\nreturn (mo,)"
+ )
+ exporter = Exporter()
request = ExportAsHTMLRequest(
- download=False,
+ download=True,
files=[],
- include_code=False,
+ include_code=True,
)
html, filename = exporter.export_as_html(
@@ -641,19 +399,15 @@ def test_export_as_html_without_code(session_view: SessionView):
request=request,
)
- # Code should not appear in the HTML
- assert "secret_value" not in html
- assert "should_not_appear" not in html
-
- # But outputs should still be visible
- assert "visible output" in html
-
- # Console outputs should be cleared (no console message in HTML)
- # The exact format depends on template implementation
+ assert filename == "notebook.html"
+ assert "Hello World" in html
+ assert "Markdown Cell" in html
+ assert 'data-marimo="true"' in html
-def test_export_as_html_with_files(session_view: SessionView):
+def test_export_as_html_with_files(session_view: SessionView) -> None:
"""Test HTML export includes virtual files."""
+
app = App()
@app.cell()
@@ -673,14 +427,12 @@ def test_export_as_html_with_files(session_view: SessionView):
session_view.last_executed_code[cell_ids[0]] = "return 'test'"
exporter = Exporter()
-
request = ExportAsHTMLRequest(
download=True,
- files=["/@file/10-test.txt"], # Mock file reference
+ files=["/@file/10-test.txt"],
include_code=True,
)
- # Mock the read_virtual_file function to avoid file system dependencies
with patch(
"marimo._server.export.exporter.read_virtual_file"
) as mock_read:
@@ -695,12 +447,12 @@ def test_export_as_html_with_files(session_view: SessionView):
)
assert filename == "notebook.html"
- # Files should be embedded as data URLs
assert "data:" in html
-def test_export_as_html_with_cell_configs(session_view: SessionView):
+def test_export_as_html_with_cell_configs(session_view: SessionView) -> None:
"""Test HTML export preserves cell configurations through serialization."""
+
app = App()
@app.cell(hide_code=True, disabled=True, column=1)
@@ -724,7 +476,6 @@ def test_export_as_html_with_cell_configs(session_view: SessionView):
session_view.last_executed_code[cell_ids[0]] = "return 'configured'"
exporter = Exporter()
-
request = ExportAsHTMLRequest(
download=True,
files=[],
@@ -740,15 +491,15 @@ def test_export_as_html_with_cell_configs(session_view: SessionView):
)
assert filename == "notebook.html"
- # Verify that the serialized notebook data contains configuration
- assert (
- "hide_code" in html or "hideCode" in html
- ) # depends on serialization format
+ assert "hide_code" in html or "hideCode" in html
assert "configured" in html
-def test_export_as_html_preserves_output_order(session_view: SessionView):
+def test_export_as_html_preserves_output_order(
+ session_view: SessionView,
+) -> None:
"""Test HTML export preserves cell execution order in session snapshot."""
+
app = App()
@app.cell()
@@ -764,10 +515,8 @@ def test_export_as_html_preserves_output_order(session_view: SessionView):
return "third"
file_manager = AppFileManager.from_app(InternalApp(app))
-
cell_ids = list(file_manager.app.cell_manager.cell_ids())
- # Add cells in different order than execution
for i, cell_id in enumerate(cell_ids):
session_view.cell_notifications[cell_id] = CellNotification(
cell_id=cell_id,
@@ -783,7 +532,6 @@ def test_export_as_html_preserves_output_order(session_view: SessionView):
session_view.last_executed_code[cell_id] = f"return 'output_{i}'"
exporter = Exporter()
-
request = ExportAsHTMLRequest(
download=True,
files=[],
@@ -799,14 +547,15 @@ def test_export_as_html_preserves_output_order(session_view: SessionView):
)
assert filename == "notebook.html"
- # All outputs should be present
assert "output_0" in html
assert "output_1" in html
assert "output_2" in html
-def test_export_as_html_with_error_outputs(session_view: SessionView):
+def test_export_as_html_with_error_outputs(session_view: SessionView) -> None:
"""Test HTML export handles error outputs correctly."""
+ from marimo._messaging.errors import MarimoExceptionRaisedError
+
app = App()
@app.cell()
@@ -814,12 +563,8 @@ def test_export_as_html_with_error_outputs(session_view: SessionView):
raise ValueError("Test error")
file_manager = AppFileManager.from_app(InternalApp(app))
-
cell_ids = list(file_manager.app.cell_manager.cell_ids())
- # Mock an error output
- from marimo._messaging.errors import MarimoExceptionRaisedError
-
error = MarimoExceptionRaisedError(
exception_type="ValueError",
msg="Test error",
@@ -838,7 +583,6 @@ def test_export_as_html_with_error_outputs(session_view: SessionView):
)
exporter = Exporter()
-
request = ExportAsHTMLRequest(
download=True,
files=[],
@@ -854,12 +598,15 @@ def test_export_as_html_with_error_outputs(session_view: SessionView):
)
assert filename == "notebook.html"
- # Error should be serialized in the session snapshot
assert "Test error" in html or "ValueError" in html
-def test_export_as_html_code_hash_consistency(session_view: SessionView):
- """Test HTML export includes correct code hash regardless of include_code setting."""
+def test_export_as_html_code_hash_consistency(
+ session_view: SessionView,
+) -> None:
+ """Test HTML export includes correct code hash regardless of include_code."""
+ import re
+
app = App()
@app.cell()
@@ -867,8 +614,8 @@ def test_export_as_html_code_hash_consistency(session_view: SessionView):
return "test"
file_manager = AppFileManager.from_app(InternalApp(app))
-
cell_ids = list(file_manager.app.cell_manager.cell_ids())
+
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
@@ -910,10 +657,6 @@ def test_export_as_html_code_hash_consistency(session_view: SessionView):
request=request_without_code,
)
- # Both should contain the same code hash
- # The code hash should be in both because it's computed from the actual file code
- import re
-
# Extract code hash from both HTML outputs
hash_pattern = r"<marimo-code-hash[^>]*>([a-f0-9]+)</marimo-code-hash>"
@@ -928,20 +671,22 @@ def test_export_as_html_code_hash_consistency(session_view: SessionView):
"Code hashes should be identical"
)
- # Verify that when include_code=False, the notebook cells have empty code
assert '"code": ""' in html_without_code, (
"Cell code should be empty when include_code=False"
)
- # But when include_code=True, the notebook cells should have code
assert '"code": "return' in html_with_code, (
"Cell code should be present when include_code=True"
)
+# HTML export virtual file replacement tests
+
+
def test_export_html_replaces_virtual_files_in_outputs(
session_view: SessionView,
-):
+) -> None:
"""Test that virtual file URLs in HTML outputs are replaced with data URIs."""
+
app = App()
@app.cell()
@@ -951,10 +696,8 @@ def test_export_html_replaces_virtual_files_in_outputs(
return mo.image(src="test.png")
file_manager = AppFileManager.from_app(InternalApp(app))
-
cell_ids = list(file_manager.app.cell_manager.cell_ids())
- # Create HTML output with a virtual file reference
html_with_virtual_file = (
'<img src="./@file/100-test.png" alt="Test image">'
)
@@ -975,16 +718,12 @@ def test_export_html_replaces_virtual_files_in_outputs(
)
exporter = Exporter()
-
- # Include the virtual file in request.files
- # Note: request.files uses /@file/ format (without the ./)
request = ExportAsHTMLRequest(
download=True,
files=["/@file/100-test.png"],
include_code=True,
)
- # Mock read_virtual_file to return test image data
with patch(
"marimo._convert.common.dom_traversal.read_virtual_file"
) as mock_read:
@@ -999,22 +738,18 @@ def test_export_html_replaces_virtual_files_in_outputs(
)
assert filename == "notebook.html"
-
- # Virtual file should be replaced with data URI in the output
assert "./@file/100-test.png" not in html
assert "data:image/png;base64," in html
- # Verify the base64-encoded data is present (fake_image_data)
- import base64
-
expected_b64 = base64.b64encode(b"fake_image_data").decode()
assert expected_b64 in html
def test_export_html_replaces_multiple_virtual_files_complex(
session_view: SessionView,
-):
+) -> None:
"""Test virtual file replacement with multiple files and nested structures."""
+
app = App()
@app.cell()
@@ -1031,7 +766,6 @@ def test_export_html_replaces_multiple_virtual_files_complex(
@app.cell()
def cell_3():
- # Cell with both virtual file and external URL
return '<div><img src="./@file/300-diagram.svg"><img src="https://example.com/external.png"></div>'
file_manager = AppFileManager.from_app(InternalApp(app))
@@ -1082,27 +816,23 @@ def test_export_html_replaces_multiple_virtual_files_complex(
timestamp=2,
)
session_view.last_executed_code[cell_ids[2]] = (
- 'return \'<div><img src="./@file/300-diagram.svg"><img src="https://example.com/external.png"></div>\''
+ 'return \'<div><img src="./@file/300-diagram.svg">'
+ '<img src="https://example.com/external.png"></div>\''
)
exporter = Exporter()
-
- # Include all virtual files plus an extra one not in outputs
- # Note: request.files uses /@file/ format (without the ./)
request = ExportAsHTMLRequest(
download=True,
files=[
"/@file/100-chart.png",
"/@file/200-plot.png",
"/@file/300-diagram.svg",
- "/@file/400-unused.txt", # Not in any output
+ "/@file/400-unused.txt",
],
include_code=True,
)
- # Mock read_virtual_file
def mock_read_side_effect(filename: str, byte_length: int) -> bytes:
- """Return different mock data based on filename."""
del byte_length
if filename == "chart.png":
return b"chart_data"
@@ -1135,700 +865,14 @@ def test_export_html_replaces_multiple_virtual_files_complex(
assert filename == "notebook.html"
- # Verify base64-encoded data is present for replaced files
- import base64
-
chart_b64 = base64.b64encode(b"chart_data").decode()
plot_b64 = base64.b64encode(b"plot_data").decode()
diagram_b64 = base64.b64encode(b"<svg>diagram</svg>").decode()
- # At least some of the base64 data should be in the HTML
- # (virtual files are replaced with data URIs)
assert chart_b64 in html, "Chart data should be embedded as base64"
assert plot_b64 in html, "Plot data should be embedded as base64"
assert diagram_b64 in html, "Diagram data should be embedded as base64"
- # Data URIs should be present
- assert "data:image/png;base64," in html # For chart and plot
- assert "data:image/svg+xml;base64," in html # For diagram
-
- # External URL should remain unchanged
+ assert "data:image/png;base64," in html
+ assert "data:image/svg+xml;base64," in html
assert "https://example.com/external.png" in html
-
- # Virtual file URLs should be replaced (though they may be URL-encoded in JSON)
- # So we just check that the base64 data is present, which proves replacement worked
-
-
-# Tests for marimo mimebundle ipynb export support
-
-
-def test_maybe_extract_dataurl_with_base64_data():
- """Test that _maybe_extract_dataurl extracts base64 data from data URLs."""
- data_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA"
- result = _maybe_extract_dataurl(data_url)
- assert result == "iVBORw0KGgoAAAANSUhEUgAAAAUA"
-
-
-def test_maybe_extract_dataurl_without_base64():
- """Test that _maybe_extract_dataurl returns non-data-URL strings as-is."""
- regular_string = "hello world"
- result = _maybe_extract_dataurl(regular_string)
- assert result == "hello world"
-
-
-def test_maybe_extract_dataurl_with_non_string():
- """Test that _maybe_extract_dataurl returns non-string data as-is."""
- data = {"key": "value"}
- result = _maybe_extract_dataurl(data)
- assert result == {"key": "value"}
-
- data = 123
- result = _maybe_extract_dataurl(data)
- assert result == 123
-
-
-def test_maybe_extract_dataurl_with_data_prefix_but_no_base64():
- """Test that _maybe_extract_dataurl handles data: prefix without base64."""
- data_url = "data:text/plain,hello"
- result = _maybe_extract_dataurl(data_url)
- assert result == "data:text/plain,hello"
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_marimo_mimebundle_to_ipynb_with_known_mimetypes():
- """Test that marimo mimebundle with known mimetypes are converted correctly."""
- mimebundle_data = json.dumps(
- {
- "text/plain": "Hello",
- "text/html": "<p>Hello</p>",
- "image/png": "data:image/png;base64,iVBORw0KGgo=",
- }
- )
-
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="application/vnd.marimo+mimebundle",
- data=mimebundle_data,
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- assert len(result) == 1
- assert result[0]["output_type"] == "display_data"
- assert "text/plain" in result[0]["data"]
- assert result[0]["data"]["text/plain"] == "Hello"
- assert "text/html" in result[0]["data"]
- assert result[0]["data"]["text/html"] == "<p>Hello</p>"
- assert "image/png" in result[0]["data"]
- # Base64 data should be extracted from data URL
- assert result[0]["data"]["image/png"] == "iVBORw0KGgo="
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_marimo_mimebundle_with_multiple_formats():
- """Test marimo mimebundle with multiple output formats."""
- mimebundle_data = json.dumps(
- {
- "text/plain": "Figure(640x480)",
- "text/html": "<div>Chart</div>",
- "image/png": "data:image/png;base64,PNG_BASE64_DATA",
- "image/svg+xml": "<svg>...</svg>",
- "application/json": {"data": [1, 2, 3]},
- }
- )
-
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="application/vnd.marimo+mimebundle",
- data=mimebundle_data,
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- assert len(result) == 1
- assert result[0]["output_type"] == "display_data"
- assert result[0]["data"]["text/plain"] == "Figure(640x480)"
- assert result[0]["data"]["text/html"] == "<div>Chart</div>"
- assert result[0]["data"]["image/png"] == "PNG_BASE64_DATA"
- assert result[0]["data"]["image/svg+xml"] == "<svg>...</svg>"
- assert result[0]["data"]["application/json"] == {"data": [1, 2, 3]}
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_regular_output_extracts_dataurl():
- """Test that regular outputs also extract data URLs."""
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="image/png",
- data="data:image/png;base64,REGULAR_PNG_DATA",
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- assert len(result) == 1
- assert result[0]["output_type"] == "display_data"
- assert result[0]["data"]["image/png"] == "REGULAR_PNG_DATA"
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_regular_output_without_dataurl():
- """Test that regular outputs without data URLs are passed through."""
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="text/plain",
- data="Hello World",
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- assert len(result) == 1
- assert result[0]["output_type"] == "display_data"
- assert result[0]["data"]["text/plain"] == "Hello World"
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_marimo_mimebundle_empty():
- """Test that empty marimo mimebundle produces no output."""
- mimebundle_data = json.dumps({})
-
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="application/vnd.marimo+mimebundle",
- data=mimebundle_data,
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- # Empty mimebundle should not produce any output
- assert len(result) == 0
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_marimo_mimebundle_with_console_output():
- """Test that console outputs (stdout/stderr) are converted correctly."""
- # Test just console outputs without main output
- console_outputs = [
- CellOutput(
- channel=CellChannel.STDOUT,
- mimetype="text/plain",
- data="Console output\n",
- ),
- CellOutput(
- channel=CellChannel.STDERR,
- mimetype="text/plain",
- data="Warning message\n",
- ),
- ]
-
- result = _convert_marimo_output_to_ipynb(None, console_outputs)
-
- # Should have stdout and stderr outputs
- assert len(result) == 2
- assert result[0]["output_type"] == "stream"
- assert result[0]["name"] == "stdout"
- assert result[0]["text"] == "Console output\n"
- assert result[1]["output_type"] == "stream"
- assert result[1]["name"] == "stderr"
- assert result[1]["text"] == "Warning message\n"
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_marimo_mimebundle_with_both_output_and_console():
- """Test marimo mimebundle with both cell output and console outputs."""
- mimebundle_data = json.dumps(
- {
- "text/plain": "Result",
- "image/png": "PNG_DATA",
- }
- )
-
- main_output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="application/vnd.marimo+mimebundle",
- data=mimebundle_data,
- )
-
- console_outputs = [
- CellOutput(
- channel=CellChannel.STDOUT,
- mimetype="text/plain",
- data="Console output\n",
- ),
- ]
-
- # First convert console outputs
- console_result = _convert_marimo_output_to_ipynb(None, console_outputs)
- # Then convert main output
- main_result = _convert_marimo_output_to_ipynb(main_output, [])
-
- # Verify console output
- assert len(console_result) == 1
- assert console_result[0]["output_type"] == "stream"
- assert console_result[0]["name"] == "stdout"
-
- # Verify main output
- assert len(main_result) == 1
- assert main_result[0]["output_type"] == "display_data"
- assert main_result[0]["data"]["text/plain"] == "Result"
- assert main_result[0]["data"]["image/png"] == "PNG_DATA"
-
-
-# Tests for metadata in ipynb export
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_marimo_mimebundle_with_metadata():
- """Test that metadata from __metadata__ key is included in ipynb output."""
- mimebundle_data = json.dumps(
- {
- "text/plain": "Figure",
- "image/png": "PNG_DATA",
- "__metadata__": {
- "width": 640,
- "height": 480,
- "dpi": 100,
- },
- }
- )
-
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="application/vnd.marimo+mimebundle",
- data=mimebundle_data,
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- assert len(result) == 1
- assert result[0]["output_type"] == "display_data"
- assert result[0]["data"]["text/plain"] == "Figure"
- assert result[0]["data"]["image/png"] == "PNG_DATA"
- # Verify metadata is included
- assert "metadata" in result[0]
- assert result[0]["metadata"] == {
- "width": 640,
- "height": 480,
- "dpi": 100,
- }
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_marimo_mimebundle_without_metadata():
- """Test that outputs without metadata have empty metadata dict."""
- mimebundle_data = json.dumps(
- {
- "text/plain": "Figure",
- "image/png": "PNG_DATA",
- }
- )
-
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="application/vnd.marimo+mimebundle",
- data=mimebundle_data,
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- assert len(result) == 1
- assert result[0]["output_type"] == "display_data"
- assert result[0]["data"]["text/plain"] == "Figure"
- assert result[0]["data"]["image/png"] == "PNG_DATA"
- # Verify metadata is empty
- assert "metadata" in result[0]
- assert result[0]["metadata"] == {}
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_marimo_mimebundle_with_non_dict_metadata():
- """Test that non-dict metadata is ignored."""
- mimebundle_data = json.dumps(
- {
- "text/plain": "Figure",
- "image/png": "PNG_DATA",
- "__metadata__": "not a dict", # This should be ignored
- }
- )
-
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="application/vnd.marimo+mimebundle",
- data=mimebundle_data,
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- assert len(result) == 1
- assert result[0]["output_type"] == "display_data"
- # Verify metadata is empty when non-dict value is provided
- assert "metadata" in result[0]
- assert result[0]["metadata"] == {}
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_marimo_mimebundle_with_nested_metadata():
- """Test that nested metadata structures are preserved."""
- mimebundle_data = json.dumps(
- {
- "text/plain": "Figure",
- "image/png": "PNG_DATA",
- "__metadata__": {
- "figure": {
- "width": 640,
- "height": 480,
- },
- "plot": {
- "type": "line",
- "color": "blue",
- },
- "tags": ["important", "experiment-1"],
- },
- }
- )
-
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="application/vnd.marimo+mimebundle",
- data=mimebundle_data,
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- assert len(result) == 1
- assert result[0]["output_type"] == "display_data"
- # Verify nested metadata is preserved
- assert result[0]["metadata"] == {
- "figure": {
- "width": 640,
- "height": 480,
- },
- "plot": {
- "type": "line",
- "color": "blue",
- },
- "tags": ["important", "experiment-1"],
- }
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_marimo_mimebundle_metadata_not_in_data():
- """Test that __metadata__ key is not included in output data."""
- mimebundle_data = json.dumps(
- {
- "text/plain": "Figure",
- "image/png": "PNG_DATA",
- "__metadata__": {
- "width": 640,
- "height": 480,
- },
- }
- )
-
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="application/vnd.marimo+mimebundle",
- data=mimebundle_data,
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- assert len(result) == 1
- assert result[0]["output_type"] == "display_data"
- # Verify __metadata__ is not in the data dict
- assert "__metadata__" not in result[0]["data"]
- assert "text/plain" in result[0]["data"]
- assert "image/png" in result[0]["data"]
- # But metadata should be in the metadata field
- assert result[0]["metadata"] == {
- "width": 640,
- "height": 480,
- }
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_marimo_mimebundle_dict():
- """Handle the case when the mimebundle is a dict, not JSON-dumped string"""
- mimebundle_data = {
- "text/plain": "Figure",
- "image/png": "PNG_DATA",
- "__metadata__": {
- "width": 640,
- "height": 480,
- },
- }
-
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="application/vnd.marimo+mimebundle",
- data=mimebundle_data,
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- assert len(result) == 1
- assert result[0]["output_type"] == "display_data"
- # Verify __metadata__ is not in the data dict
- assert "__metadata__" not in result[0]["data"]
- assert "text/plain" in result[0]["data"]
- assert "image/png" in result[0]["data"]
- # But metadata should be in the metadata field
- assert result[0]["metadata"] == {
- "width": 640,
- "height": 480,
- }
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-def test_convert_regular_output_has_empty_metadata():
- """Test that regular outputs (non-mimebundle) have empty metadata."""
- output = CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="text/plain",
- data="Hello World",
- )
-
- result = _convert_marimo_output_to_ipynb(output, [])
-
- assert len(result) == 1
- assert result[0]["output_type"] == "display_data"
- assert result[0]["data"]["text/plain"] == "Hello World"
- # Regular outputs should have empty metadata
- assert "metadata" in result[0]
- assert result[0]["metadata"] == {}
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-async def test_export_ipynb_with_exception():
- """Test that exceptions are properly formatted in ipynb output."""
- app = App()
-
- @app.cell()
- def _():
- x = undefined_variable # noqa: F821
- return (x,)
-
- # Run and export
- file_manager = AppFileManager.from_app(InternalApp(app))
- session_view, did_error = await run_app_until_completion(
- file_manager, cli_args={}, argv=None, quiet=True
- )
- assert did_error is True
-
- result = Exporter().export_as_ipynb(
- InternalApp(app), sort_mode="top-down", session_view=session_view
- )
- notebook = json.loads(result)
-
- # Find the error output
- outputs = notebook["cells"][0]["outputs"]
- error_outputs = [o for o in outputs if o["output_type"] == "error"]
- assert len(error_outputs) == 1
- assert error_outputs[0]["ename"] == "NameError"
- assert "undefined_variable" in error_outputs[0]["evalue"]
- # Traceback should be a list of strings
- assert isinstance(error_outputs[0]["traceback"], list)
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-async def test_export_ipynb_with_stdout_and_exception():
- """Test cell with both stdout and exception."""
- app = App()
-
- @app.cell()
- def _():
- print("hello before error")
- raise ValueError("test error")
-
- file_manager = AppFileManager.from_app(InternalApp(app))
- session_view, did_error = await run_app_until_completion(
- file_manager, cli_args={}, argv=None, quiet=True
- )
- assert did_error is True
-
- result = Exporter().export_as_ipynb(
- InternalApp(app), sort_mode="top-down", session_view=session_view
- )
- notebook = json.loads(result)
- outputs = notebook["cells"][0]["outputs"]
-
- # Should have both stdout and error
- stdout_outputs = [o for o in outputs if o.get("name") == "stdout"]
- error_outputs = [o for o in outputs if o["output_type"] == "error"]
-
- assert len(stdout_outputs) == 1
- assert "hello before error" in stdout_outputs[0]["text"][0]
- assert len(error_outputs) == 1
- assert error_outputs[0]["ename"] == "ValueError"
- assert "test error" in error_outputs[0]["evalue"]
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-async def test_export_ipynb_redefinition_error():
- """Test that cells depending on errored cells show ancestor error."""
- app = App()
-
- @app.cell()
- def _():
- x = 1
- return (x,)
-
- @app.cell()
- def _():
- x = 2
- return (x,)
-
- @app.cell()
- def _(x):
- y = x + 1
- return (y,)
-
- file_manager = AppFileManager.from_app(InternalApp(app))
- session_view, did_error = await run_app_until_completion(
- file_manager, cli_args={}, argv=None, quiet=True
- )
- assert did_error is True
-
- result = Exporter().export_as_ipynb(
- InternalApp(app), sort_mode="top-down", session_view=session_view
- )
- notebook = json.loads(result)
-
- # Second cell should have an ancestor error
- assert len(notebook["cells"]) >= 3
- second_cell_outputs = notebook["cells"][1]["outputs"]
- error_outputs = [
- o for o in second_cell_outputs if o["output_type"] == "error"
- ]
- # Ancestor errors might be represented differently
- # At minimum, there should be some error indication
- assert len(error_outputs) >= 1
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-async def test_export_ipynb_cycle_error():
- """Test that cells in a cycle show cycle error."""
- app = App()
-
- @app.cell()
- def _():
- x = y + 1 # noqa: F821
- return (x,)
-
- @app.cell()
- def _(x):
- y = x + 1
- return (y,)
-
- file_manager = AppFileManager.from_app(InternalApp(app))
- session_view, did_error = await run_app_until_completion(
- file_manager, cli_args={}, argv=None, quiet=True
- )
- assert did_error is True
-
- result = Exporter().export_as_ipynb(
- InternalApp(app), sort_mode="top-down", session_view=session_view
- )
- notebook = json.loads(result)
-
- # Second cell should have an ancestor error
- assert len(notebook["cells"]) >= 2
- second_cell_outputs = notebook["cells"][1]["outputs"]
- error_outputs = [
- o for o in second_cell_outputs if o["output_type"] == "error"
- ]
- # Ancestor errors might be represented differently
- # At minimum, there should be some error indication
- assert len(error_outputs) >= 1
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
-async def test_export_ipynb_ancestor_error():
- """Test that cells depending on errored cells show ancestor error."""
- app = App()
-
- @app.cell()
- def _():
- x = undefined # noqa: F821
- return (x,)
-
- @app.cell()
- def _(x):
- y = x + 1
- return (y,)
-
- file_manager = AppFileManager.from_app(InternalApp(app))
- session_view, did_error = await run_app_until_completion(
- file_manager, cli_args={}, argv=None, quiet=True
- )
- assert did_error is True
-
- result = Exporter().export_as_ipynb(
- InternalApp(app), sort_mode="top-down", session_view=session_view
- )
- notebook = json.loads(result)
-
- # Second cell should have an ancestor error
- assert len(notebook["cells"]) >= 2
- second_cell_outputs = notebook["cells"][1]["outputs"]
- error_outputs = [
- o for o in second_cell_outputs if o["output_type"] == "error"
- ]
- # Ancestor errors might be represented differently
- # At minimum, there should be some error indication
- assert len(error_outputs) >= 1
-
-
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
- sys.version_info < (3, 11), reason="3.10 has different stack trace format"
-)
-async def test_export_ipynb_with_error_snapshot(tmp_path: Path):
- """Snapshot test for error output formatting with cycles and errors."""
- app = App()
-
- # Cell 1: Part of cycle (x depends on y)
- @app.cell()
- def _(y): # noqa: F811
- x = y
- return (x,)
-
- # Cell 2: Normal cell (Y = 0)
- @app.cell()
- def _():
- Y = 0 # noqa: N806
- return (Y,)
-
- # Cell 3: Ancestor error (depends on z which fails)
- @app.cell()
- def _b(z):
- Z = z # noqa: N806
- return (Z,)
-
- # Cell 4: ZeroDivisionError
- @app.cell()
- def _a():
- z = 1 / 0
- return (z,)
-
- # Cell 5: Part of cycle (y depends on x)
- @app.cell()
- def _(x, Y): # noqa: N803
- y = x
- y = Y # noqa: F841
- return (y,)
-
- internal_app = InternalApp(app)
- test_file = tmp_path / "notebook.py"
- test_file.write_text(internal_app.to_py())
-
- result = await run_app_then_export_as_ipynb(
- MarimoPath(test_file),
- sort_mode="top-down",
- cli_args={},
- argv=None,
- )
- assert result.did_error is True
-
- # Filter file paths for deterministic snapshots
- content = _delete_lines_with_files(result.contents)
- snapshot("notebook_with_error.ipynb.txt", content)
diff --git a/tests/mocks.py b/tests/mocks.py
index ccebaa4031..f522a5ae8d 100644
--- a/tests/mocks.py
+++ b/tests/mocks.py
@@ -126,6 +126,39 @@ def _sanitize_version(output: str) -> str:
)
+def delete_lines_with_files(output: str) -> str:
+ """Remove file paths from error messages for consistent snapshots."""
+
+ def remove_file_name(line: str) -> str:
+ if "File " not in line:
+ return line
+ start = line.index("File ")
+ if ".py" in line[start:]:
+ end = line.rindex(".py") + 3
+ return line[0:start] + line[end:]
+ return line
+
+ return "\n".join(remove_file_name(line) for line in output.splitlines())
+
+
+def simplify_images(output: str) -> str:
+ """Simplify image paths for consistent snapshots."""
+ # Handle data URLs
+ output = re.sub(
+ r"data:image/png;base64,.*",
+ "data:image/png;base64,IMAGE_BASE64_DATA",
+ output,
+ )
+
+ # Handle "image/png": "*"
+ output = re.sub(
+ r'"image/png": ".*"',
+ '"image/png": "IMAGE_BASE64_DATA"',
+ output,
+ )
+ return output
+
+
NON_WINDOWS_EDGE_CASE_FILENAMES = [
"test<script>.py",
'test"quotes".py',