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: export mo.mpl.interactive as PNG, and altair as json spec when running (#7874)

Myles Scolnick20cc65ed92d4
diff --git a/.github/workflows/test_be_dagger.yaml.skip b/.github/workflows/test_be_dagger.yaml.skip
index 0c26c99c6a..98eae021e5 100644
--- a/.github/workflows/test_be_dagger.yaml.skip
+++ b/.github/workflows/test_be_dagger.yaml.skip
@@ -31,9 +31,6 @@ jobs:
continue-on-error: true
steps:
- - name: 🛑 Cancel Previous Runs
- uses: styfle/[email protected]
-
- uses: actions/checkout@v4
- uses: dagger/dagger-for-github@v6
diff --git a/.github/workflows/test_cli.yaml b/.github/workflows/test_cli.yaml
index 6d5814b0e2..10fbd9b7db 100644
--- a/.github/workflows/test_cli.yaml
+++ b/.github/workflows/test_cli.yaml
@@ -129,11 +129,10 @@ jobs:
matrix:
python-version: ["3.12"]
# TODO: update to latest once networking issues on macos-15 are resolved
+ # https://github.com/actions/runner-images/issues/10924
os: [ubuntu-latest, macos-14, windows-latest]
steps:
- - name: 🛑 Cancel Previous Runs
- uses: styfle/[email protected]
- uses: actions/checkout@v4
- name: 🐍 Setup uv
@@ -144,23 +143,21 @@ jobs:
# TODO(https://github.com/astral-sh/setup-uv/issues/226): Remove this.
prune-cache: ${{ matrix.os != 'windows-latest' }}
- - name: Install Python deps
- run: |
- uv add pytest pytest-asyncio pytest-timeout nbformat pyzmq
-
- name: Download wheel
uses: actions/download-artifact@v4
with:
name: testwheel
- - name: Install marimo
- shell: bash
- run: uv pip install marimo*whl
-
- name: Test CLI
shell: bash
run: |
- uv run --no-project pytest -v tests/_cli/test_cli* --maxfail=2
+ export MARIMO_WHEEL_PATH=$(ls $PWD/marimo*.whl)
+ uv run \
+ --group=test-optional \
+ --group=test \
+ --group=dev \
+ --with="${MARIMO_WHEEL_PATH}" \
+ pytest -v tests/_cli/test_cli* --maxfail=2
test_examples:
needs: [changes]
diff --git a/.github/workflows/test_fe.yaml b/.github/workflows/test_fe.yaml
index 997e00c3fc..7885139e36 100644
--- a/.github/workflows/test_fe.yaml
+++ b/.github/workflows/test_fe.yaml
@@ -44,9 +44,6 @@ jobs:
shell: bash
steps:
- - name: 🛑 Cancel Previous Runs
- uses: styfle/[email protected]
-
- name: ⬇️ Checkout repo
uses: actions/checkout@v4
with:
diff --git a/.github/workflows/test_fe_dagger.yaml.skip b/.github/workflows/test_fe_dagger.yaml.skip
index 2cdf5251ea..cc37e22362 100644
--- a/.github/workflows/test_fe_dagger.yaml.skip
+++ b/.github/workflows/test_fe_dagger.yaml.skip
@@ -33,9 +33,6 @@ jobs:
continue-on-error: true
steps:
- - name: 🛑 Cancel Previous Runs
- uses: styfle/[email protected]
-
- name: ⬇️ Checkout repo
uses: actions/checkout@v4
diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.py
index 74ef298fa0..693bdf9842 100644
--- a/marimo/_output/formatters/altair_formatters.py
+++ b/marimo/_output/formatters/altair_formatters.py
@@ -2,7 +2,7 @@
from __future__ import annotations
import json
-from typing import Any, Literal
+from typing import Any
from urllib.request import urlopen
from marimo._config.config import Theme
@@ -13,12 +13,10 @@ from marimo._output.formatters.formatter_factory import FormatterFactory
from marimo._plugins.core.media import io_to_data_url
from marimo._plugins.ui._impl.altair_chart import (
AltairChartType,
+ chart_to_json,
maybe_fix_vegafusion_background,
maybe_make_full_width,
)
-from marimo._plugins.ui._impl.charts.altair_transformer import (
- sanitize_nan_infs,
-)
LOGGER = marimo_logger()
@@ -187,31 +185,3 @@ def _apply_format_locales(embed_options: dict[str, Any]) -> dict[str, Any]:
embed_options["formatLocale"] = get_format_locale(format_locale)
return embed_options
-
-
-def chart_to_json(
- chart: AltairChartType,
- spec_format: Literal["vega", "vega-lite"] = "vega-lite",
- validate: bool = True,
-) -> str:
- """
- Convert an altair chart to a JSON string.
-
- This function is a wrapper around the altair.Chart.to_json method.
- It sanitizes the data in the chart if necessary and validates the spec.
- """
- try:
- return chart.to_json(
- format=spec_format,
- validate=validate,
- allow_nan=False,
- default=str,
- )
- except ValueError:
- chart.data = sanitize_nan_infs(chart.data)
- return chart.to_json(
- format=spec_format,
- validate=validate,
- allow_nan=False,
- default=str,
- )
diff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.py
index ecb2f84193..f53f96ac8c 100644
--- a/marimo/_output/hypertext.py
+++ b/marimo/_output/hypertext.py
@@ -137,21 +137,22 @@ class Html(MIME):
return self._text
def _mime_(self) -> tuple[KnownMimeType, str]:
- no_js = is_no_js()
- 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]
- )
+ if not is_no_js():
+ return ("text/html", self.text)
+
+ # Try PNG representation first (for objects with _repr_png_)
+ repr_png = getattr(self, "_repr_png_", None)
+ if repr_png is not None and callable(repr_png):
+ png_bytes = cast(bytes, repr_png())
+ return ("image/png", png_bytes.decode())
+
+ # Try markdown representation (for objects with _repr_markdown_)
+ repr_markdown = getattr(self, "_repr_markdown_", None)
+ if repr_markdown is not None and callable(repr_markdown):
+ markdown_text = cast(str, repr_markdown())
+ return ("text/markdown", markdown_text)
+
+ # Default to HTML
return ("text/html", self.text)
def __format__(self, spec: str) -> str:
diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.py
index e1398af6f6..e6ac2d58d6 100644
--- a/marimo/_plugins/stateless/mpl/_mpl.py
+++ b/marimo/_plugins/stateless/mpl/_mpl.py
@@ -444,6 +444,31 @@ def new_figure_manager_given_figure(
return manager
+class InteractiveMplHtml(Html):
+ """Html subclass that provides PNG fallback for ipynb export."""
+
+ def __init__(self, text: str, figure: Union[Figure, SubFigure]) -> None:
+ self._figure = figure
+ super().__init__(text)
+
+ def _repr_png_(self) -> bytes:
+ """Return base64-encoded PNG bytes for ipynb export fallback.
+
+ The Html._mime_ method expects _repr_png_ to return bytes that
+ can be decoded to a UTF-8 string, so we return base64-encoded data.
+ """
+ import base64
+
+ from matplotlib.figure import Figure
+
+ buf = io.BytesIO()
+ if isinstance(self._figure, Figure):
+ self._figure.savefig(buf, format="png", bbox_inches="tight")
+ else:
+ self._figure.figure.canvas.print_figure(buf, format="png")
+ return base64.b64encode(buf.getvalue())
+
+
@mddoc
def interactive(figure: Union[Figure, SubFigure, Axes]) -> Html:
"""Render a matplotlib figure using an interactive viewer.
@@ -510,13 +535,14 @@ def interactive(figure: Union[Figure, SubFigure, Axes]) -> Html:
content = _template(str(figure_manager.num), port)
- return Html(
+ return InteractiveMplHtml(
h.iframe(
srcdoc=html.escape(content),
width="100%",
height="550px",
onload="__resizeIframe(this)",
- )
+ ),
+ figure,
)
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index 47af7c72be..a0052c4303 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -21,10 +21,13 @@ from narwhals.typing import IntoDataFrame, IntoLazyFrame
from marimo import _loggers
from marimo._dependencies.dependencies import DependencyManager
+from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.hypertext import is_no_js
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._plugins.ui._impl.charts.altair_transformer import (
register_transformers,
+ sanitize_nan_infs,
)
from marimo._utils import flatten
from marimo._utils.narwhals_utils import (
@@ -652,6 +655,15 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):
on_change=on_change,
)
+ # Override _mime_ to return an Altair spec in non-JS environments
+ def _mime_(self) -> tuple[KnownMimeType, str]:
+ if is_no_js():
+ return (
+ "application/vnd.vega.v5+json",
+ chart_to_json(self._chart, validate=False),
+ )
+ return ("text/html", self.text)
+
@property
def selections(self) -> ChartSelection:
return self._chart_selection
@@ -967,3 +979,31 @@ def _has_no_nested_hconcat(chart: AltairChartType) -> bool:
return all(_has_no_nested_hconcat(layer) for layer in chart.layer)
return True
+
+
+def chart_to_json(
+ chart: AltairChartType,
+ spec_format: Literal["vega", "vega-lite"] = "vega-lite",
+ validate: bool = True,
+) -> str:
+ """
+ Convert an altair chart to a JSON string.
+
+ This function is a wrapper around the altair.Chart.to_json method.
+ It sanitizes the data in the chart if necessary and validates the spec.
+ """
+ try:
+ return chart.to_json(
+ format=spec_format,
+ validate=validate,
+ allow_nan=False,
+ default=str,
+ )
+ except ValueError:
+ chart.data = sanitize_nan_infs(chart.data)
+ return chart.to_json(
+ format=spec_format,
+ validate=validate,
+ allow_nan=False,
+ default=str,
+ )
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py
index 4ec5835b6b..09466622c0 100644
--- a/marimo/_plugins/ui/_impl/plotly.py
+++ b/marimo/_plugins/ui/_impl/plotly.py
@@ -13,6 +13,8 @@ from typing import (
from marimo import _loggers
from marimo._dependencies.dependencies import DependencyManager
+from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.hypertext import is_no_js
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import UIElement
@@ -303,6 +305,12 @@ class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):
on_change=on_change,
)
+ # Override _mime_ to return plotly HTML in non-JS environments
+ def _mime_(self) -> tuple[KnownMimeType, str]:
+ if is_no_js():
+ return ("text/html", self._figure._repr_html_())
+ return ("text/html", self.text)
+
@property
def ranges(self) -> dict[str, list[float]]:
"""Get the range selection of the plot.
diff --git a/pixi.lock b/pixi.lock
index 86d43a9282..ff53d9429f 100644
--- a/pixi.lock
+++ b/pixi.lock
@@ -119,7 +119,7 @@ environments:
- pypi: https://files.pythonhosted.org/packages/16/32/f8e3c85d1d5250232a5d3477a2a28cc291968ff175caeadaf3cc19ce0e4a/parso-0.8.5-py2.py3-none-any.whl
- pypi: https://files.pythonhosted.org/packages/29/f8/40e01c350ad9a2b3cb4e6adbcc8a83b17ee50dd5792102b6142385937db5/psutil-7.2.1-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl
- pypi: https://files.pythonhosted.org/packages/ea/10/47caf89cbb52e5bb764696fd52a8c591a2f0e851a93270c05a17f36000b5/pymdown_extensions-10.20-py3-none-any.whl
- - pypi: https://files.pythonhosted.org/packages/18/c4/09985a03dba389d4fe16a9014147a7b02fa76ef3519bf5846462a485876d/starlette-0.51.0-py3-none-any.whl
+ - pypi: https://files.pythonhosted.org/packages/81/0d/13d1d239a25cbfb19e740db83143e95c772a1fe10202dda4b76792b114dd/starlette-0.52.1-py3-none-any.whl
- pypi: https://files.pythonhosted.org/packages/3d/d8/2083a1daa7439a66f3a48589a57d576aa117726762618f6bb09fe3798796/uvicorn-0.40.0-py3-none-any.whl
- pypi: https://files.pythonhosted.org/packages/18/29/71729b4671f21e1eaa5d6573031ab810ad2936c8175f03f97f3ff164c802/websockets-16.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl
- pypi: ./
@@ -217,7 +217,7 @@ environments:
- pypi: https://files.pythonhosted.org/packages/16/32/f8e3c85d1d5250232a5d3477a2a28cc291968ff175caeadaf3cc19ce0e4a/parso-0.8.5-py2.py3-none-any.whl
- pypi: https://files.pythonhosted.org/packages/c5/2c/78e4a789306a92ade5000da4f5de3255202c534acdadc3aac7b5458fadef/psutil-7.2.1-cp36-abi3-macosx_11_0_arm64.whl
- pypi: https://files.pythonhosted.org/packages/ea/10/47caf89cbb52e5bb764696fd52a8c591a2f0e851a93270c05a17f36000b5/pymdown_extensions-10.20-py3-none-any.whl
- - pypi: https://files.pythonhosted.org/packages/18/c4/09985a03dba389d4fe16a9014147a7b02fa76ef3519bf5846462a485876d/starlette-0.51.0-py3-none-any.whl
+ - pypi: https://files.pythonhosted.org/packages/81/0d/13d1d239a25cbfb19e740db83143e95c772a1fe10202dda4b76792b114dd/starlette-0.52.1-py3-none-any.whl
- pypi: https://files.pythonhosted.org/packages/3d/d8/2083a1daa7439a66f3a48589a57d576aa117726762618f6bb09fe3798796/uvicorn-0.40.0-py3-none-any.whl
- pypi: https://files.pythonhosted.org/packages/40/1e/9771421ac2286eaab95b8575b0cb701ae3663abf8b5e1f64f1fd90d0a673/websockets-16.0-cp312-cp312-macosx_11_0_arm64.whl
- pypi: ./
@@ -1133,7 +1133,7 @@ packages:
- pypi: ./
name: marimo
version: 0.19.4
- sha256: d736d3a736c76f64d737bbf418312a9ff0d45d16b31382d2765becb16450d90f
+ sha256: 33d1fdf0428c4fa081a538af862209731fd8e27af5ac43041d232d6918ede2e4
requires_dist:
- click>=8.0,<9
- jedi>=0.18.0
@@ -1169,7 +1169,6 @@ packages:
- mcp>=1.0.0 ; extra == 'mcp'
- pydantic>2 ; extra == 'mcp'
requires_python: '>=3.10'
- editable: true
- pypi: https://files.pythonhosted.org/packages/70/81/54e3ce63502cd085a0c556652a4e1b919c45a446bd1e5300e10c44c8c521/markdown-3.10-py3-none-any.whl
name: markdown
version: '3.10'
@@ -1793,10 +1792,10 @@ packages:
- pkg:pypi/sniffio?source=compressed-mapping
size: 15698
timestamp: 1762941572482
-- pypi: https://files.pythonhosted.org/packages/18/c4/09985a03dba389d4fe16a9014147a7b02fa76ef3519bf5846462a485876d/starlette-0.51.0-py3-none-any.whl
+- pypi: https://files.pythonhosted.org/packages/81/0d/13d1d239a25cbfb19e740db83143e95c772a1fe10202dda4b76792b114dd/starlette-0.52.1-py3-none-any.whl
name: starlette
- version: 0.51.0
- sha256: fb460a3d6fd3c958d729fdd96aee297f89a51b0181f16401fe8fd4cb6129165d
+ version: 0.52.1
+ sha256: 0029d43eb3d273bc4f83a08720b4912ea4b071087a3b48db01b7c839f7954d74
requires_dist:
- anyio>=3.6.2,<5
- typing-extensions>=4.10.0 ; python_full_version < '3.13'
diff --git a/pyproject.toml b/pyproject.toml
index 854f3c1572..039a0b8295 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -154,6 +154,57 @@ test = [
"cffi>=1.16.0",
]
+test-optional = [
+ # For testing ADBC driver-based SQL connections
+ "adbc_driver_manager",
+ "adbc_driver_sqlite",
+ "python-lsp-server>=1.10.0",
+ # For testing mo.ui.chart, table, ...
+ "vl-convert-python",
+ "vegafusion",
+ "pyarrow>=19.0.1",
+ "pyarrow_hotfix",
+ "altair>=5.4.0",
+ "plotly>=5.14.0",
+ "polars>=1.32.2",
+ "sqlglot[rs]>=26.2.0",
+ "sqlalchemy>=2.0.40",
+ "pyiceberg>=0.9.0",
+ # For testing clickhouse
+ "chdb>=3; platform_system != 'Windows'", # there is no suitable wheel for windows
+ "clickhouse-connect>=0.8.18",
+ "redshift-connector[full]>=2.1.7",
+ "pandas>=1.5.3",
+ "hvplot~=0.11.3",
+ # Causes issues installing `shapely` (v2.0.7)
+ # "geopandas~=1.0.1",
+ "duckdb>=1.0.0",
+ "ibis-framework[duckdb]>=10.3.0",
+ # For testing mo.image
+ "pillow~=10.4.0",
+ "anywidget~=0.9.18",
+ "ipython~=8.12.3",
+ # testing gen ai
+ "pydantic-ai-slim[google,anthropic,bedrock,openai]>=1.39.0",
+ # - google-auth uses cachetools, and cachetools<5.0.0 uses collections.MutableMapping (removed in Python 3.10)
+ "cachetools>=5.0.0",
+ "boto3>=1.38.46",
+ # for bedrock ui chat
+ "litellm>=1.70.0",
+ # exporting as ipynb
+ "nbformat>=5.10.4",
+ "sympy>=1.13.3",
+ "jupytext>=1.17.2",
+ # For standard scientific computing/ ML
+ "jax>=0.4.0; python_version == '3.12'",
+ "torch>=2.4.0; python_version == '3.12'",
+ "scikit-bio>=0.6.3; python_version == '3.12'",
+ "mcp>=1.0.0",
+ # zeromq
+ "pyzmq>=27.1.0",
+]
+
+
[tool.hatch]
installer = "uv"
@@ -239,56 +290,7 @@ test-narwhals = """
[tool.hatch.envs.test-optional]
template = "test"
-dependency-groups = ["dev", "test"]
-extra-dependencies = [
- # For testing ADBC driver-based SQL connections
- "adbc_driver_manager",
- "adbc_driver_sqlite",
- "python-lsp-server>=1.10.0",
- # For testing mo.ui.chart, table, ...
- "vl-convert-python",
- "vegafusion",
- "pyarrow>=19.0.1",
- "pyarrow_hotfix",
- "altair>=5.4.0",
- "plotly>=5.14.0",
- "polars>=1.32.2",
- "sqlglot[rs]>=26.2.0",
- "sqlalchemy>=2.0.40",
- "pyiceberg>=0.9.0",
- # For testing clickhouse
- "chdb>=3; platform_system != 'Windows'", # there is no suitable wheel for windows
- "clickhouse-connect>=0.8.18",
- "redshift-connector[full]>=2.1.7",
- "pandas>=1.5.3",
- "hvplot~=0.11.3",
- # Causes issues installing `shapely` (v2.0.7)
- # "geopandas~=1.0.1",
- "duckdb>=1.0.0",
- "ibis-framework[duckdb]>=10.3.0",
- # For testing mo.image
- "pillow~=10.4.0",
- "anywidget~=0.9.18",
- "ipython~=8.12.3",
- # testing gen ai
- "pydantic-ai-slim[google,anthropic,bedrock,openai]>=1.39.0",
- # - google-auth uses cachetools, and cachetools<5.0.0 uses collections.MutableMapping (removed in Python 3.10)
- "cachetools>=5.0.0",
- "boto3>=1.38.46",
- # for bedrock ui chat
- "litellm>=1.70.0",
- # exporting as ipynb
- "nbformat>=5.10.4",
- "sympy>=1.13.3",
- "jupytext>=1.17.2",
- # For standard scientific computing/ ML
- "jax>=0.4.0; python_version == '3.12'",
- "torch>=2.4.0; python_version == '3.12'",
- "scikit-bio>=0.6.3; python_version == '3.12'",
- "mcp>=1.0.0",
- # zeromq
- "pyzmq>=27.1.0",
-]
+dependency-groups = ["dev", "test", "test-optional"]
[[tool.hatch.envs.test-optional.matrix]]
python = ["3.10", "3.11", "3.12", "3.13", "3.14"]
@@ -351,8 +353,7 @@ exclude = [
"tests/_ast/codegen_data",
"tests/_ast/test_app.py",
"tests/_cli/cli_data",
- "tests/_cli/fixtures",
- "tests/_convert/ipynb/fixtures",
+ "tests/**/fixtures",
"tests/_lint/test_files",
"tests/_runtime/runtime_data",
]
@@ -501,8 +502,6 @@ exclude = [
'tests/_ast/codegen_data',
'tests/_ast/cell_data',
'tests/_cli/cli_data',
- 'tests/_cli/fixtures',
- 'tests/_convert/ipynb/fixtures',
'tests/_runtime/runtime_data',
'marimo/_snippets/data/',
'marimo/_smoke_tests/',
diff --git a/tests/_cli/snapshots/ipynb.txt b/tests/_cli/snapshots/export/ipynb/ipynb.txt
similarity index 100%
rename from tests/_cli/snapshots/ipynb.txt
rename to tests/_cli/snapshots/export/ipynb/ipynb.txt
diff --git a/tests/_cli/snapshots/ipynb_topdown.txt b/tests/_cli/snapshots/export/ipynb/ipynb_topdown.txt
similarity index 100%
rename from tests/_cli/snapshots/ipynb_topdown.txt
rename to tests/_cli/snapshots/export/ipynb/ipynb_topdown.txt
diff --git a/tests/_cli/snapshots/ipynb_with_errors.txt b/tests/_cli/snapshots/export/ipynb/ipynb_with_errors.txt
similarity index 100%
rename from tests/_cli/snapshots/ipynb_with_errors.txt
rename to tests/_cli/snapshots/export/ipynb/ipynb_with_errors.txt
diff --git a/tests/_cli/snapshots/export/ipynb/ipynb_with_media_outputs.txt b/tests/_cli/snapshots/export/ipynb/ipynb_with_media_outputs.txt
new file mode 100644
index 0000000000..b1f7e1ddab
--- /dev/null
+++ b/tests/_cli/snapshots/export/ipynb/ipynb_with_media_outputs.txt
@@ -0,0 +1,279 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {
+ "marimo": {
+ "name": "cell_imports"
+ }
+ },
+ "outputs": [],
+ "source": [
+ "import marimo as mo\n",
+ "import matplotlib.pyplot as plt\n",
+ "import altair as alt\n",
+ "import plotly.graph_objs as go\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import pyarrow\n",
+ "\n",
+ "np.random.seed(5)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "MJUe",
+ "metadata": {
+ "marimo": {
+ "name": "pure_markdown_cell"
+ }
+ },
+ "source": [
+ "pure markdown cell"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "vblA",
+ "metadata": {
+ "marimo": {
+ "name": "ends_with_markdown"
+ }
+ },
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "ends with markdown"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "_x = 10\n",
+ "mo.md(\"ends with markdown\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bkHC",
+ "metadata": {
+ "marimo": {
+ "name": "cell_slider"
+ }
+ },
+ "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": [
+ "slider = mo.ui.slider(0, 10)\n",
+ "slider"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "lEQa",
+ "metadata": {
+ "marimo": {
+ "name": "cell_matplotlib"
+ }
+ },
+ "outputs": [
+ {
+ "data": {
+ "image/png": "IMAGE_BASE64_DATA"
+ },
+ "metadata": {
+ "image/png": {
+ "height": 413,
+ "width": 568
+ }
+ },
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "# Matplotlib plot\n",
+ "x = np.linspace(0, 2 * np.pi, 100)\n",
+ "y = np.sin(x)\n",
+ "fig, ax = plt.subplots()\n",
+ "mpplot = ax.plot(x, y)\n",
+ "fig"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "PKri",
+ "metadata": {
+ "marimo": {
+ "name": "basic_dataframe"
+ }
+ },
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<table border=\"1\" class=\"dataframe\"><thead><tr style=\"text-align: right;\"><th></th><th>x</th></tr></thead><tbody><tr><th>0</th><td>1</td></tr></tbody></table>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "df = pd.DataFrame({\"x\": [1]})\n",
+ "df"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Xref",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "image/png": "IMAGE_BASE64_DATA"
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "# Interactive figure\n",
+ "mo.mpl.interactive(fig)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "SFPL",
+ "metadata": {
+ "marimo": {
+ "name": "cell_altair"
+ }
+ },
+ "outputs": [
+ {
+ "data": {
+ "application/vnd.vegalite.v5+json": "{\n \"$schema\": \"https://vega.github.io/schema/vega-lite/v6.1.0.json\",\n \"config\": {\n \"view\": {\n \"continuousHeight\": 300,\n \"continuousWidth\": 300\n }\n },\n \"data\": {\n \"name\": \"data-a202e5dd04552c98b78a4bc5fc59f367\"\n },\n \"datasets\": {\n \"data-a202e5dd04552c98b78a4bc5fc59f367\": [\n {\n \"x\": 1,\n \"y\": 1\n }\n ]\n },\n \"encoding\": {\n \"x\": {\n \"field\": \"x\",\n \"type\": \"ordinal\"\n },\n \"y\": {\n \"field\": \"y\",\n \"type\": \"quantitative\"\n }\n },\n \"mark\": {\n \"type\": \"circle\"\n },\n \"usermeta\": {\n \"embedOptions\": {}\n },\n \"width\": \"container\"\n}"
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "# Altair chart\n",
+ "_df = pd.DataFrame({\"x\": [1], \"y\": [1]})\n",
+ "chart = alt.Chart(_df).mark_circle().encode(x=\"x:O\", y=\"y:Q\")\n",
+ "chart"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "BYtC",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "application/vnd.vega.v5+json": "{\n \"$schema\": \"https://vega.github.io/schema/vega-lite/v6.1.0.json\",\n \"config\": {\n \"view\": {\n \"continuousHeight\": 300,\n \"continuousWidth\": 300\n }\n },\n \"data\": {\n \"name\": \"data-a202e5dd04552c98b78a4bc5fc59f367\"\n },\n \"datasets\": {\n \"data-a202e5dd04552c98b78a4bc5fc59f367\": [\n {\n \"x\": 1,\n \"y\": 1\n }\n ]\n },\n \"encoding\": {\n \"x\": {\n \"field\": \"x\",\n \"type\": \"ordinal\"\n },\n \"y\": {\n \"field\": \"y\",\n \"type\": \"quantitative\"\n }\n },\n \"mark\": {\n \"type\": \"circle\"\n },\n \"usermeta\": {\n \"embedOptions\": {}\n }\n}"
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "# Wrapped in mo.ui.altair_chart()\n",
+ "mo.ui.altair_chart(chart)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "RGSE",
+ "metadata": {
+ "marimo": {
+ "name": "cell_plotly"
+ }
+ },
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<marimo-plotly>REDACTED</marimo-plotly>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "# Plotly chart\n",
+ "trace = go.Scatter(x=np.arange(2), y=np.random.randn(2), mode=\"lines+markers\")\n",
+ "plot = go.Figure(data=[trace])\n",
+ "plot"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Kclp",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<div> <script type=\"text/javascript\">window.PlotlyConfig = {MathJaxConfig: 'local'};</script>\n",
+ " <script charset=\"utf-8\" src=\"https://cdn.plot.ly/plotly-VERSION.min.js\" integrity=\"INTEGRITY_HASH\" crossorigin=\"anonymous\"></script> <div id=\"PLOTLY_DIV_ID\" class=\"plotly-graph-div\" style=\"height:100%; width:100%;\"></div> <script type=\"text/javascript\"> window.PLOTLYENV=window.PLOTLYENV || {}; if (document.getElementById(\"PLOTLY_DIV_ID\")) { Plotly.newPlot(\"PLOTLY_DIV_ID\", [{\"mode\":\"lines+markers\",\"x\":{\"dtype\":\"i1\",\"bdata\":\"PLOTLY_BINARY_DATA\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"FB+RNhI93D\\u002fi42YA+izVvw==\"},\"type\":\"scatter\"}], {\"template\":{\"data\":{\"histogram2dcontour\":[{\"type\":\"histogram2dcontour\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]}],\"choropleth\":[{\"type\":\"choropleth\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}],\"histogram2d\":[{\"type\":\"histogram2d\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]}],\"heatmap\":[{\"type\":\"heatmap\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]}],\"contourcarpet\":[{\"type\":\"contourcarpet\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}],\"contour\":[{\"type\":\"contour\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]}],\"surface\":[{\"type\":\"surface\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]}],\"mesh3d\":[{\"type\":\"mesh3d\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}],\"scatter\":[{\"fillpattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2},\"type\":\"scatter\"}],\"parcoords\":[{\"type\":\"parcoords\",\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scatterpolargl\":[{\"type\":\"scatterpolargl\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"bar\":[{\"error_x\":{\"color\":\"#2a3f5f\"},\"error_y\":{\"color\":\"#2a3f5f\"},\"marker\":{\"line\":{\"color\":\"#E5ECF6\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"bar\"}],\"scattergeo\":[{\"type\":\"scattergeo\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scatterpolar\":[{\"type\":\"scatterpolar\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"histogram\":[{\"marker\":{\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"histogram\"}],\"scattergl\":[{\"type\":\"scattergl\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scatter3d\":[{\"type\":\"scatter3d\",\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scattermap\":[{\"type\":\"scattermap\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scattermapbox\":[{\"type\":\"scattermapbox\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scatterternary\":[{\"type\":\"scatterternary\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scattercarpet\":[{\"type\":\"scattercarpet\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"carpet\":[{\"aaxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"white\",\"linecolor\":\"white\",\"minorgridcolor\":\"white\",\"startlinecolor\":\"#2a3f5f\"},\"baxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"white\",\"linecolor\":\"white\",\"minorgridcolor\":\"white\",\"startlinecolor\":\"#2a3f5f\"},\"type\":\"carpet\"}],\"table\":[{\"cells\":{\"fill\":{\"color\":\"#EBF0F8\"},\"line\":{\"color\":\"white\"}},\"header\":{\"fill\":{\"color\":\"#C8D4E3\"},\"line\":{\"color\":\"white\"}},\"type\":\"table\"}],\"barpolar\":[{\"marker\":{\"line\":{\"color\":\"#E5ECF6\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"barpolar\"}],\"pie\":[{\"automargin\":true,\"type\":\"pie\"}]},\"layout\":{\"autotypenumbers\":\"strict\",\"colorway\":[\"#636efa\",\"#EF553B\",\"#00cc96\",\"#ab63fa\",\"#FFA15A\",\"#19d3f3\",\"#FF6692\",\"#B6E880\",\"#FF97FF\",\"#FECB52\"],\"font\":{\"color\":\"#2a3f5f\"},\"hovermode\":\"closest\",\"hoverlabel\":{\"align\":\"left\"},\"paper_bgcolor\":\"white\",\"plot_bgcolor\":\"#E5ECF6\",\"polar\":{\"bgcolor\":\"#E5ECF6\",\"angularaxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\"},\"radialaxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\"}},\"ternary\":{\"bgcolor\":\"#E5ECF6\",\"aaxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\"},\"baxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\"},\"caxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\"}},\"coloraxis\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"colorscale\":{\"sequential\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"sequentialminus\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"diverging\":[[0,\"#8e0152\"],[0.1,\"#c51b7d\"],[0.2,\"#de77ae\"],[0.3,\"#f1b6da\"],[0.4,\"#fde0ef\"],[0.5,\"#f7f7f7\"],[0.6,\"#e6f5d0\"],[0.7,\"#b8e186\"],[0.8,\"#7fbc41\"],[0.9,\"#4d9221\"],[1,\"#276419\"]]},\"xaxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"white\",\"automargin\":true,\"zerolinewidth\":2},\"yaxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"white\",\"automargin\":true,\"zerolinewidth\":2},\"scene\":{\"xaxis\":{\"backgroundcolor\":\"#E5ECF6\",\"gridcolor\":\"white\",\"linecolor\":\"white\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"white\",\"gridwidth\":2},\"yaxis\":{\"backgroundcolor\":\"#E5ECF6\",\"gridcolor\":\"white\",\"linecolor\":\"white\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"white\",\"gridwidth\":2},\"zaxis\":{\"backgroundcolor\":\"#E5ECF6\",\"gridcolor\":\"white\",\"linecolor\":\"white\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"white\",\"gridwidth\":2}},\"shapedefaults\":{\"line\":{\"color\":\"#2a3f5f\"}},\"annotationdefaults\":{\"arrowcolor\":\"#2a3f5f\",\"arrowhead\":0,\"arrowwidth\":1},\"geo\":{\"bgcolor\":\"white\",\"landcolor\":\"#E5ECF6\",\"subunitcolor\":\"white\",\"showland\":true,\"showlakes\":true,\"lakecolor\":\"white\"},\"title\":{\"x\":0.05},\"mapbox\":{\"style\":\"light\"}}},\"dragmode\":\"zoom\"}, {\"responsive\": true} ) }; </script> </div>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "# Wrapped in mo.ui.plotly\n",
+ "mo.ui.plotly(plot)"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3"
+ },
+ "marimo": {
+ "app_config": {
+ "width": "medium"
+ },
+ "header": "# /// script\n# requires-python = \">=3.13\"\n# dependencies = [\n# \"altair==6.0.0\",\n# \"marimo\",\n# \"matplotlib==3.10.8\",\n# \"numpy==2.4.1\",\n# \"pandas==2.3.3\",\n# \"plotly==6.5.2\",\n# \"pyarrow==22.0.0\",\n# ]\n# ///\n\n",
+ "marimo_version": "0.0.0"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_cli/snapshots/ipynb_with_outputs.txt b/tests/_cli/snapshots/export/ipynb/ipynb_with_outputs.txt
similarity index 100%
rename from tests/_cli/snapshots/ipynb_with_outputs.txt
rename to tests/_cli/snapshots/export/ipynb/ipynb_with_outputs.txt
diff --git a/tests/_cli/snapshots/async.txt b/tests/_cli/snapshots/export/md/async.txt
similarity index 100%
rename from tests/_cli/snapshots/async.txt
rename to tests/_cli/snapshots/export/md/async.txt
diff --git a/tests/_cli/snapshots/broken.txt b/tests/_cli/snapshots/export/md/broken.txt
similarity index 100%
rename from tests/_cli/snapshots/broken.txt
rename to tests/_cli/snapshots/export/md/broken.txt
diff --git a/tests/_cli/snapshots/export_markdown_with_errors.txt b/tests/_cli/snapshots/export/md/export_markdown_with_errors.txt
similarity index 100%
rename from tests/_cli/snapshots/export_markdown_with_errors.txt
rename to tests/_cli/snapshots/export/md/export_markdown_with_errors.txt
diff --git a/tests/_cli/snapshots/markdown.txt b/tests/_cli/snapshots/export/md/markdown.txt
similarity index 100%
rename from tests/_cli/snapshots/markdown.txt
rename to tests/_cli/snapshots/export/md/markdown.txt
diff --git a/tests/_cli/snapshots/script.txt b/tests/_cli/snapshots/export/script/script.txt
similarity index 100%
rename from tests/_cli/snapshots/script.txt
rename to tests/_cli/snapshots/export/script/script.txt
diff --git a/tests/_cli/snapshots/script_with_errors.txt b/tests/_cli/snapshots/export/script/script_with_errors.txt
similarity index 100%
rename from tests/_cli/snapshots/script_with_errors.txt
rename to tests/_cli/snapshots/export/script/script_with_errors.txt
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index d7c6347c8c..889cd31f48 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -18,7 +18,13 @@ 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 delete_lines_with_files, snapshotter
+from tests.mocks import (
+ _sanitize_version,
+ delete_lines_with_files,
+ simplify_images,
+ simplify_plotly,
+ snapshotter,
+)
if TYPE_CHECKING:
import pathlib
@@ -31,56 +37,66 @@ def _is_win32() -> bool:
return sys.platform == "win32"
+def _run_export(
+ export_format: str,
+ file: str,
+ *extra_args: str,
+ capture_output: bool = True,
+ input_data: bytes | None = None,
+) -> subprocess.CompletedProcess[bytes]:
+ """Helper to run marimo export commands."""
+ cmd = ["marimo", "export", export_format, file, *extra_args]
+ return subprocess.run(cmd, capture_output=capture_output, input=input_data)
+
+
+def _assert_success(p: subprocess.CompletedProcess[bytes]) -> None:
+ assert p.returncode == 0, p.stderr.decode()
+
+
+def _assert_failure(p: subprocess.CompletedProcess[bytes]) -> None:
+ assert p.returncode != 0, p.stderr.decode()
+
+
+def _get_snapshot_path(export_format: str, name: str) -> str:
+ """Get snapshot path following the pattern export/<format>/<name>.txt"""
+ return f"export/{export_format}/{name}.txt"
+
+
+def _normalize_html_path(html: str, temp_file: str) -> str:
+ """Normalize HTML by removing the temporary file's directory path."""
+ dirname = path.dirname(temp_file)
+ return html.replace(dirname, "path")
+
+
class TestExportHTML:
@staticmethod
def test_cli_export_html(temp_marimo_file: str) -> None:
- p = subprocess.run(
- ["marimo", "export", "html", temp_marimo_file],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
+ p = _run_export("html", temp_marimo_file)
+ _assert_success(p)
html = normalize_index_html(p.stdout.decode())
- # Remove folder path
- dirname = path.dirname(temp_marimo_file)
- html = html.replace(dirname, "path")
+ html = _normalize_html_path(html, temp_marimo_file)
assert '<marimo-code hidden=""></marimo-code>' not in html
@staticmethod
def test_cli_export_html_no_code(temp_marimo_file: str) -> None:
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html",
- temp_marimo_file,
- "--no-include-code",
- ],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
+ p = _run_export("html", temp_marimo_file, "--no-include-code")
+ _assert_success(p)
html = normalize_index_html(p.stdout.decode())
- # Remove folder path
- dirname = path.dirname(temp_marimo_file)
- html = html.replace(dirname, "path")
+ html = _normalize_html_path(html, temp_marimo_file)
assert '<marimo-code hidden=""></marimo-code>' in html
@staticmethod
def test_cli_export_html_wasm(temp_marimo_file: str) -> None:
out_dir = Path(temp_marimo_file).parent / "out"
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html-wasm",
- temp_marimo_file,
- "--mode",
- "edit",
- "--output",
- out_dir,
- ],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
+ p = _run_export(
+ "html-wasm",
+ temp_marimo_file,
+ "--mode",
+ "edit",
+ "--output",
+ str(out_dir),
+ )
+ _assert_success(p)
html = Path(out_dir / "index.html").read_text()
assert '"mode": "edit"' in html
assert '<marimo-code hidden=""></marimo-code>' not in html
@@ -96,35 +112,19 @@ class TestExportHTML:
(public_dir / "test.txt").write_text("test content")
out_dir = Path(temp_marimo_file).parent / "out"
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html-wasm",
- temp_marimo_file,
- "--output",
- out_dir,
- ],
- capture_output=True,
+ p = _run_export(
+ "html-wasm", temp_marimo_file, "--output", str(out_dir)
)
- assert p.returncode == 0, p.stderr.decode()
+ _assert_success(p)
# Verify public folder was copied
assert (out_dir / "public" / "test.txt").exists()
assert (out_dir / "public" / "test.txt").read_text() == "test content"
# Try exporting to the same directory that contains the public folder
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html-wasm",
- temp_marimo_file,
- "--output",
- public_dir.parent,
- ],
- capture_output=True,
+ p = _run_export(
+ "html-wasm", temp_marimo_file, "--output", str(public_dir.parent)
)
- assert p.returncode == 0, p.stderr.decode()
+ _assert_success(p)
# Clean up
shutil.rmtree(public_dir)
@@ -132,19 +132,14 @@ class TestExportHTML:
@staticmethod
def test_cli_export_html_wasm_cloudflare(temp_marimo_file: str) -> None:
out_dir = Path(temp_marimo_file).parent / "cloudflare" / "out"
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html-wasm",
- temp_marimo_file,
- "--output",
- out_dir,
- "--include-cloudflare",
- ],
- capture_output=True,
+ p = _run_export(
+ "html-wasm",
+ temp_marimo_file,
+ "--output",
+ str(out_dir),
+ "--include-cloudflare",
)
- assert p.returncode == 0, p.stderr.decode()
+ _assert_success(p)
# Verify Cloudflare files were created
assert (out_dir.parent / "index.js").exists()
@@ -164,18 +159,9 @@ class TestExportHTML:
temp_marimo_file: str,
) -> None:
out_dir = Path(temp_marimo_file).parent / "out_file"
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html-wasm",
- temp_marimo_file,
- "--output",
- str(out_dir / "foo.html"),
- ],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
+ output_path = str(out_dir / "foo.html")
+ p = _run_export("html-wasm", temp_marimo_file, "--output", output_path)
+ _assert_success(p)
assert Path(out_dir / "foo.html").exists()
assert not Path(out_dir / "index.html").exists()
html = Path(out_dir / "foo.html").read_text()
@@ -184,20 +170,15 @@ class TestExportHTML:
@staticmethod
def test_cli_export_html_wasm_read(temp_marimo_file: str) -> None:
out_dir = Path(temp_marimo_file).parent / "out"
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html-wasm",
- temp_marimo_file,
- "--mode",
- "run",
- "--output",
- out_dir,
- ],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
+ p = _run_export(
+ "html-wasm",
+ temp_marimo_file,
+ "--mode",
+ "run",
+ "--output",
+ str(out_dir),
+ )
+ _assert_success(p)
html = Path(out_dir / "index.html").read_text()
assert '"mode": "read"' in html
assert '<marimo-code hidden=""></marimo-code>' not in html
@@ -252,28 +233,21 @@ class TestExportHTML:
@staticmethod
def test_cli_export_async(temp_async_marimo_file: str) -> None:
- p = subprocess.run(
- ["marimo", "export", "html", temp_async_marimo_file],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
- assert "ValueError" not in p.stderr.decode()
- assert "Traceback" not in p.stderr.decode()
+ p = _run_export("html", temp_async_marimo_file)
+ _assert_success(p)
+ stderr = p.stderr.decode()
+ assert "ValueError" not in stderr
+ assert "Traceback" not in stderr
html = normalize_index_html(p.stdout.decode())
- # Remove folder path
- dirname = path.dirname(temp_async_marimo_file)
- html = html.replace(dirname, "path")
+ html = _normalize_html_path(html, temp_async_marimo_file)
assert '<marimo-code hidden=""></marimo-code>' not in html
@staticmethod
def test_export_html_with_errors(
temp_marimo_file_with_errors: str,
) -> None:
- p = subprocess.run(
- ["marimo", "export", "html", temp_marimo_file_with_errors],
- capture_output=True,
- )
- assert p.returncode != 0, p.stderr.decode()
+ p = _run_export("html", temp_marimo_file_with_errors)
+ _assert_failure(p)
html = normalize_index_html(p.stdout.decode())
# Errors but still produces HTML
assert " division by zero" in p.stderr.decode()
@@ -283,16 +257,8 @@ class TestExportHTML:
def test_export_html_with_multiple_definitions(
temp_marimo_file_with_multiple_definitions: str,
) -> None:
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html",
- temp_marimo_file_with_multiple_definitions,
- ],
- capture_output=True,
- )
- assert p.returncode != 0, p.stderr.decode()
+ p = _run_export("html", temp_marimo_file_with_multiple_definitions)
+ _assert_failure(p)
# Errors but still produces HTML
assert "MultipleDefinitionError" in p.stderr.decode()
assert "<marimo-code" in p.stdout.decode()
@@ -370,40 +336,20 @@ class TestExportHTML:
@staticmethod
@pytest.mark.skipif(not HAS_UV, reason="uv is required for sandbox tests")
def test_cli_export_html_sandbox(temp_marimo_file: str) -> None:
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html",
- temp_marimo_file,
- "--sandbox",
- ],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
+ p = _run_export("html", temp_marimo_file, "--sandbox")
+ _assert_success(p)
output = p.stderr.decode()
# Check for sandbox message
assert "Running in a sandbox" in output
assert "run --isolated" in output
html = normalize_index_html(output)
- # Remove folder path
- dirname = path.dirname(temp_marimo_file)
- html = html.replace(dirname, "path")
+ html = _normalize_html_path(html, temp_marimo_file)
assert '<marimo-code hidden=""></marimo-code>' not in html
@staticmethod
def test_cli_export_html_sandbox_no_prompt(temp_marimo_file: str) -> None:
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html",
- temp_marimo_file,
- "--no-sandbox",
- ],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
+ p = _run_export("html", temp_marimo_file, "--no-sandbox")
+ _assert_success(p)
@staticmethod
def test_cli_export_html_force_overwrite(temp_marimo_file: str) -> None:
@@ -411,53 +357,29 @@ class TestExportHTML:
Test that the --force/-f flag allows overwriting an existing file
using a simple, error-free notebook.
"""
-
- p1 = subprocess.run(
- ["marimo", "export", "html", temp_marimo_file],
- capture_output=True,
- )
- assert p1.returncode == 0, p1.stderr.decode()
+ p1 = _run_export("html", temp_marimo_file)
+ _assert_success(p1)
html = normalize_index_html(p1.stdout.decode())
-
- dirname = path.dirname(temp_marimo_file)
- html = html.replace(dirname, "path")
+ html = _normalize_html_path(html, temp_marimo_file)
assert '<marimo-code hidden=""></marimo-code>' not in html
output_path = Path(temp_marimo_file).parent / "output.html"
- p2 = subprocess.run(
- [
- "marimo",
- "export",
- "html",
- temp_marimo_file,
- "-o",
- str(output_path),
- ],
- capture_output=True,
- input=b"n\n",
+ p2 = _run_export(
+ "html", temp_marimo_file, "-o", str(output_path), input_data=b"n\n"
)
assert p2.returncode == 0, "Expected a graceful exit with no errors"
- p3 = subprocess.run(
- [
- "marimo",
- "export",
- "html",
- temp_marimo_file,
- "-o",
- str(output_path),
- "--force",
- ],
- capture_output=True,
+ p3 = _run_export(
+ "html", temp_marimo_file, "-o", str(output_path), "--force"
)
- assert p3.returncode == 0, p3.stderr.decode()
+ _assert_success(p3)
class TestExportHtmlSmokeTests:
- def assert_not_errored(
+ def _assert_no_traceback(
self, p: subprocess.CompletedProcess[bytes]
) -> None:
- assert p.returncode == 0, p.stderr.decode()
+ """Assert no traceback in stdout or stderr."""
assert not any(
line.startswith("Traceback")
for line in p.stderr.decode().splitlines()
@@ -467,126 +389,86 @@ class TestExportHtmlSmokeTests:
for line in p.stdout.decode().splitlines()
)
- def assert_has_errors(self, p: subprocess.CompletedProcess[bytes]) -> None:
- assert p.returncode != 0, p.stderr.decode()
+ def _assert_not_errored(
+ self, p: subprocess.CompletedProcess[bytes]
+ ) -> None:
+ _assert_success(p)
+ self._assert_no_traceback(p)
+
+ def _assert_has_errors(
+ self, p: subprocess.CompletedProcess[bytes]
+ ) -> None:
+ _assert_failure(p)
assert any(
"Export was successful, but some cells failed to execute" in line
for line in p.stderr.decode().splitlines()
), p.stderr.decode()
- assert not any(
- line.startswith("Traceback")
- for line in p.stdout.decode().splitlines()
- ), p.stdout.decode()
-
- def test_export_intro_tutorial(self, tmp_path: pathlib.Path) -> None:
- from marimo._tutorials import intro
-
- file = tmp_path / "intro.py"
+ self._assert_no_traceback(p)
+
+ def _export_tutorial(
+ self,
+ tmp_path: pathlib.Path,
+ module_import: str,
+ filename: str = "mod.py",
+ extra_args: tuple[str, ...] = (),
+ ) -> subprocess.CompletedProcess[bytes]:
+ """Helper to export a tutorial module to HTML."""
+ module = __import__(
+ f"marimo._tutorials.{module_import}",
+ fromlist=[module_import],
+ )
+ file = tmp_path / filename
out = tmp_path / "out.html"
- file.write_text(inspect.getsource(intro), encoding="utf-8")
- p = subprocess.run(
- ["marimo", "export", "html", str(file), "-o", str(out)],
- capture_output=True,
- )
+ file.write_text(inspect.getsource(module), encoding="utf-8")
+ p = _run_export("html", str(file), "-o", str(out), *extra_args)
assert Path(out).exists()
- self.assert_not_errored(p)
+ return p
- def test_export_ui_tutorial(self, tmp_path: pathlib.Path) -> None:
- from marimo._tutorials import ui as mod
+ def test_export_intro_tutorial(self, tmp_path: pathlib.Path) -> None:
+ p = self._export_tutorial(tmp_path, "intro", "intro.py")
+ self._assert_not_errored(p)
- file = tmp_path / "mod.py"
- file.write_text(inspect.getsource(mod), encoding="utf-8")
- out = tmp_path / "out.html"
- p = subprocess.run(
- ["marimo", "export", "html", str(file), "-o", str(out)],
- capture_output=True,
- )
- assert Path(out).exists()
- self.assert_not_errored(p)
+ def test_export_ui_tutorial(self, tmp_path: pathlib.Path) -> None:
+ p = self._export_tutorial(tmp_path, "ui")
+ self._assert_not_errored(p)
def test_export_dataflow_tutorial(self, tmp_path: pathlib.Path) -> None:
- from marimo._tutorials import dataflow as mod
-
- file = tmp_path / "mod.py"
- file.write_text(inspect.getsource(mod), encoding="utf-8")
- out = tmp_path / "out.html"
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html",
- str(file),
- "-o",
- str(out),
- "--no-sandbox",
- ],
- capture_output=True,
+ p = self._export_tutorial(
+ tmp_path, "dataflow", extra_args=("--no-sandbox",)
)
- self.assert_has_errors(p)
+ self._assert_has_errors(p)
def test_export_layout_tutorial(self, tmp_path: pathlib.Path) -> None:
- from marimo._tutorials import layout as mod
-
- file = tmp_path / "mod.py"
- file.write_text(inspect.getsource(mod), encoding="utf-8")
- out = tmp_path / "out.html"
- p = subprocess.run(
- ["marimo", "export", "html", str(file), "-o", str(out)],
- capture_output=True,
- )
- assert Path(out).exists()
- self.assert_not_errored(p)
+ p = self._export_tutorial(tmp_path, "layout")
+ self._assert_not_errored(p)
@pytest.mark.skipif(
condition=not DependencyManager.matplotlib.has(),
reason="matplotlib is not installed",
)
def test_export_plots_tutorial(self, tmp_path: pathlib.Path) -> None:
- from marimo._tutorials import plots as mod
-
- file = tmp_path / "plots.py"
- file.write_text(inspect.getsource(mod), encoding="utf-8")
- out = tmp_path / "out.html"
- p = subprocess.run(
- ["marimo", "export", "html", str(file), "-o", str(out)],
- capture_output=True,
+ p = self._export_tutorial(
+ tmp_path, "plots", "plots.py", extra_args=("--no-sandbox",)
)
- assert Path(out).exists()
- self.assert_not_errored(p)
+ self._assert_not_errored(p)
def test_export_marimo_for_jupyter_users(
self, tmp_path: pathlib.Path
) -> None:
- from marimo._tutorials import for_jupyter_users as mod
-
- file = tmp_path / "mod.py"
- file.write_text(inspect.getsource(mod), encoding="utf-8")
- out = tmp_path / "out.html"
- p = subprocess.run(
- ["marimo", "export", "html", str(file), "-o", str(out)],
- capture_output=True,
- )
- assert Path(out).exists()
- self.assert_has_errors(p)
+ p = self._export_tutorial(tmp_path, "for_jupyter_users")
+ self._assert_has_errors(p)
class TestExportScript:
@staticmethod
def test_export_script(temp_marimo_file: str) -> None:
- p = subprocess.run(
- ["marimo", "export", "script", temp_marimo_file],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
- output = p.stdout.decode()
- snapshot("script.txt", output)
+ p = _run_export("script", temp_marimo_file)
+ _assert_success(p)
+ snapshot(_get_snapshot_path("script", "script"), p.stdout.decode())
@staticmethod
def test_export_script_async(temp_async_marimo_file: str) -> None:
- p = subprocess.run(
- ["marimo", "export", "script", temp_async_marimo_file],
- capture_output=True,
- )
+ p = _run_export("script", temp_async_marimo_file)
assert p.returncode == 2, p.stderr.decode()
assert (
"Cannot export a notebook with async code to a flat script"
@@ -597,18 +479,8 @@ class TestExportScript:
def test_export_script_with_multiple_definitions(
temp_marimo_file_with_multiple_definitions: str,
) -> None:
- p = subprocess.run(
- [
- "marimo",
- "export",
- "script",
- temp_marimo_file_with_multiple_definitions,
- ],
- capture_output=True,
- )
- assert p.returncode != 0, (
- "Expected non-zero return code due to multiple definitions"
- )
+ p = _run_export("script", temp_marimo_file_with_multiple_definitions)
+ _assert_failure(p)
error_message = p.stderr.decode()
assert (
"MultipleDefinitionError: This app can't be run because it has multiple definitions of the name x"
@@ -619,13 +491,12 @@ class TestExportScript:
def test_export_script_with_errors(
temp_marimo_file_with_errors: str,
) -> None:
- p = subprocess.run(
- ["marimo", "export", "script", temp_marimo_file_with_errors],
- capture_output=True,
+ p = _run_export("script", temp_marimo_file_with_errors)
+ _assert_success(p)
+ snapshot(
+ _get_snapshot_path("script", "script_with_errors"),
+ p.stdout.decode(),
)
- assert p.returncode == 0, p.stderr.decode()
- output = p.stdout.decode()
- snapshot("script_with_errors.txt", output)
@pytest.mark.skipif(
condition=DependencyManager.watchdog.has() or _is_win32(),
@@ -705,45 +576,32 @@ class TestExportScript:
class TestExportMarkdown:
@staticmethod
def test_export_markdown(temp_marimo_file: str) -> None:
- p = subprocess.run(
- ["marimo", "export", "md", temp_marimo_file],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
- output = p.stdout.decode()
- snapshot("markdown.txt", output)
+ p = _run_export("md", temp_marimo_file)
+ _assert_success(p)
+ snapshot(_get_snapshot_path("md", "markdown"), p.stdout.decode())
@staticmethod
def test_export_markdown_async(temp_async_marimo_file: str) -> None:
- p = subprocess.run(
- ["marimo", "export", "md", temp_async_marimo_file],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
- output = p.stdout.decode()
- snapshot("async.txt", output)
+ p = _run_export("md", temp_async_marimo_file)
+ _assert_success(p)
+ snapshot(_get_snapshot_path("md", "async"), p.stdout.decode())
@staticmethod
def test_export_markdown_broken(temp_unparsable_marimo_file: str) -> None:
- p = subprocess.run(
- ["marimo", "export", "md", temp_unparsable_marimo_file],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
- output = p.stdout.decode()
- snapshot("broken.txt", output)
+ p = _run_export("md", temp_unparsable_marimo_file)
+ _assert_success(p)
+ snapshot(_get_snapshot_path("md", "broken"), p.stdout.decode())
@staticmethod
def test_export_markdown_with_errors(
temp_marimo_file_with_errors: str,
) -> None:
- p = subprocess.run(
- ["marimo", "export", "md", temp_marimo_file_with_errors],
- capture_output=True,
+ p = _run_export("md", temp_marimo_file_with_errors)
+ _assert_success(p)
+ snapshot(
+ _get_snapshot_path("md", "export_markdown_with_errors"),
+ p.stdout.decode(),
)
- assert p.returncode == 0, p.stderr.decode()
- output = p.stdout.decode()
- snapshot("export_markdown_with_errors.txt", output)
@pytest.mark.skipif(
condition=DependencyManager.watchdog.has() or _is_win32(),
@@ -826,14 +684,10 @@ class TestExportIpynb:
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],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
- output = p.stdout.decode()
+ p = _run_export("ipynb", temp_marimo_file_with_md)
+ _assert_success(p)
# ipynb has non-deterministic ids
- snapshot("ipynb.txt", output)
+ snapshot(_get_snapshot_path("ipynb", "ipynb"), p.stdout.decode())
@pytest.mark.skipif(
not DependencyManager.nbformat.has(),
@@ -843,28 +697,17 @@ class TestExportIpynb:
self, temp_marimo_file_with_md: str
) -> None:
# Test topological sort (default)
- p = subprocess.run(
- ["marimo", "export", "ipynb", temp_marimo_file_with_md],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
+ p = _run_export("ipynb", temp_marimo_file_with_md)
+ _assert_success(p)
topo_output = p.stdout.decode()
# Test top-down sort
- p = subprocess.run(
- [
- "marimo",
- "export",
- "ipynb",
- temp_marimo_file_with_md,
- "--sort",
- "top-down",
- ],
- capture_output=True,
+ p = _run_export(
+ "ipynb", temp_marimo_file_with_md, "--sort", "top-down"
)
- assert p.returncode == 0, p.stderr.decode()
+ _assert_success(p)
topdown_output = p.stdout.decode()
- snapshot("ipynb_topdown.txt", topdown_output)
+ snapshot(_get_snapshot_path("ipynb", "ipynb_topdown"), topdown_output)
# Outputs should be different since sorting is different
assert topo_output != topdown_output
@@ -877,31 +720,45 @@ class TestExportIpynb:
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()
+ p = _run_export("ipynb", temp_marimo_file_with_md)
+ _assert_success(p)
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()
+ p = _run_export("ipynb", temp_marimo_file_with_md, "--include-outputs")
+ _assert_success(p)
with_outputs = p.stdout.decode()
- snapshot("ipynb_with_outputs.txt", with_outputs)
+ snapshot(
+ _get_snapshot_path("ipynb", "ipynb_with_outputs"), with_outputs
+ )
# Outputs should be different since one includes execution results
assert no_outputs != with_outputs
+ @pytest.mark.skipif(
+ not DependencyManager.nbformat.has(),
+ reason="This test requires nbformat.",
+ )
+ def test_export_ipynb_with_media_outputs(
+ self, temp_marimo_file_with_media: str
+ ) -> None:
+ # Test with outputs
+ p = _run_export(
+ "ipynb",
+ temp_marimo_file_with_media,
+ "--include-outputs",
+ "--no-sandbox",
+ )
+ _assert_success(p)
+ with_outputs = p.stdout.decode()
+ with_outputs = simplify_images(with_outputs)
+ with_outputs = simplify_plotly(with_outputs)
+ with_outputs = _sanitize_version(with_outputs)
+ snapshot(
+ _get_snapshot_path("ipynb", "ipynb_with_media_outputs"),
+ with_outputs.strip(),
+ )
+
@pytest.mark.skipif(
not DependencyManager.nbformat.has(),
reason="This test requires nbformat.",
@@ -909,17 +766,12 @@ class TestExportIpynb:
def test_export_ipynb_with_multiple_definitions(
self, temp_marimo_file_with_multiple_definitions: str
) -> None:
- p = subprocess.run(
- [
- "marimo",
- "export",
- "ipynb",
- temp_marimo_file_with_multiple_definitions,
- "--include-outputs",
- ],
- capture_output=True,
+ p = _run_export(
+ "ipynb",
+ temp_marimo_file_with_multiple_definitions,
+ "--include-outputs",
)
- assert p.returncode != 0, p.stderr.decode()
+ _assert_failure(p)
# Error is now captured in the ipynb output as a proper Jupyter error
output = p.stdout.decode()
assert "multiple-defs" in output
@@ -932,23 +784,16 @@ class TestExportIpynb:
def test_export_ipynb_with_errors(
self, temp_marimo_file_with_errors: str
) -> None:
- p = subprocess.run(
- [
- "marimo",
- "export",
- "ipynb",
- temp_marimo_file_with_errors,
- "--include-outputs",
- ],
- capture_output=True,
+ p = _run_export(
+ "ipynb", temp_marimo_file_with_errors, "--include-outputs"
)
- assert p.returncode != 0, p.stderr.decode()
+ _assert_failure(p)
# Error is now captured in the ipynb output (stdout) as a proper
# Jupyter error output, not printed to stderr
output = p.stdout.decode()
assert "division by zero" in output
output = delete_lines_with_files(output)
- snapshot("ipynb_with_errors.txt", output)
+ snapshot(_get_snapshot_path("ipynb", "ipynb_with_errors"), output)
@staticmethod
@pytest.mark.skipif(
@@ -957,20 +802,15 @@ class TestExportIpynb:
)
def test_cli_export_ipynb_sandbox(temp_marimo_file: str) -> None:
output_file = temp_marimo_file.replace(".py", "_sandbox.ipynb")
- p = subprocess.run(
- [
- "marimo",
- "export",
- "ipynb",
- temp_marimo_file,
- "--sandbox",
- "--include-outputs",
- "--output",
- output_file,
- ],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
+ p = _run_export(
+ "ipynb",
+ temp_marimo_file,
+ "--sandbox",
+ "--include-outputs",
+ "--output",
+ output_file,
+ )
+ _assert_success(p)
output = p.stderr.decode()
# Check for sandbox message
assert "Running in a sandbox" in output
@@ -985,18 +825,13 @@ class TestExportIpynb:
temp_marimo_file: str,
) -> None:
# Should not use sandbox when not including outputs
- p = subprocess.run(
- [
- "marimo",
- "export",
- "ipynb",
- temp_marimo_file,
- "--sandbox",
- "--no-include-outputs",
- ],
- capture_output=True,
+ p = _run_export(
+ "ipynb",
+ temp_marimo_file,
+ "--sandbox",
+ "--no-include-outputs",
)
- assert p.returncode == 0, p.stderr.decode()
+ _assert_success(p)
output = p.stdout.decode()
# Should be valid JSON since sandbox is not used
notebook = json.loads(output)
@@ -1005,14 +840,5 @@ class TestExportIpynb:
@staticmethod
def test_cli_export_html_sandbox_no_prompt(temp_marimo_file: str) -> None:
- p = subprocess.run(
- [
- "marimo",
- "export",
- "html",
- temp_marimo_file,
- "--no-sandbox",
- ],
- capture_output=True,
- )
- assert p.returncode == 0, p.stderr.decode()
+ p = _run_export("html", temp_marimo_file, "--no-sandbox")
+ _assert_success(p)
diff --git a/tests/_plugins/stateless/test_mpl.py b/tests/_plugins/stateless/test_mpl.py
index 555f28b4cb..4f91120ffc 100644
--- a/tests/_plugins/stateless/test_mpl.py
+++ b/tests/_plugins/stateless/test_mpl.py
@@ -15,11 +15,66 @@ from marimo._runtime.commands import DeleteCellCommand
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
+HAS_DEPS = DependencyManager.matplotlib.has()
- not DependencyManager.matplotlib.has(),
- reason="matplotlib is not installed",
-)
+
[email protected](not HAS_DEPS, reason="matplotlib is not installed")
+def test_mpl_interactive_repr_png() -> None:
+ """Test that mpl.interactive provides PNG fallback for ipynb export."""
+ import base64
+
+ import matplotlib.pyplot as plt
+
+ from marimo._plugins.stateless.mpl._mpl import InteractiveMplHtml
+
+ # Create a simple figure
+ fig, ax = plt.subplots()
+ ax.plot([1, 2, 3], [1, 2, 3])
+
+ # Create the InteractiveMplHtml object
+ html_obj = InteractiveMplHtml("<div>test</div>", fig)
+
+ # Verify _repr_png_ returns valid base64-encoded PNG bytes
+ png_b64 = html_obj._repr_png_()
+ assert isinstance(png_b64, bytes)
+
+ # Decode and verify it's valid PNG
+ png_bytes = base64.b64decode(png_b64)
+ assert png_bytes.startswith(b"\x89PNG") # PNG magic bytes
+ assert len(png_bytes) > 100 # Should have substantial content
+
+ plt.close(fig)
+
+
[email protected](not HAS_DEPS, reason="matplotlib is not installed")
+def test_mpl_interactive_mime_no_js() -> None:
+ """Test that _mime_ returns PNG when in no-JS mode (ipynb export)."""
+ import matplotlib.pyplot as plt
+
+ from marimo._output.hypertext import patch_html_for_non_interactive_output
+ from marimo._plugins.stateless.mpl._mpl import InteractiveMplHtml
+
+ # Create a simple figure
+ fig, ax = plt.subplots()
+ ax.plot([1, 2, 3], [1, 2, 3])
+
+ # In normal mode, should return text/html
+ html_obj = InteractiveMplHtml("<div>test</div>", fig)
+ mimetype, _ = html_obj._mime_()
+ assert mimetype == "text/html"
+
+ # In no-JS mode (ipynb export), should return image/png
+ with patch_html_for_non_interactive_output():
+ html_obj2 = InteractiveMplHtml("<div>test</div>", fig)
+ mimetype, data = html_obj2._mime_()
+ assert mimetype == "image/png"
+ # Data should be the PNG bytes decoded
+ assert isinstance(data, str)
+
+ plt.close(fig)
+
+
[email protected](not HAS_DEPS, reason="matplotlib is not installed")
async def test_mpl_interactive(k: Kernel, exec_req: ExecReqProvider) -> None:
from threading import Thread
@@ -53,10 +108,7 @@ async def test_mpl_interactive(k: Kernel, exec_req: ExecReqProvider) -> None:
await k.delete_cell(DeleteCellCommand(cell_id=cell.cell_id))
- not DependencyManager.matplotlib.has(),
- reason="matplotlib is not installed",
-)
[email protected](not HAS_DEPS, reason="matplotlib is not installed")
async def test_mpl_show(k: Kernel, exec_req: ExecReqProvider) -> None:
await k.run(
[
@@ -71,10 +123,7 @@ async def test_mpl_show(k: Kernel, exec_req: ExecReqProvider) -> None:
)
- not DependencyManager.matplotlib.has(),
- reason="matplotlib is not installed",
-)
[email protected](not HAS_DEPS, reason="matplotlib is not installed")
def test_patch_javascript() -> None:
from matplotlib.backends.backend_webagg_core import FigureManagerWebAgg
diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txt
index 85234325ff..1b9d3c81a6 100644
--- a/tests/_server/templates/snapshots/export1.txt
+++ b/tests/_server/templates/snapshots/export1.txt
@@ -63,8 +63,8 @@
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"sql_output": "auto", "width": "compact"},
"view": {"showAppCode": true},
- "notebook": {"cells": [{"code": "print('Hello, Cell 1')", "code_hash": "6eea77c855e5bfd73f3d851f474ed789", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "code_hash": "0dce0226aecd5db222f6a3aa3223214b", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
- "session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
+ "notebook": {"cells": [{"code": "print('Hello, Cell 1')", "code_hash": "6eea77c855e5bfd73f3d851f474ed789", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "code_hash": "0dce0226aecd5db222f6a3aa3223214b", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
+ "session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"runtimeConfig": null,
};
</script>
diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txt
index 27aa64783e..3541533c83 100644
--- a/tests/_server/templates/snapshots/export2.txt
+++ b/tests/_server/templates/snapshots/export2.txt
@@ -63,8 +63,8 @@
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"sql_output": "auto", "width": "compact"},
"view": {"showAppCode": true},
- "notebook": {"cells": [{"code": "print('Hello, Cell 1')", "code_hash": "6eea77c855e5bfd73f3d851f474ed789", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "code_hash": "0dce0226aecd5db222f6a3aa3223214b", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
- "session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
+ "notebook": {"cells": [{"code": "print('Hello, Cell 1')", "code_hash": "6eea77c855e5bfd73f3d851f474ed789", "config": {}, "id": "cell1", "name": "Cell 1"}, {"code": "print('Hello, Cell 2')", "code_hash": "0dce0226aecd5db222f6a3aa3223214b", "config": {}, "id": "cell2", "name": "Cell 2"}], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
+ "session": {"cells": [{"code_hash": "abc123", "console": [{"name": "stdout", "text": "Hello, Cell 1", "type": "stream"}, {"name": "stderr", "text": "Error in Cell 1", "type": "stream"}], "id": "cell1", "outputs": [{"data": {"text/plain": "Hello, Cell 1"}, "type": "data"}]}, {"code_hash": "def456", "console": [], "id": "cell2", "outputs": []}], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"runtimeConfig": null,
};
</script>
diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txt
index 7f18dc4458..eed25a6a48 100644
--- a/tests/_server/templates/snapshots/export3.txt
+++ b/tests/_server/templates/snapshots/export3.txt
@@ -63,8 +63,8 @@
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"sql_output": "auto", "width": "compact"},
"view": {"showAppCode": true},
- "notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
- "session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
+ "notebook": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
+ "session": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"runtimeConfig": null,
};
</script>
diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txt
index f65783cdd5..3f309979b7 100644
--- a/tests/_server/templates/snapshots/export4.txt
+++ b/tests/_server/templates/snapshots/export4.txt
@@ -63,8 +63,8 @@
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"css_file": "custom.css", "sql_output": "auto", "width": "compact"},
"view": {"showAppCode": true},
- "notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
- "session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
+ "notebook": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
+ "session": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"runtimeConfig": null,
};
</script>
diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txt
index de5af5c1bb..41a3f3ab46 100644
--- a/tests/_server/templates/snapshots/export5.txt
+++ b/tests/_server/templates/snapshots/export5.txt
@@ -63,8 +63,8 @@
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"app_title": "My App", "html_head_file": "head.html", "sql_output": "auto", "width": "compact"},
"view": {"showAppCode": true},
- "notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
- "session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
+ "notebook": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
+ "session": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"runtimeConfig": null,
};
</script>
diff --git a/tests/_server/templates/snapshots/export6.txt b/tests/_server/templates/snapshots/export6.txt
index 71a55cb195..7a6aae997c 100644
--- a/tests/_server/templates/snapshots/export6.txt
+++ b/tests/_server/templates/snapshots/export6.txt
@@ -63,8 +63,8 @@
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"sql_output": "auto", "width": "compact"},
"view": {"showAppCode": true},
- "notebook": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
- "session": {"cells": [], "metadata": {"marimo_version": "0.1.0"}, "version": "1"},
+ "notebook": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
+ "session": {"cells": [], "metadata": {"marimo_version": "0.0.0"}, "version": "1"},
"runtimeConfig": null,
};
</script>
diff --git a/tests/conftest.py b/tests/conftest.py
index 27358cb953..04271ff497 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -2,12 +2,11 @@
from __future__ import annotations
import dataclasses
-import inspect
-import os
import re
+import shutil
import sys
import textwrap
-from tempfile import TemporaryDirectory
+from pathlib import Path
from typing import TYPE_CHECKING, Any
import pytest
@@ -261,339 +260,88 @@ def executing_kernel() -> Generator[Kernel, None, None]:
mocked.teardown()
-def _cleanup_tmp_dir(tmp_dir: TemporaryDirectory) -> None:
- try:
- # Tests shouldn't care whether temporary directory cleanup
- # fails. Python 3.10+ has an ignore_cleanup_error argument,
- # but we still support 3.9.
- tmp_dir.cleanup()
- except Exception:
- pass
+FIXTURE_DIR = Path(__file__).parent / "fixtures"
@pytest.fixture
-def temp_marimo_file() -> Generator[str, None, None]:
- tmp_dir = TemporaryDirectory()
- tmp_file = os.path.join(tmp_dir.name, "notebook.py")
- content = inspect.cleandoc(
- """
- import marimo
- app = marimo.App()
-
- @app.cell
- def __():
- import marimo as mo
- return mo,
-
- @app.cell
- def __(mo):
- slider = mo.ui.slider(0, 10)
- return slider,
-
- if __name__ == "__main__":
- app.run()
- """
- )
-
- try:
- with open(tmp_file, "w") as f:
- f.write(content)
- yield tmp_file
- finally:
- _cleanup_tmp_dir(tmp_dir)
+def temp_marimo_file(tmp_path: Path) -> str:
+ fixture_file = FIXTURE_DIR / "notebook.py"
+ tmp_file = tmp_path / "test" / "notebook.py"
+ tmp_file.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy(fixture_file, tmp_file)
+ return str(tmp_file)
@pytest.fixture
-def temp_sandboxed_marimo_file() -> Generator[str, None, None]:
- tmp_dir = TemporaryDirectory()
- tmp_file = os.path.join(tmp_dir.name, "notebook.py")
- content = inspect.cleandoc(
- """
- # Copyright 2026 Marimo. All rights reserved.
- # /// script
- # requires-python = ">=3.11"
- # dependencies = [
- # "polars",
- # "marimo>=0.8.0",
- # "quak",
- # "vega-datasets",
- # ]
- # ///
-
- import marimo
- app = marimo.App()
-
- @app.cell
- def __():
- import marimo as mo
- return mo,
-
- @app.cell
- def __(mo):
- slider = mo.ui.slider(0, 10)
- return slider,
-
- if __name__ == "__main__":
- app.run()
- """
- )
-
- try:
- with open(tmp_file, "w") as f:
- f.write(content)
- yield tmp_file
- finally:
- _cleanup_tmp_dir(tmp_dir)
+def temp_sandboxed_marimo_file(tmp_path: Path) -> str:
+ fixture_file = FIXTURE_DIR / "notebook_sandboxed.py"
+ tmp_file = tmp_path / "sandboxed" / "notebook.py"
+ tmp_file.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy(fixture_file, tmp_file)
+ return str(tmp_file)
@pytest.fixture
-def temp_async_marimo_file() -> Generator[str, None, None]:
- tmp_dir = TemporaryDirectory()
- tmp_file = os.path.join(tmp_dir.name, "notebook.py")
- content = inspect.cleandoc(
- """
- import marimo
- app = marimo.App()
-
- @app.cell
- async def __():
- import asyncio
- await asyncio.sleep(0.1)
- return asyncio,
-
- if __name__ == "__main__":
- app.run()
- """
- )
-
- try:
- with open(tmp_file, "w") as f:
- f.write(content)
- f.flush()
- yield tmp_file
- finally:
- _cleanup_tmp_dir(tmp_dir)
+def temp_async_marimo_file(tmp_path: Path) -> str:
+ fixture_file = FIXTURE_DIR / "notebook_async.py"
+ tmp_file = tmp_path / "async" / "notebook.py"
+ tmp_file.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy(fixture_file, tmp_file)
+ return str(tmp_file)
@pytest.fixture
-def temp_unparsable_marimo_file() -> Generator[str, None, None]:
- tmp_dir = TemporaryDirectory()
- tmp_file = os.path.join(tmp_dir.name, "notebook.py")
- content = inspect.cleandoc(
- """
- import marimo
- app = marimo.App()
-
- app._unparsable_cell(
- r\"""
- return
- \""",
- name="__"
- )
-
- app._unparsable_cell(
- r\"""
- partial_statement =
- \""",
- name="__"
- )
-
- @app.cell
- def __():
- valid_statement = 1
- return valid_statement,
-
- if __name__ == "__main__":
- app.run()
- """
- )
-
- try:
- with open(tmp_file, "w") as f:
- f.write(content)
- f.flush()
- yield tmp_file
- finally:
- _cleanup_tmp_dir(tmp_dir)
+def temp_unparsable_marimo_file(tmp_path: Path) -> str:
+ fixture_file = FIXTURE_DIR / "notebook_unparsable.py"
+ tmp_file = tmp_path / "unparsable" / "notebook.py"
+ tmp_file.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy(fixture_file, tmp_file)
+ return str(tmp_file)
@pytest.fixture
-def temp_marimo_file_with_md() -> Generator[str, None, None]:
- tmp_dir = TemporaryDirectory()
- tmp_file = os.path.join(tmp_dir.name, "notebook.py")
- content = inspect.cleandoc(
- """
- import marimo
- app = marimo.App()
-
- @app.cell
- def __(mo):
- control_dep = None
- mo.md("markdown")
- return control_dep
-
- @app.cell
- def __(mo, control_dep):
- control_dep
- mo.md(f"parameterized markdown {123}")
- return
-
- @app.cell
- def __():
- mo.md("plain markdown")
- return mo,
-
- @app.cell
- def __():
- import marimo as mo
- return mo,
-
- if __name__ == "__main__":
- app.run()
- """
- )
-
- try:
- with open(tmp_file, "w") as f:
- f.write(content)
- yield tmp_file
- finally:
- _cleanup_tmp_dir(tmp_dir)
+def temp_marimo_file_with_md(tmp_path: Path) -> str:
+ fixture_file = FIXTURE_DIR / "notebook_with_md.py"
+ tmp_file = tmp_path / "with_md" / "notebook.py"
+ tmp_file.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy(fixture_file, tmp_file)
+ return str(tmp_file)
@pytest.fixture
-def temp_md_marimo_file() -> Generator[str, None, None]:
- tmp_dir = TemporaryDirectory()
- tmp_file = os.path.join(tmp_dir.name, "notebook.md")
- content = inspect.cleandoc(
- """
- ---
- title: Notebook
- marimo-version: 0.0.0
- ---
-
- # This is a markdown document.
- <!---->
- This is a another cell.
-
- ```python {.marimo}
- import marimo as mo
- ```
-
- ```python {.marimo}
- slider = mo.ui.slider(0, 10)
- ```
- """
- )
-
- try:
- with open(tmp_file, "w") as f:
- f.write(content)
- yield tmp_file
- finally:
- _cleanup_tmp_dir(tmp_dir)
+def temp_marimo_file_with_media(tmp_path: Path) -> str:
+ fixture_file = FIXTURE_DIR / "notebook_with_media.py"
+ tmp_file = tmp_path / "with_media" / "notebook.py"
+ tmp_file.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy(fixture_file, tmp_file)
+ return str(tmp_file)
@pytest.fixture
-def old_temp_md_marimo_file() -> Generator[str, None, None]:
- tmp_dir = TemporaryDirectory()
- tmp_file = os.path.join(tmp_dir.name, "notebook.md")
- content = inspect.cleandoc(
- """
- ---
- title: Notebook
- marimo-version: 0.0.0
- ---
-
- # This is a markdown document.
- <!---->
- This is a another cell.
-
- ```{.python.marimo}
- import marimo as mo
- ```
-
- ```{.python.marimo}
- slider = mo.ui.slider(0, 10)
- ```
- """
- )
-
- try:
- with open(tmp_file, "w") as f:
- f.write(content)
- yield tmp_file
- finally:
- _cleanup_tmp_dir(tmp_dir)
+def temp_md_marimo_file(tmp_path: Path) -> str:
+ fixture_file = FIXTURE_DIR / "notebook.md"
+ tmp_file = tmp_path / "with_md" / "notebook.md"
+ tmp_file.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy(fixture_file, tmp_file)
+ return str(tmp_file)
@pytest.fixture
-def temp_marimo_file_with_errors() -> Generator[str, None, None]:
- tmp_dir = TemporaryDirectory()
- tmp_file = os.path.join(tmp_dir.name, "notebook.py")
- content = inspect.cleandoc(
- """
- import marimo
- app = marimo.App()
-
- @app.cell
- def __():
- import marimo as mo
- return mo,
-
- @app.cell
- def __(mo):
- slider = mo.ui.slider(0, 10)
- return slider,
-
- @app.cell
- def __():
- 1 / 0
- return
-
- if __name__ == "__main__":
- app.run()
- """
- )
-
- try:
- with open(tmp_file, "w") as f:
- f.write(content)
- yield tmp_file
- finally:
- _cleanup_tmp_dir(tmp_dir)
+def temp_marimo_file_with_errors(tmp_path: Path) -> str:
+ fixture_file = FIXTURE_DIR / "notebook_with_errors.py"
+ tmp_file = tmp_path / "with_errors" / "notebook.py"
+ tmp_file.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy(fixture_file, tmp_file)
+ return str(tmp_file)
@pytest.fixture
-def temp_marimo_file_with_multiple_definitions() -> Generator[str, None, None]:
- tmp_dir = TemporaryDirectory()
- tmp_file = os.path.join(tmp_dir.name, "notebook.py")
- content = inspect.cleandoc(
- """
- import marimo
- app = marimo.App()
-
- @app.cell
- def __():
- x = 1
- return x,
-
- @app.cell
- def __():
- x = 2
- return x,
-
- if __name__ == "__main__":
- app.run()
- """
- )
-
- try:
- with open(tmp_file, "w") as f:
- f.write(content)
- yield tmp_file
- finally:
- _cleanup_tmp_dir(tmp_dir)
+def temp_marimo_file_with_multiple_definitions(tmp_path: Path) -> str:
+ fixture_file = FIXTURE_DIR / "notebook_with_multiple_definitions.py"
+ tmp_file = tmp_path / "with_multiple_definitions" / "notebook.py"
+ tmp_file.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy(fixture_file, tmp_file)
+ return str(tmp_file)
# Factory to create ExecuteCellCommands and abstract away cell ID
diff --git a/tests/fixtures/notebook.md b/tests/fixtures/notebook.md
new file mode 100644
index 0000000000..dcda5ffb79
--- /dev/null
+++ b/tests/fixtures/notebook.md
@@ -0,0 +1,16 @@
+---
+title: Notebook
+marimo-version: 0.0.0
+---
+
+# This is a markdown document.
+<!---->
+This is a another cell.
+
+```python {.marimo}
+import marimo as mo
+```
+
+```python {.marimo}
+slider = mo.ui.slider(0, 10)
+```
diff --git a/tests/fixtures/notebook.py b/tests/fixtures/notebook.py
new file mode 100644
index 0000000000..e22f61525d
--- /dev/null
+++ b/tests/fixtures/notebook.py
@@ -0,0 +1,19 @@
+import marimo
+
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
+def __(mo):
+ slider = mo.ui.slider(0, 10)
+ return (slider,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/fixtures/notebook_async.py b/tests/fixtures/notebook_async.py
new file mode 100644
index 0000000000..4143754b4a
--- /dev/null
+++ b/tests/fixtures/notebook_async.py
@@ -0,0 +1,14 @@
+import marimo
+
+app = marimo.App()
+
+
+async def __():
+ import asyncio
+ await asyncio.sleep(0.1)
+ return (asyncio,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/fixtures/notebook_sandboxed.py b/tests/fixtures/notebook_sandboxed.py
new file mode 100644
index 0000000000..50cc3bad68
--- /dev/null
+++ b/tests/fixtures/notebook_sandboxed.py
@@ -0,0 +1,30 @@
+# Copyright 2026 Marimo. All rights reserved.
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "polars",
+# "marimo>=0.8.0",
+# "quak",
+# "vega-datasets",
+# ]
+# ///
+
+import marimo
+
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
+def __(mo):
+ slider = mo.ui.slider(0, 10)
+ return (slider,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/fixtures/notebook_unparsable.py b/tests/fixtures/notebook_unparsable.py
new file mode 100644
index 0000000000..9b35b3a875
--- /dev/null
+++ b/tests/fixtures/notebook_unparsable.py
@@ -0,0 +1,27 @@
+import marimo
+
+app = marimo.App()
+
+app._unparsable_cell(
+ r"""
+ return
+ """,
+ name="__",
+)
+
+app._unparsable_cell(
+ r"""
+ partial_statement =
+ """,
+ name="__",
+)
+
+
+def __():
+ valid_statement = 1
+ return (valid_statement,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/fixtures/notebook_with_errors.py b/tests/fixtures/notebook_with_errors.py
new file mode 100644
index 0000000000..9077bd906d
--- /dev/null
+++ b/tests/fixtures/notebook_with_errors.py
@@ -0,0 +1,25 @@
+import marimo
+
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
+def __(mo):
+ slider = mo.ui.slider(0, 10)
+ return (slider,)
+
+
+def __():
+ 1 / 0
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/fixtures/notebook_with_md.py b/tests/fixtures/notebook_with_md.py
new file mode 100644
index 0000000000..713880aedc
--- /dev/null
+++ b/tests/fixtures/notebook_with_md.py
@@ -0,0 +1,33 @@
+import marimo
+
+app = marimo.App()
+
+
+def __(mo):
+ control_dep = None
+ mo.md("markdown")
+ return control_dep
+
+
+def __(mo, control_dep):
+ control_dep
+ mo.md(f"parameterized markdown {123}")
+ return
+
+
+def __():
+ mo.md("plain markdown")
+ return (mo,)
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/fixtures/notebook_with_media.py b/tests/fixtures/notebook_with_media.py
new file mode 100644
index 0000000000..23ad0c8063
--- /dev/null
+++ b/tests/fixtures/notebook_with_media.py
@@ -0,0 +1,114 @@
+# /// script
+# requires-python = ">=3.13"
+# dependencies = [
+# "altair==6.0.0",
+# "marimo",
+# "matplotlib==3.10.8",
+# "numpy==2.4.1",
+# "pandas==2.3.3",
+# "plotly==6.5.2",
+# "pyarrow==22.0.0",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.19.4"
+app = marimo.App(width="medium")
+
+
+def cell_imports():
+ import marimo as mo
+ import matplotlib.pyplot as plt
+ import altair as alt
+ import plotly.graph_objs as go
+ import numpy as np
+ import pandas as pd
+ import pyarrow
+
+ np.random.seed(5)
+ return alt, go, mo, np, pd, plt
+
+
+def pure_markdown_cell(mo):
+ mo.md("""
+ pure markdown cell
+ """)
+ return
+
+
+def ends_with_markdown(mo):
+ _x = 10
+ mo.md("ends with markdown")
+ return
+
+
+def cell_slider(mo):
+ slider = mo.ui.slider(0, 10)
+ slider
+ return
+
+
+def cell_matplotlib(np, plt):
+ # Matplotlib plot
+ x = np.linspace(0, 2 * np.pi, 100)
+ y = np.sin(x)
+ fig, ax = plt.subplots()
+ mpplot = ax.plot(x, y)
+ fig
+ return (fig,)
+
+
+def basic_dataframe(pd):
+ df = pd.DataFrame({"x": [1]})
+ df
+ return
+
+
+def _(fig, mo):
+ # Interactive figure
+ mo.mpl.interactive(fig)
+ return
+
+
+def cell_altair(alt, pd):
+ # Altair chart
+ _df = pd.DataFrame({"x": [1], "y": [1]})
+ chart = alt.Chart(_df).mark_circle().encode(x="x:O", y="y:Q")
+ chart
+ return (chart,)
+
+
+def _(chart, mo):
+ # Wrapped in mo.ui.altair_chart()
+ mo.ui.altair_chart(chart)
+ return
+
+
+def cell_plotly(go, np):
+ # Plotly chart
+ trace = go.Scatter(x=np.arange(2), y=np.random.randn(2), mode="lines+markers")
+ plot = go.Figure(data=[trace])
+ plot
+ return (plot,)
+
+
+def _(mo, plot):
+ # Wrapped in mo.ui.plotly
+ mo.ui.plotly(plot)
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/fixtures/notebook_with_multiple_definitions.py b/tests/fixtures/notebook_with_multiple_definitions.py
new file mode 100644
index 0000000000..4074d88fa0
--- /dev/null
+++ b/tests/fixtures/notebook_with_multiple_definitions.py
@@ -0,0 +1,19 @@
+import marimo
+
+app = marimo.App()
+
+
+def __():
+ x = 1
+ return (x,)
+
+
+def __():
+ x = 2
+ return (x,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/mocks.py b/tests/mocks.py
index f522a5ae8d..01dddfb17d 100644
--- a/tests/mocks.py
+++ b/tests/mocks.py
@@ -121,9 +121,13 @@ def snapshotter(current_file: str) -> SnapshotFunc:
def _sanitize_version(output: str) -> str:
- return output.replace(f"{__version__} (editable)", "0.0.0").replace(
+ output = output.replace(f"{__version__} (editable)", "0.0.0").replace(
f"{__version__}", "0.0.0"
)
+ output = re.sub(
+ r'"marimo_version": "[^"]*"', '"marimo_version": "0.0.0"', output
+ )
+ return output
def delete_lines_with_files(output: str) -> str:
@@ -159,6 +163,92 @@ def simplify_images(output: str) -> str:
return output
+def simplify_plotly(output: str) -> str:
+ """Simplify plotly output for consistent snapshots."""
+ # Replace any <marimo-plotly ...>...</marimo-plotly> (attributes or not, any whitespace, multiline)
+ # This will handle possible attributes, whitespace, and multiline contents.
+ output = re.sub(
+ r"<marimo-plotly\b[^>]*>.*?</marimo-plotly>",
+ "<marimo-plotly>REDACTED</marimo-plotly>",
+ output,
+ flags=re.DOTALL | re.IGNORECASE,
+ )
+ # Replace plotly base64 blobs in data URLs (including possible line breaks)
+ output = re.sub(
+ r"data:application/json;base64,[A-Za-z0-9+/=\n\r]*",
+ "data:application/json;base64,REDACTED_BASE64_DATA",
+ output,
+ flags=re.DOTALL,
+ )
+ # As a last resort, if there are still very large chunks of plotly content,
+ # we redact anything between tags that looks like giant plotly JSON blobs.
+ output = re.sub(
+ r'("application/vnd\.plotly\.v1\+json":\s*")[^"]*(")',
+ r"\1REDACTED_PLOTLY_JSON\2",
+ output,
+ flags=re.DOTALL,
+ )
+
+ # Sanitize raw Plotly HTML output (from mo.ui.plotly())
+ # Replace random UUID-like div IDs (handles both escaped and unescaped quotes)
+ output = re.sub(
+ r'id=\\"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\"',
+ 'id=\\"PLOTLY_DIV_ID\\"',
+ output,
+ )
+ output = re.sub(
+ r'id="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"',
+ 'id="PLOTLY_DIV_ID"',
+ output,
+ )
+ # Replace UUID in getElementById calls (handles both escaped and unescaped quotes)
+ output = re.sub(
+ r'getElementById\(\\"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\"\)',
+ 'getElementById(\\"PLOTLY_DIV_ID\\")',
+ output,
+ )
+ output = re.sub(
+ r'getElementById\("([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"\)',
+ 'getElementById("PLOTLY_DIV_ID")',
+ output,
+ )
+ # Replace UUID in Plotly.newPlot calls (handles both escaped and unescaped quotes)
+ output = re.sub(
+ r'Plotly\.newPlot\(\s*\\"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\"',
+ 'Plotly.newPlot(\\"PLOTLY_DIV_ID\\"',
+ output,
+ )
+ output = re.sub(
+ r'Plotly\.newPlot\(\s*"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"',
+ 'Plotly.newPlot("PLOTLY_DIV_ID"',
+ output,
+ )
+ # Replace plotly CDN URLs with version and integrity (handles both escaped and unescaped quotes)
+ output = re.sub(
+ r'src=\\"https://cdn\.plot\.ly/plotly-[^\\"]*\\" integrity=\\"[^\\"]*\\"',
+ 'src=\\"https://cdn.plot.ly/plotly-VERSION.min.js\\" integrity=\\"INTEGRITY_HASH\\"',
+ output,
+ )
+ output = re.sub(
+ r'src="https://cdn\.plot\.ly/plotly-[^"]*" integrity="[^"]*"',
+ 'src="https://cdn.plot.ly/plotly-VERSION.min.js" integrity="INTEGRITY_HASH"',
+ output,
+ )
+ # Replace base64-encoded binary data in plotly JSON (handles both escaped and unescaped quotes)
+ output = re.sub(
+ r'\\"bdata\\":\\"[^\\"]*\\"',
+ '\\"bdata\\":\\"PLOTLY_BINARY_DATA\\"',
+ output,
+ )
+ output = re.sub(
+ r'"bdata":"[^"]*"',
+ '"bdata":"PLOTLY_BINARY_DATA"',
+ output,
+ )
+
+ return output
+
+
NON_WINDOWS_EDGE_CASE_FILENAMES = [
"test<script>.py",
'test"quotes".py',