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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
from __future__ import annotations
import asyncio
import base64
import json
import pathlib
import sys
import textwrap
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
from dataclasses import replace
from typing import TYPE_CHECKING, Any
from unittest.mock import AsyncMock, 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._dependencies.dependencies import Dependency, DependencyManager
from marimo._dependencies.errors import ManyModulesNotFoundError
from marimo._export._status import PDFExportStatusEvent
from marimo._export.exporter import Exporter, render_pdf
from marimo._export.file import (
export_html,
export_ipynb,
export_markdown,
export_pdf,
export_wasm,
run_notebook,
)
from marimo._export.requests import (
HTMLExportRequest,
HTMLFileExportRequest,
IPYNBFileExportRequest,
MarkdownFileExportRequest,
NotebookExecutionOptions,
PDFExportRequest,
PDFFileExportRequest,
RunNotebookRequest,
WASMExportRequest,
WASMFileExportRequest,
)
from marimo._export.serialization import serialize_notebook_snapshot
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.msgspec_encoder import encode_json_str
from marimo._messaging.notification import (
CellNotification,
EsmSpec,
ModelLifecycleNotification,
ModelOpen,
)
from marimo._schemas.export import (
ExportAsHTMLRequest,
)
from marimo._schemas.export_options import (
ExportPDFPreset,
HTMLExportOptions,
IPYNBExportOptions,
MarkdownExportOptions,
PDFExportOptions,
PDFRasterizationOptions,
WASMExportOptions,
)
from marimo._session.notebook import AppFileManager
from marimo._session.state.serialize import get_session_cache_file
from marimo._session.state.session_view import SessionView
from marimo._types.ids import WidgetModelId
from marimo._utils.marimo_path import MarimoPath
from tests._server.templates.utils import parse_mount_config
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()
HAS_DEPS = (
HAS_NBFORMAT
and DependencyManager.polars.has()
and DependencyManager.altair.has()
and DependencyManager.matplotlib.has()
)
def _html_export_request(
*,
filename: str | None,
app: InternalApp,
session_view: SessionView,
display_config: Any,
request: ExportAsHTMLRequest,
sharing_config: Any = None,
) -> HTMLExportRequest:
return HTMLExportRequest(
filename=filename,
app_code=app.to_py(),
app_config=app.config,
snapshot=serialize_notebook_snapshot(
app,
session_view,
drop_virtual_file_outputs=False,
include_model_notifications=True,
),
display_config=display_config,
options=HTMLExportOptions(
files=tuple(request.files),
include_code=request.include_code,
asset_url=request.asset_url,
),
sharing_config=sharing_config,
)
def _wasm_export_request(
*,
filename: str | None,
app: InternalApp,
display_config: Any,
code: str,
mode: Any,
show_code: bool,
asset_url: str | None = None,
session_snapshot: Any = None,
notebook_snapshot: Any = None,
sharing_config: Any = None,
) -> WASMExportRequest:
return WASMExportRequest(
filename=filename,
app_config=app.config,
display_config=display_config,
code=code,
options=WASMExportOptions(
mode=mode,
show_code=show_code,
asset_url=asset_url,
),
session_snapshot=session_snapshot,
notebook_snapshot=notebook_snapshot,
sharing_config=sharing_config,
)
def _write_layout_notebook(
tmp_path: Path,
*,
contents: str | None,
layout_file: str = "layouts/layout.json",
) -> Path:
notebook = tmp_path / "test.py"
source = (
(FIXTURES_DIR / "with_layout.py")
.read_text()
.replace("layouts/layout.json", layout_file)
)
notebook.write_text(source)
if contents is not None:
path = tmp_path / layout_file
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(contents)
return notebook
def _pdf_export_request(
*,
app: InternalApp,
session_view: SessionView | None,
png_fallbacks: Any = None,
webpdf: bool = False,
include_inputs: bool = True,
status_callback: Any = None,
preset: ExportPDFPreset = "document",
) -> PDFExportRequest:
return PDFExportRequest(
app=app,
session_view=session_view,
png_fallbacks=png_fallbacks,
options=PDFExportOptions(
webpdf=webpdf,
preset=preset,
include_inputs=include_inputs,
),
status_callback=status_callback,
)
@pytest.mark.parametrize(
("filename", "source", "expected_fence"),
[
("demo.qmd", "```{marimo .python}\nx = 1\n```", "```{marimo .python"),
(
"demo.myst.md",
"```{marimo} python\nx = 1\n```",
"```{marimo} python",
),
],
)
def test_export_as_md_uses_resolved_markdown_filename(
tmp_path: Path, filename: str, source: str, expected_fence: str
) -> None:
notebook = tmp_path / filename
notebook.write_text(source, encoding="utf-8")
result = export_markdown(
MarkdownFileExportRequest(
path=MarimoPath(notebook),
options=MarkdownExportOptions(),
)
)
assert result.download_filename == filename
assert expected_fence in result.text
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]
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)
# run_notebook
async def test_run_notebook_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_notebook(
RunNotebookRequest(
file_manager=file_manager,
options=NotebookExecutionOptions(cli_args={}, argv=None),
)
)
assert did_error is False
cell_notifications = [
op
for op in session_view.snapshot_notifications()
if isinstance(op, CellNotification)
]
snapshot(
"run_notebook_with_stop.txt",
_print_messages(cell_notifications),
)
async def test_run_notebook_persists_session_snapshot(
tmp_path: Path,
) -> None:
notebook = tmp_path / "notebook.py"
notebook.write_text(
"""
import marimo
app = marimo.App()
@app.cell
def _():
return
if __name__ == "__main__":
app.run()
""",
encoding="utf-8",
)
file_manager = AppFileManager(str(notebook))
_, did_error = await run_notebook(
RunNotebookRequest(
file_manager=file_manager,
options=NotebookExecutionOptions(cli_args={}, argv=None),
)
)
assert did_error is False
session_file = get_session_cache_file(notebook)
assert session_file.exists()
data = json.loads(session_file.read_text(encoding="utf-8"))
assert "script_metadata_hash" in data["metadata"]
@pytest.mark.skipif(
sys.version_info >= (3, 13), reason="3.13 has different stack trace format"
)
@pytest.mark.xfail(reason="flakey", strict=False)
async def test_run_notebook_with_stack_trace() -> None:
"""Test run until completion with stack trace from exception."""
app = App()
@app.cell()
def _():
print("running internal tests")
@app.cell()
def _():
import sys
sys.stderr.write("internal error\n")
@app.cell()
def _():
given_password = "test"
if given_password != "s3cret":
raise ValueError(
"Failed to authenticate. The correct password is 's3cret'."
)
file_manager = AppFileManager.from_app(InternalApp(app))
session_view, did_error = await run_notebook(
RunNotebookRequest(
file_manager=file_manager,
options=NotebookExecutionOptions(cli_args={}, argv=None),
)
)
assert did_error is True
cell_notifications = [
op
for op in session_view.snapshot_notifications()
if isinstance(op, CellNotification)
]
messages = _print_messages(cell_notifications)
snapshot(
"run_notebook_with_stack_trace.txt",
delete_lines_with_files(messages),
)
@pytest.mark.flaky(reruns=3)
async def test_run_notebook_with_console_output(
capsys: pytest.CaptureFixture[str],
) -> None:
"""Test run until completion with console output."""
internal_app = _load_fixture_app("with_console_output")
file_manager = AppFileManager.from_app(internal_app)
session_view, did_error = await run_notebook(
RunNotebookRequest(
file_manager=file_manager,
options=NotebookExecutionOptions(cli_args={}, argv=None),
)
)
assert did_error is False
def _assert_contents() -> None:
captured = capsys.readouterr()
assert "hello stdout" in captured.err
assert "hello stderr" in captured.err
# 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()
cell_notifications = [
op
for op in session_view.snapshot_notifications()
if isinstance(op, CellNotification)
]
snapshot(
"run_notebook_with_console_output.txt",
_print_messages(cell_notifications),
)
# WASM export
@pytest.mark.parametrize(
("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(
_wasm_export_request(
filename=file_manager.filename,
app=file_manager.app,
display_config=DEFAULT_CONFIG["display"],
mode=mode,
code=file_manager.app.to_py(),
show_code=True,
)
)
assert filename == "notebook.wasm.html"
assert "alert(" in content
assert expected_mode_in_content in content
@pytest.mark.parametrize(
"export_kind",
["static", "wasm", "wasm-executed"],
)
@pytest.mark.parametrize(
("layout_file", "contents", "expected"),
[
(
"layouts/layout.json",
'{"type": "slides", "data": {}}',
{"type": "slides", "data": {}},
),
("layouts/layout.json", "{", None),
("layouts/missing.json", None, None),
(
"data:application/json;base64,"
+ base64.b64encode(
b'{"type":"slides","data":{"deck":{"transition":"fade"}}}'
).decode("ascii"),
None,
{
"type": "slides",
"data": {"deck": {"transition": "fade"}},
},
),
(
"layouts/layout.txt",
'{"type": "slides", "data": {}}',
None,
),
],
ids=["valid", "malformed", "missing", "data-uri", "non-json"],
)
async def test_file_export_resolves_layout_once(
tmp_path: Path,
export_kind: str,
layout_file: str,
contents: str | None,
expected: dict[str, Any] | None,
) -> None:
test_file = _write_layout_notebook(
tmp_path,
layout_file=layout_file,
contents=contents,
)
if export_kind == "static":
result = await export_html(
HTMLFileExportRequest(
path=MarimoPath(test_file),
options=HTMLExportOptions(files=(), include_code=True),
)
)
else:
result = await export_wasm(
WASMFileExportRequest(
path=MarimoPath(test_file),
options=WASMExportOptions(mode="run", show_code=True),
execution=(
NotebookExecutionOptions(cli_args={}, argv=[])
if export_kind == "wasm-executed"
else None
),
)
)
assert result.did_error is False
assert parse_mount_config(result.text)["layout"] == expected
if not layout_file.startswith("data:"):
assert layout_file not in result.text
if expected is not None:
assert "data:application/json;base64," in result.text
# HTML export
@pytest.mark.parametrize(
("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."""
app = App()
@app.cell()
def test_cell():
secret_value = "should_not_appear"
print("visible output")
return secret_value
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",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data="visible output",
),
console=[
CellOutput(
channel=CellChannel.STDOUT,
mimetype="text/plain",
data="console message",
)
],
timestamp=0,
)
session_view.last_executed_code[cell_ids[0]] = (
"secret_value = 'should_not_appear'\n"
"print('visible output')\n"
"return secret_value"
)
exporter = Exporter()
request = ExportAsHTMLRequest(
download=not include_code,
files=[],
include_code=include_code,
)
html, filename = exporter.export_as_html(
_html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
assert filename == "notebook.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_omits_getpass_response(
session_view: SessionView,
) -> None:
app = App()
@app.cell()
def _():
import getpass
_password = getpass.getpass("Password: ")
internal_app = InternalApp(app)
cell_id = next(iter(internal_app.cell_manager.cell_ids()))
session_view.add_notification(
CellNotification(
cell_id=cell_id,
console=CellOutput.stdin("Password: ", password=True),
)
)
secret = "getpass-regression-secret"
session_view.add_stdin(secret)
html, _ = Exporter().export_as_html(
_html_export_request(
filename="getpass.py",
app=internal_app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=ExportAsHTMLRequest(
download=False, files=[], include_code=True
),
)
)
assert secret not in html
assert secret not in encode_json_str(session_view.snapshot_notifications())
assert parse_mount_config(html)["session"]["cells"][0]["console"] == [
{
"type": "stream",
"name": "stdout",
"text": "Password: \n",
"mimetype": "text/plain",
}
]
def test_export_as_html_with_serialization(session_view: SessionView) -> None:
"""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,)
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",
),
console=[
CellOutput(
channel=CellChannel.STDOUT,
mimetype="text/plain",
data="Hello World",
)
],
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,)"
)
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=[],
include_code=True,
)
html, filename = exporter.export_as_html(
_html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
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) -> None:
"""Test HTML export includes virtual files."""
app = App()
@app.cell()
def test_cell():
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",
output=None,
console=[],
timestamp=0,
)
session_view.last_executed_code[cell_ids[0]] = "return 'test'"
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=["/@file/10-test.txt"],
include_code=True,
)
with patch("marimo._export.exporter.read_virtual_file") as mock_read:
mock_read.return_value = b"test file content"
html, filename = exporter.export_as_html(
_html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
assert filename == "notebook.html"
assert "data:" in html
def test_export_as_html_includes_composed_widget_esm(
session_view: SessionView,
) -> None:
"""A composed-only widget's ESM is embedded in standalone HTML."""
app = App()
@app.cell()
def parent_cell():
return "parent"
file_manager = AppFileManager.from_app(InternalApp(app))
cell_id = next(iter(file_manager.app.cell_manager.cell_ids()))
session_view.cell_notifications[cell_id] = CellNotification(
cell_id=cell_id,
status="idle",
output=None,
console=[],
timestamp=0,
)
session_view.last_executed_code[cell_id] = "return 'parent'"
widget_code = b"export default { render() {} }"
widget_url = f"./@file/{len(widget_code)}-child-widget.js"
session_view.add_notification(
ModelLifecycleNotification(
model_id=WidgetModelId("child-widget"),
message=ModelOpen(
state={},
buffer_paths=[],
buffers=[],
esm_spec=EsmSpec(url=widget_url, hash="child-hash"),
),
)
)
with patch(
"marimo._export.exporter.read_virtual_file",
return_value=widget_code,
):
html, _filename = Exporter().export_as_html(
_html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=ExportAsHTMLRequest(
download=True,
files=[],
include_code=True,
),
),
)
assert f'"/{widget_url.removeprefix("./")}":' in html
assert base64.b64encode(widget_code).decode("ascii") in html
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)
def configured_cell():
return "configured"
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",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data="configured",
),
console=[],
timestamp=0,
)
session_view.last_executed_code[cell_ids[0]] = "return 'configured'"
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=[],
include_code=True,
)
html, filename = exporter.export_as_html(
_html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
assert filename == "notebook.html"
assert "hide_code" in html or "hideCode" in html
assert "configured" in html
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()
def cell_first():
return "first"
@app.cell()
def cell_second():
return "second"
@app.cell()
def cell_third():
return "third"
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
for i, cell_id in enumerate(cell_ids):
session_view.cell_notifications[cell_id] = CellNotification(
cell_id=cell_id,
status="idle",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data=f"output_{i}",
),
console=[],
timestamp=i,
)
session_view.last_executed_code[cell_id] = f"return 'output_{i}'"
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=[],
include_code=True,
)
html, filename = exporter.export_as_html(
_html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
assert filename == "notebook.html"
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) -> None:
"""Test HTML export handles error outputs correctly."""
from marimo._messaging.errors import MarimoExceptionRaisedError
app = App()
@app.cell()
def error_cell():
raise ValueError("Test error")
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
error = MarimoExceptionRaisedError(
exception_type="ValueError",
msg="Test error",
raising_cell=cell_ids[0],
)
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput.errors([error]),
console=[],
timestamp=0,
)
session_view.last_executed_code[cell_ids[0]] = (
"raise ValueError('Test error')"
)
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=[],
include_code=True,
)
html, filename = exporter.export_as_html(
_html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
assert filename == "notebook.html"
assert "Test error" in html or "ValueError" in html
def _write_lazy_notebook(path: Path, lazy_arg: str) -> None:
path.write_text(
textwrap.dedent(
f"""
import marimo
app = marimo.App()
@app.cell
def _():
import marimo as mo
def _make_async():
async def inner():
return "ASYNC_RESULT"
return inner
mo.lazy({lazy_arg})
return ()
if __name__ == "__main__":
app.run()
"""
)
)
@pytest.mark.skipif(
not DependencyManager.nbformat.has(), reason="nbformat not installed"
)
@pytest.mark.parametrize(
("lazy_arg", "expected_marker", "should_resolve"),
[
pytest.param('"EAGER_VALUE"', "EAGER_VALUE", True, id="eager_value"),
pytest.param(
'lambda: "SYNC_RESULT"', "SYNC_RESULT", True, id="sync_callable"
),
pytest.param(
"_make_async()", "ASYNC_RESULT", False, id="async_callable"
),
],
)
async def test_export_ipynb_resolves_lazy(
tmp_path: Path,
lazy_arg: str,
expected_marker: str,
should_resolve: bool,
) -> None:
"""Regression test for https://github.com/marimo-team/marimo/issues/9624.
Non-interactive exports (ipynb, PDF) resolve sync `mo.lazy` content
eagerly. Async elements can't be awaited from `__new__` and stay as
placeholders.
"""
notebook = tmp_path / "lazy_notebook.py"
_write_lazy_notebook(notebook, lazy_arg)
result = await export_ipynb(
IPYNBFileExportRequest(
path=MarimoPath(str(notebook)),
options=IPYNBExportOptions(sort_mode="top-down"),
execution=NotebookExecutionOptions(cli_args={}, argv=[]),
)
)
# The rendered HTML is wrapped in <span> by as_html; the raw marker
# alone appears in the cell source regardless, so check the wrapped
# form to confirm resolution.
rendered = f"<span>{expected_marker}</span>"
if should_resolve:
assert rendered in result.contents
assert "marimo-lazy" not in result.contents
else:
assert "marimo-lazy" in result.contents
assert rendered not in result.contents
async def test_export_html_keeps_lazy_placeholder(
tmp_path: Path,
) -> None:
"""HTML export ships interactive widgets and leaves `mo.lazy` as a placeholder.
Static HTML exports don't resolve `mo.lazy` because the global
`is_non_interactive` flag would also switch tables/altair/plotly/etc.
to non-interactive fallbacks. A lazy-specific resolution path can be
added later as a follow-up.
"""
notebook = tmp_path / "lazy_notebook.py"
_write_lazy_notebook(notebook, 'lambda: "SYNC_RESULT"')
result = await export_html(
HTMLFileExportRequest(
path=MarimoPath(str(notebook)),
options=HTMLExportOptions(
files=(),
include_code=False,
),
execution=NotebookExecutionOptions(cli_args={}, argv=[]),
)
)
assert "marimo-lazy" in result.contents
assert "SYNC_RESULT" not in result.contents
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()
def test_cell():
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",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="application/vnd.marimo+error",
data=[
{
"type": "exception",
"msg": "bad",
"exception_type": "ValueError",
"raising_cell": None,
"traceback": None,
}
],
code="private_source_sentinel = 42",
),
console=[],
timestamp=0,
)
session_view.last_executed_code[cell_ids[0]] = "return 'test'"
exporter = Exporter()
# Test with include_code=True
export_request = _html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=ExportAsHTMLRequest(
download=True,
files=[],
include_code=True,
),
)
snapshot_before = deepcopy(export_request.snapshot)
# Test with include_code=False
html_without_code, _ = exporter.export_as_html(
replace(
export_request,
options=HTMLExportOptions(files=(), include_code=False),
)
)
html_with_code, _ = exporter.export_as_html(export_request)
assert export_request.snapshot == snapshot_before
assert "private_source_sentinel" not in html_without_code
assert "private_source_sentinel" in html_with_code
# Extract code hash from both HTML outputs
hash_pattern = r"<marimo-code-hash[^>]*>([a-f0-9]+)</marimo-code-hash>"
hash_with_code = re.search(hash_pattern, html_with_code)
hash_without_code = re.search(hash_pattern, html_without_code)
assert hash_with_code is not None, "Code hash not found in HTML with code"
assert hash_without_code is not None, (
"Code hash not found in HTML without code"
)
assert hash_with_code.group(1) == hash_without_code.group(1), (
"Code hashes should be identical"
)
assert '"code": ""' in html_without_code, (
"Cell code should be empty when include_code=False"
)
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()
def test_cell():
import marimo as mo
return mo.image(src="test.png")
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
html_with_virtual_file = (
'<img src="./@file/100-test.png" alt="Test image">'
)
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/html",
data=html_with_virtual_file,
),
console=[],
timestamp=0,
)
session_view.last_executed_code[cell_ids[0]] = (
"import marimo as mo\nreturn mo.image(src='test.png')"
)
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=["/@file/100-test.png"],
include_code=True,
)
with patch(
"marimo._convert.common.dom_traversal.read_virtual_file"
) as mock_read:
mock_read.return_value = b"fake_image_data"
html, filename = exporter.export_as_html(
_html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
assert filename == "notebook.html"
assert "./@file/100-test.png" not in html
assert "data:image/png;base64," in html
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()
def cell_1():
import marimo as mo
return mo.image(src="chart.png")
@app.cell()
def cell_2():
import marimo as mo
return mo.md("")
@app.cell()
def cell_3():
return '<div><img src="./@file/300-diagram.svg"><img src="https://example.com/external.png"></div>'
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
# Cell 1: Image with virtual file
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/html",
data='<img src="./@file/100-chart.png" alt="Chart">',
),
console=[],
timestamp=0,
)
session_view.last_executed_code[cell_ids[0]] = (
"import marimo as mo\nreturn mo.image(src='chart.png')"
)
# Cell 2: Markdown with virtual file
session_view.cell_notifications[cell_ids[1]] = CellNotification(
cell_id=cell_ids[1],
status="idle",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/html",
data='<p><img src="./@file/200-plot.png" alt="Plot"></p>',
),
console=[],
timestamp=1,
)
session_view.last_executed_code[cell_ids[1]] = (
"import marimo as mo\nreturn mo.md('')"
)
# Cell 3: Mixed - virtual file and external URL
session_view.cell_notifications[cell_ids[2]] = CellNotification(
cell_id=cell_ids[2],
status="idle",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/html",
data='<div><img src="./@file/300-diagram.svg"><img src="https://example.com/external.png"></div>',
),
console=[],
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>\''
)
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=[
"/@file/100-chart.png",
"/@file/200-plot.png",
"/@file/300-diagram.svg",
"/@file/400-unused.txt",
],
include_code=True,
)
def mock_read_side_effect(filename: str, byte_length: int) -> bytes:
del byte_length
if filename == "chart.png":
return b"chart_data"
elif filename == "plot.png":
return b"plot_data"
elif filename == "diagram.svg":
return b"<svg>diagram</svg>"
elif filename == "unused.txt":
return b"unused_content"
return b"default_data"
with (
patch(
"marimo._convert.common.dom_traversal.read_virtual_file"
) as mock_read_dom,
patch(
"marimo._export.exporter.read_virtual_file"
) as mock_read_exporter,
):
mock_read_dom.side_effect = mock_read_side_effect
mock_read_exporter.side_effect = mock_read_side_effect
html, filename = exporter.export_as_html(
_html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
assert filename == "notebook.html"
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()
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"
assert "data:image/png;base64," in html
assert "data:image/svg+xml;base64," in html
assert "https://example.com/external.png" in html
def test_export_html_replaces_audio_virtual_files(
session_view: SessionView,
) -> None:
"""Test that audio virtual file URLs are inlined as data URIs."""
app = App()
@app.cell()
def test_cell():
import marimo as mo
return mo.audio(src="clip.wav")
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
html_with_audio = '<audio src="./@file/500-clip.wav" controls></audio>'
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/html",
data=html_with_audio,
),
console=[],
timestamp=0,
)
session_view.last_executed_code[cell_ids[0]] = (
"import marimo as mo\nreturn mo.audio(src='clip.wav')"
)
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=["/@file/500-clip.wav"],
include_code=True,
)
with patch(
"marimo._convert.common.dom_traversal.read_virtual_file"
) as mock_read:
mock_read.return_value = b"fake_audio_data"
html, filename = exporter.export_as_html(
_html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
assert filename == "notebook.html"
assert "./@file/500-clip.wav" not in html
# mimetypes returns audio/x-wav on macOS/Linux, audio/wav on Windows
assert (
"data:audio/x-wav;base64," in html or "data:audio/wav;base64," in html
)
expected_b64 = base64.b64encode(b"fake_audio_data").decode()
assert expected_b64 in html
def test_export_html_inlines_public_folder_images(
session_view: SessionView, tmp_path: Path
) -> None:
"""Test that <img src="public/..."> references are inlined as data URIs.
Regression test for marimo-team/marimo#9625: a markdown cell like
`mo.md("")` produces HTML output that points at
`public/image.png`. The standalone exported HTML must inline those
images so the file is self-contained when opened without the sibling
`public/` folder.
"""
# Arrange: notebook file with a sibling public/image.png
notebook_path = tmp_path / "nb.py"
notebook_path.write_text("import marimo\napp = marimo.App()\n")
public_dir = tmp_path / "public"
public_dir.mkdir()
png_bytes = b"\x89PNG\r\n\x1a\nfakeimage"
(public_dir / "image.png").write_bytes(png_bytes)
app = App()
@app.cell()
def cell_md():
import marimo as mo
return mo.md("")
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
# mo.md emits rendered HTML under text/markdown: the raw
# `public/image.png` path is preserved (no inlining at runtime).
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/markdown",
data=(
'<span class="markdown">'
'<img alt="alt" src="public/image.png">'
"</span>"
),
),
console=[],
timestamp=0,
)
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=[],
include_code=True,
)
html, _filename = exporter.export_as_html(
_html_export_request(
filename=str(notebook_path),
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
# The original path is gone; the image is embedded as a data URI.
assert 'src="public/image.png"' not in html
assert "data:image/png;base64," in html
assert base64.b64encode(png_bytes).decode() in html
def test_export_html_does_not_touch_non_html_outputs(
session_view: SessionView, tmp_path: Path
) -> None:
"""text/plain (and other non-HTML) outputs must NOT be HTML-parsed.
Regression guard: previously `_iter_html_data_strings` yielded every
string mime entry, which meant `text/plain` data containing literal
`./@file/...` text was rewritten as if it were HTML.
"""
notebook_path = tmp_path / "nb.py"
notebook_path.write_text("import marimo\napp = marimo.App()\n")
app = App()
@app.cell()
def _():
return None
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
# A plain-text output that happens to contain virtual-file and public/
# tokens — these must NOT be rewritten because the mime is text/plain.
plain = "see ./@file/100-test.png or public/image.png"
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data=plain,
),
console=[],
timestamp=0,
)
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=[],
include_code=True,
)
html, _ = exporter.export_as_html(
_html_export_request(
filename=str(notebook_path),
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
# The plain-text content is preserved verbatim (JSON-escaped in the
# session snapshot, hence the substring check rather than equality).
assert "./@file/100-test.png" in html
assert "public/image.png" in html
def test_export_html_public_folder_blocks_path_traversal(
session_view: SessionView, tmp_path: Path
) -> None:
"""Test that path traversal attempts via public/ paths are rejected."""
notebook_path = tmp_path / "nb.py"
notebook_path.write_text("import marimo\napp = marimo.App()\n")
(tmp_path / "public").mkdir()
# File OUTSIDE the public/ folder that an attacker would try to read.
(tmp_path / "secret.txt").write_bytes(b"shh")
app = App()
@app.cell()
def cell_md():
return None
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",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/html",
data='<img src="public/../secret.txt">',
),
console=[],
timestamp=0,
)
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=[],
include_code=True,
)
html, _ = exporter.export_as_html(
_html_export_request(
filename=str(notebook_path),
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
# The secret file must NOT be inlined.
assert base64.b64encode(b"shh").decode() not in html
def test_export_html_skips_oversized_virtual_files(
session_view: SessionView,
) -> None:
"""Test that virtual files exceeding the size limit are not inlined."""
app = App()
@app.cell()
def test_cell():
import marimo as mo
return mo.audio(src="huge.wav")
file_manager = AppFileManager.from_app(InternalApp(app))
cell_ids = list(file_manager.app.cell_manager.cell_ids())
# 20_000_000 bytes (20 MB) exceeds the 10 MB inline limit
html_with_large_audio = (
'<audio src="./@file/20000000-huge.wav" controls></audio>'
)
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/html",
data=html_with_large_audio,
),
console=[],
timestamp=0,
)
session_view.last_executed_code[cell_ids[0]] = (
"import marimo as mo\nreturn mo.audio(src='huge.wav')"
)
exporter = Exporter()
request = ExportAsHTMLRequest(
download=True,
files=["/@file/20000000-huge.wav"],
include_code=True,
)
with (
patch(
"marimo._convert.common.dom_traversal.read_virtual_file"
) as mock_read_dom,
patch(
"marimo._export.exporter.read_virtual_file"
) as mock_read_exporter,
):
mock_read_dom.return_value = b"huge_audio"
mock_read_exporter.return_value = b"huge_audio"
html, _filename = exporter.export_as_html(
_html_export_request(
filename=file_manager.filename,
app=file_manager.app,
session_view=session_view,
display_config=DEFAULT_CONFIG["display"],
request=request,
)
)
# The large file should NOT be inlined as audio in the HTML output
# mimetypes returns audio/x-wav on macOS/Linux, audio/wav on Windows
assert "data:audio/x-wav;base64," not in html
assert "data:audio/wav;base64," not in html
# A text/plain placeholder should appear instead of the broken URL
assert "data:text/plain;base64," in html
assert "./@file/20000000-huge.wav" not in html
class TestPDFExport:
@pytest.mark.asyncio
@pytest.mark.parametrize(
("preset", "expected"),
[("document", b"document"), ("slides", b"slides")],
)
async def test_render_pdf_dispatches_by_preset(
self,
preset: ExportPDFPreset,
expected: bytes,
session_view: SessionView,
) -> None:
request = _pdf_export_request(
app=InternalApp(App()),
session_view=session_view,
preset=preset,
)
with (
patch.object(
Exporter,
"export_as_pdf",
autospec=True,
return_value=b"document",
) as document_export,
patch.object(
Exporter,
"export_as_slides_pdf",
autospec=True,
return_value=b"slides",
) as slides_export,
):
result = await render_pdf(request)
assert result == expected
if preset == "document":
assert document_export.call_args.args[1] is request
slides_export.assert_not_awaited()
else:
document_export.assert_not_called()
assert slides_export.await_args.args[1] is request
def test_export_as_pdf_requires_dependencies(
self,
session_view: SessionView,
) -> None:
"""Test that PDF export raises error when dependencies are missing."""
app = App()
@app.cell()
def test_cell():
return "test"
file_manager = AppFileManager.from_app(InternalApp(app))
exporter = Exporter()
# Mock nbformat as missing
with patch.object(Dependency, "has", return_value=False):
with pytest.raises(ManyModulesNotFoundError) as excinfo:
exporter.export_as_pdf(
_pdf_export_request(
app=file_manager.app,
session_view=session_view,
webpdf=False,
)
)
assert "for PDF export" in str(excinfo.value)
@pytest.mark.asyncio
async def test_export_pdf_reports_execute_raster_render(
self,
temp_marimo_file: str,
session_view: SessionView,
) -> None:
events: list[PDFExportStatusEvent] = []
async def fake_run_app_until_completion(
*args: Any, **kwargs: Any
) -> tuple[SessionView, bool]:
del args, kwargs
return session_view, False
async def fake_collect_pdf_png_fallbacks(
request: Any,
) -> dict[str, str]:
status_callback = request.status_callback
assert status_callback is not None
status_callback(
PDFExportStatusEvent(
phase="raster",
message="rasterizing interactive outputs...",
total=2,
)
)
status_callback(
PDFExportStatusEvent(
phase="raster",
message="rasterizing interactive outputs...",
current=1,
total=2,
)
)
return {"cell-1": "data:image/png;base64,ZmFrZQ=="}
def fake_export_as_pdf(
self: Exporter, request: PDFExportRequest
) -> bytes:
del self
status_callback = request.status_callback
assert status_callback is not None
status_callback(
PDFExportStatusEvent(
phase="render",
message="rendering PDF via WebPDF...",
)
)
return b"mock_pdf"
with (
patch(
"marimo._export.file.run_notebook",
side_effect=fake_run_app_until_completion,
),
patch(
"marimo._export._pdf_raster.collect_pdf_png_fallbacks",
side_effect=fake_collect_pdf_png_fallbacks,
),
patch.object(
Exporter,
"export_as_pdf",
autospec=True,
side_effect=fake_export_as_pdf,
),
):
result = await export_pdf(
PDFFileExportRequest(
path=MarimoPath(temp_marimo_file),
options=PDFExportOptions(
webpdf=True,
preset="document",
include_inputs=False,
),
rasterization=PDFRasterizationOptions(enabled=True),
execution=NotebookExecutionOptions(
cli_args={},
argv=None,
),
status_callback=events.append,
)
)
assert result is not None
assert result.contents == b"mock_pdf"
assert result.did_error is False
assert [event.phase for event in events] == [
"execute",
"execute_complete",
"raster",
"raster",
"prepare",
"render",
"complete",
]
assert [event.message for event in events] == [
"executing notebook...",
"notebook execution finished.",
"rasterizing interactive outputs...",
"rasterizing interactive outputs...",
"serializing notebook for PDF rendering...",
"rendering PDF via WebPDF...",
"done.",
]
@pytest.mark.asyncio
async def test_export_pdf_reports_render_only_without_outputs(
self,
temp_marimo_file: str,
) -> None:
events: list[PDFExportStatusEvent] = []
def fake_export_as_pdf(
self: Exporter, request: PDFExportRequest
) -> bytes:
del self
status_callback = request.status_callback
assert status_callback is not None
status_callback(
PDFExportStatusEvent(
phase="render",
message="rendering PDF via standard exporter...",
)
)
return b"mock_pdf"
with (
patch(
"marimo._export.file.run_notebook",
side_effect=AssertionError(
"execution should not run without outputs"
),
),
patch(
"marimo._export._pdf_raster.collect_pdf_png_fallbacks",
side_effect=AssertionError(
"rasterization should not run without outputs"
),
),
patch.object(
Exporter,
"export_as_pdf",
autospec=True,
side_effect=fake_export_as_pdf,
),
):
result = await export_pdf(
PDFFileExportRequest(
path=MarimoPath(temp_marimo_file),
options=PDFExportOptions(
webpdf=False,
preset="document",
include_inputs=False,
),
rasterization=PDFRasterizationOptions(enabled=False),
status_callback=events.append,
)
)
assert result is not None
assert result.contents == b"mock_pdf"
assert result.did_error is False
assert [(event.phase, event.message) for event in events] == [
("prepare", "serializing notebook for PDF rendering..."),
("render", "rendering PDF via standard exporter..."),
("complete", "done."),
]
@pytest.mark.skipif(
not HAS_NBFORMAT or not DependencyManager.nbconvert.has(),
reason="nbformat and nbconvert are required to render ipynb",
)
def test_hide_code_cells_are_stripped_by_nbconvert(self) -> None:
"""End-to-end check that `hide_code=True` cells are excluded from
rendered nbconvert output (LaTeX/HTML/Slides) via the `remove-input`
tag wired up in `Exporter`.
Regression test for marimo-team/marimo#9523.
"""
import nbformat
from marimo._convert.ipynb.from_ir import convert_from_ir_to_ipynb
from marimo._export.exporter import (
_nbconvert_tag_remove_config,
)
app = App()
@app.cell(hide_code=True)
def _():
shouldnotappear = "hidden"
return (shouldnotappear,)
@app.cell()
def _():
shouldappear = "visible"
return (shouldappear,)
ipynb = convert_from_ir_to_ipynb(
InternalApp(app), sort_mode="top-down"
)
notebook = nbformat.reads(ipynb, as_version=4)
config = _nbconvert_tag_remove_config()
from nbconvert import HTMLExporter, LatexExporter, SlidesExporter
for exporter_cls in (LatexExporter, HTMLExporter, SlidesExporter):
rendered, _ = exporter_cls(config=config).from_notebook_node(
notebook
)
assert "shouldnotappear" not in rendered, (
f"{exporter_cls.__name__} did not strip the hidden cell source"
)
assert "shouldappear" in rendered, (
f"{exporter_cls.__name__} dropped the visible cell source"
)
@pytest.mark.skipif(
not HAS_NBFORMAT or not DependencyManager.nbconvert.has(),
reason="nbformat and nbconvert are required to render ipynb",
)
def test_webpdf_inlines_code_wrapping_css(self) -> None:
"""WebPDF export inlines CSS that wraps long code lines.
JupyterLab's stylesheet clips the code input area, so long lines were
silently truncated in the PDF instead of wrapping.
Regression test for marimo-team/marimo#9421.
"""
import nbformat
from marimo._export._nbconvert import (
_render_webpdf_html,
)
notebook = nbformat.v4.new_notebook()
notebook.cells = [
nbformat.v4.new_code_cell(
"# a comment long enough to run past the printable width of a "
"PDF page and get clipped"
)
]
html = _render_webpdf_html(
notebook, include_inputs=True, filename=None
)
assert ".jp-InputArea-editor .highlight pre" in html
assert "white-space: pre-wrap !important" in html
assert "overflow-wrap: anywhere !important" in html
@pytest.mark.asyncio
async def test_export_pdf_ignores_status_callback_failures(
self,
temp_marimo_file: str,
) -> None:
def failing_status_callback(event: PDFExportStatusEvent) -> None:
raise RuntimeError(f"boom:{event.phase}")
def fake_export_as_pdf(
self: Exporter, *args: Any, **kwargs: Any
) -> bytes:
del self, args, kwargs
return b"mock_pdf"
with (
patch(
"marimo._export.file.run_notebook",
side_effect=AssertionError(
"execution should not run without outputs"
),
),
patch(
"marimo._export._pdf_raster.collect_pdf_png_fallbacks",
side_effect=AssertionError(
"rasterization should not run without outputs"
),
),
patch.object(
Exporter,
"export_as_pdf",
autospec=True,
side_effect=fake_export_as_pdf,
),
):
result = await export_pdf(
PDFFileExportRequest(
path=MarimoPath(temp_marimo_file),
options=PDFExportOptions(
webpdf=False,
preset="document",
include_inputs=False,
),
rasterization=PDFRasterizationOptions(enabled=False),
status_callback=failing_status_callback,
)
)
assert result is not None
assert result.contents == b"mock_pdf"
assert result.did_error is False
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
or not DependencyManager.nbconvert.has()
or not DependencyManager.playwright.has(),
reason="nbformat or nbconvert or playwright not installed",
)
def test_export_as_pdf_non_webpdf_mode(
self,
session_view: SessionView,
) -> None:
"""Test PDF export in non-webpdf mode (mocked)."""
app = App()
@app.cell()
def test_cell():
return "test"
file_manager = AppFileManager.from_app(InternalApp(app))
exporter = Exporter()
# Mock PDFExporter to avoid requiring LaTeX
mock_exporter_instance = MagicMock()
mock_exporter_instance.from_notebook_node.return_value = (
b"mock_pdf_data",
{},
)
with patch("nbconvert.PDFExporter") as mock_pdf_exporter:
mock_pdf_exporter.return_value = mock_exporter_instance
result = exporter.export_as_pdf(
_pdf_export_request(
app=file_manager.app,
session_view=session_view,
webpdf=False,
)
)
assert result == b"mock_pdf_data"
mock_pdf_exporter.assert_called_once()
mock_exporter_instance.from_notebook_node.assert_called_once()
assert mock_exporter_instance.exclude_input is False
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
or not DependencyManager.nbconvert.has(),
reason="nbformat or nbconvert not installed",
)
def test_export_as_pdf_webpdf_mode(
self,
session_view: SessionView,
) -> None:
"""Test PDF export in webpdf mode (mocked)."""
from bs4 import BeautifulSoup
app = App()
@app.cell()
def test_cell():
return "test"
file_manager = AppFileManager.from_app(InternalApp(app))
exporter = Exporter()
mock_exporter_instance = MagicMock()
mock_exporter_instance.run_playwright.return_value = (
b"mock_webpdf_data"
)
with (
patch.object(DependencyManager, "require_many"),
patch.object(sys, "platform", "linux"),
patch("nbconvert.WebPDFExporter") as mock_webpdf_exporter,
):
mock_webpdf_exporter.return_value = mock_exporter_instance
result = exporter.export_as_pdf(
_pdf_export_request(
app=file_manager.app,
session_view=session_view,
webpdf=True,
)
)
assert result == b"mock_webpdf_data"
mock_webpdf_exporter.assert_called_once_with(
allow_chromium_download=True
)
html = BeautifulSoup(
mock_exporter_instance.run_playwright.call_args.args[0],
"html.parser",
)
assert html.select_one(".jp-InputArea") is not None
@pytest.mark.skipif(
sys.platform != "win32" or not DependencyManager.nbformat.has(),
reason="requires Windows and nbformat",
)
def test_webpdf_render_preserves_parent_event_loop_policy(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
import nbformat
from marimo._export._nbconvert import _render_webpdf
(tmp_path / "nbconvert.py").write_text(
textwrap.dedent(
"""
class HTMLExporter:
def __init__(self, config, template_name):
self.config = config
self.preprocessors = []
def register_preprocessor(self, preprocessor, enabled=False):
self.preprocessors.append((preprocessor, enabled))
def from_notebook_node(self, notebook):
return "<html></html>", {}
class WebPDFExporter:
def __init__(self, allow_chromium_download):
pass
def run_playwright(self, html):
return b"mock_webpdf_data"
"""
),
encoding="utf-8",
)
monkeypatch.syspath_prepend(str(tmp_path))
with (
patch.object(
asyncio, "set_event_loop_policy"
) as set_event_loop_policy,
):
result = _render_webpdf(
nbformat.v4.new_notebook(), # type: ignore[no-untyped-call]
include_inputs=True,
)
assert result == b"mock_webpdf_data"
set_event_loop_policy.assert_not_called()
@pytest.mark.skipif(
sys.platform != "win32" or not DependencyManager.nbconvert.has(),
reason="requires Windows and nbconvert",
)
def test_webpdf_worker_can_spawn_subprocess_on_windows(self) -> None:
from marimo._export._nbconvert import (
_print_webpdf,
)
async def spawn_process() -> None:
process = await asyncio.create_subprocess_exec(
sys.executable, "-c", "pass"
)
assert await process.wait() == 0
mock_exporter_instance = MagicMock()
def render(*_args: Any, **_kwargs: Any) -> bytes:
with ThreadPoolExecutor(max_workers=1) as pool:
pool.submit(asyncio.run, spawn_process()).result()
return b"mock_webpdf_data"
mock_exporter_instance.run_playwright.side_effect = render
original_policy = asyncio.get_event_loop_policy()
selector_policy = asyncio.WindowsSelectorEventLoopPolicy()
asyncio.set_event_loop_policy(selector_policy)
try:
with patch(
"nbconvert.WebPDFExporter", create=True
) as mock_webpdf_exporter:
mock_webpdf_exporter.return_value = mock_exporter_instance
result = _print_webpdf("<html></html>")
assert result == b"mock_webpdf_data"
finally:
asyncio.set_event_loop_policy(original_policy)
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
or not DependencyManager.nbconvert.has(),
reason="nbformat or nbconvert not installed",
)
def test_export_as_pdf_webpdf_mode_without_inputs(
self,
session_view: SessionView,
) -> None:
"""Test WebPDF export suppressing code inputs."""
from bs4 import BeautifulSoup
app = App()
@app.cell()
def test_cell():
return "test"
file_manager = AppFileManager.from_app(InternalApp(app))
exporter = Exporter()
mock_exporter_instance = MagicMock()
mock_exporter_instance.run_playwright.return_value = (
b"mock_webpdf_data_no_inputs"
)
with (
patch.object(DependencyManager, "require_many"),
patch.object(sys, "platform", "linux"),
patch("nbconvert.WebPDFExporter") as mock_webpdf_exporter,
):
mock_webpdf_exporter.return_value = mock_exporter_instance
result = exporter.export_as_pdf(
_pdf_export_request(
app=file_manager.app,
session_view=session_view,
include_inputs=False,
webpdf=True,
)
)
assert result == b"mock_webpdf_data_no_inputs"
mock_webpdf_exporter.assert_called_once_with(
allow_chromium_download=True
)
html = BeautifulSoup(
mock_exporter_instance.run_playwright.call_args.args[0],
"html.parser",
)
assert html.select_one(".jp-InputArea") is None
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
or not DependencyManager.nbconvert.has(),
reason="nbformat or nbconvert not installed",
)
def test_export_as_pdf_returns_none_on_invalid_data(
self,
session_view: SessionView,
) -> None:
"""Test PDF export returns None when exporter returns non-bytes data."""
app = App()
@app.cell()
def test_cell():
return "test"
file_manager = AppFileManager.from_app(InternalApp(app))
exporter = Exporter()
# Mock PDFExporter to return invalid data
mock_exporter_instance = MagicMock()
mock_exporter_instance.from_notebook_node.return_value = (
"not_bytes", # Invalid - should be bytes
{},
)
with (
patch.object(DependencyManager, "require_many"),
patch("nbconvert.PDFExporter") as mock_pdf_exporter,
):
mock_pdf_exporter.return_value = mock_exporter_instance
result = exporter.export_as_pdf(
_pdf_export_request(
app=file_manager.app,
session_view=session_view,
webpdf=False,
)
)
assert result is None
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
or not DependencyManager.nbconvert.has(),
reason="nbformat or nbconvert not installed",
)
def test_export_as_pdf_falls_back_to_webpdf_on_oserror(
self,
session_view: SessionView,
) -> None:
"""Test PDF export falls back to webpdf when standard PDF fails with OSError."""
app = App()
@app.cell()
def test_cell():
return "test"
file_manager = AppFileManager.from_app(InternalApp(app))
exporter = Exporter()
# Mock PDFExporter to raise OSError (pandoc/xelatex not found)
mock_pdf_exporter_instance = MagicMock()
mock_pdf_exporter_instance.from_notebook_node.side_effect = OSError(
"xelatex not found"
)
# Mock WebPDFExporter to succeed
mock_webpdf_exporter_instance = MagicMock()
mock_webpdf_exporter_instance.run_playwright.return_value = (
b"fallback_webpdf_data"
)
with (
patch.object(DependencyManager, "require_many"),
patch.object(sys, "platform", "linux"),
patch("nbconvert.PDFExporter") as mock_pdf_exporter,
patch("nbconvert.WebPDFExporter") as mock_webpdf_exporter,
):
mock_pdf_exporter.return_value = mock_pdf_exporter_instance
mock_webpdf_exporter.return_value = mock_webpdf_exporter_instance
result = exporter.export_as_pdf(
_pdf_export_request(
app=file_manager.app,
session_view=session_view,
include_inputs=False,
webpdf=False, # Request standard PDF, but it should fall back
)
)
# Should fall back to webpdf and succeed
assert result == b"fallback_webpdf_data"
# PDFExporter was tried first
mock_pdf_exporter.assert_called_once()
mock_pdf_exporter_instance.from_notebook_node.assert_called_once()
assert mock_pdf_exporter_instance.exclude_input is True
# WebPDFExporter was used as fallback
mock_webpdf_exporter.assert_called_once_with(
allow_chromium_download=True
)
mock_webpdf_exporter_instance.run_playwright.assert_called_once()
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
or not DependencyManager.nbconvert.has(),
reason="nbformat or nbconvert not installed",
)
def test_export_as_pdf_falls_back_to_webpdf_on_conversion_error(
self,
session_view: SessionView,
) -> None:
"""Test PDF export falls back to webpdf when pandoc is missing."""
from nbconvert.utils.pandoc import (
PandocMissing, # type: ignore[import-not-found]
)
app = App()
@app.cell()
def test_cell():
return "test"
file_manager = AppFileManager.from_app(InternalApp(app))
exporter = Exporter()
mock_pdf_exporter_instance = MagicMock()
mock_pdf_exporter_instance.from_notebook_node.side_effect = (
PandocMissing()
)
mock_webpdf_exporter_instance = MagicMock()
mock_webpdf_exporter_instance.run_playwright.return_value = (
b"fallback_webpdf_data"
)
with (
patch.object(DependencyManager, "require_many"),
patch.object(sys, "platform", "linux"),
patch("nbconvert.PDFExporter") as mock_pdf_exporter,
patch("nbconvert.WebPDFExporter") as mock_webpdf_exporter,
):
mock_pdf_exporter.return_value = mock_pdf_exporter_instance
mock_webpdf_exporter.return_value = mock_webpdf_exporter_instance
result = exporter.export_as_pdf(
_pdf_export_request(
app=file_manager.app,
session_view=session_view,
webpdf=False,
)
)
assert result == b"fallback_webpdf_data"
mock_pdf_exporter.assert_called_once()
mock_pdf_exporter_instance.from_notebook_node.assert_called_once()
mock_webpdf_exporter.assert_called_once_with(
allow_chromium_download=True
)
mock_webpdf_exporter_instance.run_playwright.assert_called_once()
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
or not DependencyManager.nbconvert.has(),
reason="nbformat or nbconvert not installed",
)
def test_export_as_pdf_falls_back_to_webpdf_on_unexpected_error(
self,
session_view: SessionView,
) -> None:
"""Test PDF export falls back to webpdf and logs error on unexpected exceptions."""
app = App()
@app.cell()
def test_cell():
return "test"
file_manager = AppFileManager.from_app(InternalApp(app))
exporter = Exporter()
mock_pdf_exporter_instance = MagicMock()
mock_pdf_exporter_instance.from_notebook_node.side_effect = (
RuntimeError("unexpected template error")
)
mock_webpdf_exporter_instance = MagicMock()
mock_webpdf_exporter_instance.run_playwright.return_value = (
b"fallback_webpdf_data"
)
with (
patch.object(DependencyManager, "require_many"),
patch.object(sys, "platform", "linux"),
patch("nbconvert.PDFExporter") as mock_pdf_exporter,
patch("nbconvert.WebPDFExporter") as mock_webpdf_exporter,
):
mock_pdf_exporter.return_value = mock_pdf_exporter_instance
mock_webpdf_exporter.return_value = mock_webpdf_exporter_instance
result = exporter.export_as_pdf(
_pdf_export_request(
app=file_manager.app,
session_view=session_view,
webpdf=False,
)
)
assert result == b"fallback_webpdf_data"
mock_pdf_exporter.assert_called_once()
mock_webpdf_exporter.assert_called_once_with(
allow_chromium_download=True
)
@pytest.mark.skipif(
not DependencyManager.nbformat.has()
or not DependencyManager.nbconvert.has(),
reason="nbformat or nbconvert not installed",
)
def test_export_as_pdf_reports_status_during_fallback_to_webpdf(
self,
session_view: SessionView,
) -> None:
app = App()
@app.cell()
def test_cell():
return "test"
file_manager = AppFileManager.from_app(InternalApp(app))
exporter = Exporter()
events: list[PDFExportStatusEvent] = []
mock_pdf_exporter_instance = MagicMock()
mock_pdf_exporter_instance.from_notebook_node.side_effect = OSError(
"xelatex not found"
)
mock_webpdf_exporter_instance = MagicMock()
mock_webpdf_exporter_instance.run_playwright.return_value = (
b"fallback_webpdf_data"
)
with (
patch.object(DependencyManager, "require_many"),
patch.object(sys, "platform", "linux"),
patch("nbconvert.PDFExporter") as mock_pdf_exporter,
patch("nbconvert.WebPDFExporter") as mock_webpdf_exporter,
):
mock_pdf_exporter.return_value = mock_pdf_exporter_instance
mock_webpdf_exporter.return_value = mock_webpdf_exporter_instance
result = exporter.export_as_pdf(
_pdf_export_request(
app=file_manager.app,
session_view=session_view,
webpdf=False,
status_callback=events.append,
)
)
assert result == b"fallback_webpdf_data"
assert [(event.phase, event.message) for event in events] == [
("render", "rendering PDF via standard exporter..."),
(
"render_fallback",
"standard PDF export failed; falling back to WebPDF...",
),
("render", "rendering PDF via WebPDF..."),
]
@pytest.mark.skipif(
not DependencyManager.nbformat.has(),
reason="nbformat not installed",
)
async def test_export_as_slides_pdf(
self,
session_view: SessionView,
) -> None:
"""Test slides PDF export uses SlidesExporter + async Playwright."""
app = App()
@app.cell()
def slide_1():
return "slide 1"
@app.cell()
def slide_2():
return "slide 2"
file_manager = AppFileManager.from_app(InternalApp(app))
exporter = Exporter()
mock_slides_exporter_instance = MagicMock()
mock_slides_exporter_instance.from_notebook_node.return_value = (
"<html>mock slides html</html>",
{},
)
mock_slides_exporter_cls = MagicMock(
return_value=mock_slides_exporter_instance
)
mock_page = AsyncMock()
mock_page.pdf.return_value = b"mock_slides_pdf_data"
mock_browser = AsyncMock()
mock_browser.new_page.return_value = mock_page
mock_playwright_instance = AsyncMock()
mock_playwright_instance.chromium.launch.return_value = mock_browser
mock_playwright_cm = AsyncMock()
mock_playwright_cm.__aenter__.return_value = mock_playwright_instance
mock_playwright_cm.__aexit__.return_value = False
mock_async_playwright = MagicMock(return_value=mock_playwright_cm)
mock_nbconvert = MagicMock()
mock_nbconvert.SlidesExporter = mock_slides_exporter_cls
mock_playwright_async = MagicMock()
mock_playwright_async.async_playwright = mock_async_playwright
orig_nbconvert = sys.modules.get("nbconvert")
orig_playwright = sys.modules.get("playwright.async_api")
try:
sys.modules["nbconvert"] = mock_nbconvert
sys.modules["playwright.async_api"] = mock_playwright_async
with (
patch.object(
DependencyManager.nbconvert, "has", return_value=True
),
patch.object(
DependencyManager.playwright, "has", return_value=True
),
):
events: list[PDFExportStatusEvent] = []
result = await exporter.export_as_slides_pdf(
_pdf_export_request(
app=file_manager.app,
session_view=session_view,
status_callback=events.append,
preset="slides",
)
)
assert result == b"mock_slides_pdf_data"
assert [(event.phase, event.message) for event in events] == [
("render", "rendering slides PDF...")
]
mock_slides_exporter_cls.assert_called_once()
mock_slides_exporter_instance.from_notebook_node.assert_called_once()
notebook = (
mock_slides_exporter_instance.from_notebook_node.call_args[0][
0
]
)
slide_types = [
cell.metadata.get("slideshow", {}).get("slide_type")
for cell in notebook.cells
]
assert slide_types
assert set(slide_types) == {"slide"}
mock_page.goto.assert_called_once()
goto_url = mock_page.goto.call_args[0][0]
assert goto_url.startswith("file://")
assert "?print-pdf" in goto_url
assert mock_page.evaluate.await_count >= 1
mock_page.wait_for_timeout.assert_called_once_with(300)
mock_page.add_style_tag.assert_called_once()
mock_page.pdf.assert_called_once_with(
print_background=True,
prefer_css_page_size=True,
)
finally:
if orig_nbconvert is not None:
sys.modules["nbconvert"] = orig_nbconvert
else:
sys.modules.pop("nbconvert", None)
if orig_playwright is not None:
sys.modules["playwright.async_api"] = orig_playwright
else:
sys.modules.pop("playwright.async_api", None)
@pytest.mark.skipif(
not DependencyManager.nbformat.has(),
reason="nbformat not installed",
)
async def test_export_as_slides_pdf_marks_all_slides_without_inputs(
self,
session_view: SessionView,
) -> None:
app = App()
@app.cell()
def slide_1():
value = 1
return value
@app.cell()
def slide_2():
value = 2
return value
file_manager = AppFileManager.from_app(InternalApp(app))
exporter = Exporter()
mock_slides_exporter_instance = MagicMock()
mock_slides_exporter_instance.from_notebook_node.return_value = (
"<html>mock slides html</html>",
{},
)
mock_slides_exporter_cls = MagicMock(
return_value=mock_slides_exporter_instance
)
mock_page = AsyncMock()
mock_page.pdf.return_value = b"mock_slides_pdf_data"
mock_browser = AsyncMock()
mock_browser.new_page.return_value = mock_page
mock_playwright_instance = AsyncMock()
mock_playwright_instance.chromium.launch.return_value = mock_browser
mock_playwright_cm = AsyncMock()
mock_playwright_cm.__aenter__.return_value = mock_playwright_instance
mock_playwright_cm.__aexit__.return_value = False
mock_async_playwright = MagicMock(return_value=mock_playwright_cm)
mock_nbconvert = MagicMock()
mock_nbconvert.SlidesExporter = mock_slides_exporter_cls
mock_playwright_async = MagicMock()
mock_playwright_async.async_playwright = mock_async_playwright
orig_nbconvert = sys.modules.get("nbconvert")
orig_playwright = sys.modules.get("playwright.async_api")
try:
sys.modules["nbconvert"] = mock_nbconvert
sys.modules["playwright.async_api"] = mock_playwright_async
with (
patch.object(
DependencyManager.nbconvert, "has", return_value=True
),
patch.object(
DependencyManager.playwright, "has", return_value=True
),
):
result = await exporter.export_as_slides_pdf(
_pdf_export_request(
app=file_manager.app,
session_view=session_view,
include_inputs=False,
preset="slides",
)
)
assert result == b"mock_slides_pdf_data"
notebook = (
mock_slides_exporter_instance.from_notebook_node.call_args[0][
0
]
)
slide_types = [
cell.metadata.get("slideshow", {}).get("slide_type")
for cell in notebook.cells
]
assert set(slide_types) == {"skip"}
mock_page.pdf.assert_called_once_with(
print_background=True,
prefer_css_page_size=True,
)
finally:
if orig_nbconvert is not None:
sys.modules["nbconvert"] = orig_nbconvert
else:
sys.modules.pop("nbconvert", None)
if orig_playwright is not None:
sys.modules["playwright.async_api"] = orig_playwright
else:
sys.modules.pop("playwright.async_api", None)
@pytest.mark.skipif(not HAS_NBFORMAT, reason="nbformat not installed")
async def test_export_as_slides_pdf_inlines_images_and_png_fallbacks(
session_view: SessionView,
) -> None:
app = App()
@app.cell()
def image_slide():
return "image"
@app.cell()
def interactive_slide():
return "interactive"
internal_app = InternalApp(app)
image_id, interactive_id = internal_app.cell_manager.cell_ids()
image_data = {
"text/html": '<img src="./@file/4-plot.png">',
"text/plain": "literal ./@file/4-plot.png",
"image/png": "bmF0aXZl",
}
session_view.add_notification(
CellNotification(
cell_id=image_id,
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="application/vnd.marimo+mimebundle",
data=image_data,
),
console=[CellOutput.stdout("console ./@file/4-plot.png")],
)
)
session_view.add_notification(
CellNotification(
cell_id=interactive_id,
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/html",
data="<marimo-slider></marimo-slider>",
),
)
)
with (
patch.object(DependencyManager.nbconvert, "has", return_value=True),
patch.object(DependencyManager.playwright, "has", return_value=True),
patch(
"marimo._convert.common.dom_traversal.read_virtual_file",
return_value=b"plot",
),
patch.object(
Exporter, "_export_slides_as_pdf", new_callable=AsyncMock
) as render,
):
render.return_value = b"pdf"
result = await Exporter().export_as_slides_pdf(
_pdf_export_request(
app=internal_app,
session_view=session_view,
png_fallbacks={
interactive_id: "data:image/png;base64,Y2FwdHVyZWQ=",
},
preset="slides",
)
)
assert result == b"pdf"
notebook = render.await_args.args[0]
assert notebook.cells[0].id == image_id
assert notebook.cells[0].outputs[1].data == {
**image_data,
"text/html": '<img src="data:image/png;base64,cGxvdA==">',
}
assert notebook.cells[0].outputs[0].text == "console ./@file/4-plot.png"
assert notebook.cells[1].id == interactive_id
assert notebook.cells[1].outputs[0].data == {
"image/png": "Y2FwdHVyZWQ=",
}
assert session_view.cell_notifications[image_id].output.data == image_data
@pytest.mark.skipif(
sys.platform == "win32",
reason="Unix permission bits not supported on Windows",
)
def test_export_assets_preserves_write_permission(
tmp_path: Path,
) -> None:
"""Test export_assets keeps output writable when source is read-only."""
import stat
src = tmp_path / "nix-store" / "_static"
src.mkdir(parents=True)
(src / "file.txt").write_text("hello")
sub = src / "assets"
sub.mkdir()
(sub / "nested.txt").write_text("marimo")
# 555 simulates /nix/store permissions
src.chmod(0o555)
sub.chmod(0o555)
dest = tmp_path / "output"
dest.mkdir()
with patch("marimo._export.exporter.ROOT", src):
Exporter().export_assets(dest)
assert dest.stat().st_mode & stat.S_IWUSR, (
"export_assets made the output directory read-only"
)
assert (dest / "assets").stat().st_mode & stat.S_IWUSR, (
"export_assets made the assets subdirectory read-only"
)
async def test_export_wasm_unexecuted_pins_header_to_pyodide_lock(
tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""The default (unexecuted) export rewrites bundled pins to the lock.
Specifiers on packages Pyodide does not ship are preserved.
"""
lockfile = tmp_path / "pyodide-lock.json"
lockfile.write_text(
json.dumps(
{
"packages": {
"numpy": {
"name": "numpy",
"version": "2.4.3",
"package_type": "package",
}
}
}
)
)
monkeypatch.setenv("MARIMO_PYODIDE_LOCK_FILE", str(lockfile))
monkeypatch.delenv("MARIMO_HTML_WASM_SANDBOX_BOOTSTRAPPED", raising=False)
notebook = tmp_path / "notebook.py"
notebook.write_text(
textwrap.dedent(
"""
# /// script
# dependencies = [
# "numpy==1.26.0",
# "emoji",
# "nltools==0.6.0.dev2",
# ]
# ///
import marimo
__generated_with = "0.0.0"
app = marimo.App()
@app.cell
def _():
import emoji
return
if __name__ == "__main__":
app.run()
"""
).lstrip()
)
result = await export_wasm(
WASMFileExportRequest(
path=MarimoPath(notebook),
options=WASMExportOptions(mode="run", show_code=True),
)
)
assert result.did_error is False
assert "numpy==2.4.3" in result.text
assert "numpy==1.26.0" not in result.text
assert "nltools==0.6.0.dev2" in result.text
assert 'lock_kind = \\"observed\\"' in result.text
async def test_export_wasm_offline_resolves_header_as_written(
tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Offline exports resolve the header against their own lockfile."""
lockfile = tmp_path / "pyodide-lock.json"
lockfile.write_text(
json.dumps(
{
"packages": {
"numpy": {
"name": "numpy",
"version": "2.4.3",
"package_type": "package",
}
}
}
)
)
monkeypatch.setenv("MARIMO_PYODIDE_LOCK_FILE", str(lockfile))
notebook = tmp_path / "notebook.py"
notebook.write_text(
textwrap.dedent(
"""
# /// script
# dependencies = ["numpy", "pandas>=2"]
# ///
import marimo
__generated_with = "0.0.0"
app = marimo.App()
if __name__ == "__main__":
app.run()
"""
).lstrip()
)
async def bundle(code: str, *_args: Any, sources: Any, **_kwargs: Any):
return code, sources
with patch(
"marimo._export.offline.bundle_wasm_runtime",
AsyncMock(side_effect=bundle),
) as bundle_wasm_runtime:
result = await export_wasm(
WASMFileExportRequest(
path=MarimoPath(notebook),
options=WASMExportOptions(mode="run", show_code=True),
offline_export_dir=tmp_path / "dist",
)
)
assert result.did_error is False
bundled_code = bundle_wasm_runtime.await_args.args[0]
assert 'dependencies = ["numpy", "pandas>=2"]' in bundled_code