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.

Fix dependency installation in island payloads (#10832)

Myles Scolnick1495aa794c1c
diff --git a/docs/guides/exporting/webassembly_html.md b/docs/guides/exporting/webassembly_html.md
index 1b6791a9a6..c17bdde207 100644
--- a/docs/guides/exporting/webassembly_html.md
+++ b/docs/guides/exporting/webassembly_html.md
@@ -413,9 +413,13 @@ Any relevant `.html` that gets generated can be run through the [`development.md
### Island payloads
-`MarimoIslandGenerator.render_html(include_payload=True)` and `render_body(include_payload=True)` include a JSON payload. The payload stores each cell's code, rendered output HTML, output MIME type, and display settings.
+Use `render_html(include_payload=True)` or `render_body(include_payload=True)` to include a JSON payload. For custom layouts, include `render_payload_script()` alongside the rendered islands.
-The islands runtime uses this payload to hydrate the page. The DOM still provides the visible island slots, and the payload provides the runtime cell code and output metadata.
+The payload supplies cell code, output HTML, MIME types, and display settings for the island elements. For notebooks loaded with `from_file`, it also carries declared dependencies. Pyodide evaluates dependency markers in its own Python environment and installs applicable packages before it runs the cells.
+
+Declare PyPI packages such as `cowsay` in the notebook's PEP 723 block. Imports alone do not add PyPI packages to the payload.
+
+Markdown and QMD notebooks can declare dependencies in the `pyproject` or `header` frontmatter field. When both fields define metadata, `pyproject` takes precedence.
An emitted payload looks like this. HTML-sensitive characters inside JSON strings are escaped before marimo writes the script tag.
diff --git a/frontend/src/core/islands/__tests__/parse.test.ts b/frontend/src/core/islands/__tests__/parse.test.ts
index 96ecef186e..4eb4c7d99f 100644
--- a/frontend/src/core/islands/__tests__/parse.test.ts
+++ b/frontend/src/core/islands/__tests__/parse.test.ts
@@ -19,6 +19,13 @@ import {
} from "../parse";
import { createMockIslandElement, createMockIslands } from "./test-utils.tsx";
+function islandSnapshotPath(filename: string): string {
+ return new URL(
+ `../../../../../tests/_islands/snapshots/${filename}`,
+ import.meta.url,
+ ).pathname.replace(/^\/@fs/, "");
+}
+
function createPayloadCell(
overrides: Partial<{
cellId: string;
@@ -47,6 +54,7 @@ function appendPayload(
payload: {
schemaVersion: number;
appId: string;
+ dependencies?: unknown;
cells: ReturnType<typeof createPayloadCell>[];
},
) {
@@ -58,6 +66,33 @@ function appendPayload(
}
describe("createMarimoFile", () => {
+ it("should serialize dependencies as top-level script metadata", () => {
+ const file = createMarimoFile({
+ dependencies: ['cowsay==6.1; sys_platform == "emscripten"'],
+ cells: [{ code: "import cowsay" }],
+ });
+ expect(file).toBe(
+ [
+ "# /// script",
+ '# dependencies = ["cowsay==6.1; sys_platform == \\"emscripten\\""]',
+ "# ///",
+ "import marimo",
+ "app = marimo.App()",
+ "@app.cell",
+ "def __():",
+ " import cowsay",
+ " return",
+ ].join("\n"),
+ );
+ });
+
+ it("should omit metadata for empty dependencies", () => {
+ const cells = [{ code: "import cowsay" }];
+ expect(createMarimoFile({ cells, dependencies: [] })).toBe(
+ createMarimoFile({ cells }),
+ );
+ });
+
it("should return a string", () => {
const app = {
cells: [
@@ -736,13 +771,7 @@ describe("parseMarimoIslandApps", () => {
});
it("should parse Python-generated island payload snapshots", () => {
- const html = readFileSync(
- new URL(
- "../../../../../tests/_islands/snapshots/html-payload.txt",
- import.meta.url,
- ).pathname.replace(/^\/@fs/, ""),
- "utf8",
- );
+ const html = readFileSync(islandSnapshotPath("html-payload.txt"), "utf8");
container.innerHTML = html;
const result = parseMarimoIslandApps(container);
@@ -775,6 +804,108 @@ describe("parseMarimoIslandApps", () => {
expect(islands[2].getAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX)).toBe("1");
});
+ it("should restore metadata from a Python-generated dependency payload", () => {
+ container.innerHTML = readFileSync(
+ islandSnapshotPath("body-dependencies.txt"),
+ "utf8",
+ );
+
+ const probed = parseMarimoIslandApps(container, { materialize: false });
+ const apps = parseMarimoIslandApps(container);
+
+ expect(probed).toEqual(apps);
+ expect(apps).toEqual([
+ {
+ id: "main",
+ payloadBacked: true,
+ dependencies: [
+ 'cowsay==6.1; sys_platform == "emscripten"',
+ "rich[jupyter]>=13",
+ "desktop; sys_platform != 'emscripten'",
+ "older-python; python_version < '3.13'",
+ "newer-python; python_version >= '3.13'",
+ ],
+ cells: [{ cellId: "Hbol", code: "import cowsay", output: "", idx: 0 }],
+ },
+ ]);
+ // The Python Pyodide test reads this file with the real metadata parser.
+ expect(createMarimoFile(apps[0])).toBe(
+ readFileSync(islandSnapshotPath("notebook-dependencies.txt"), "utf8"),
+ );
+ });
+
+ it("should carry dependencies from payloads into each generated notebook", () => {
+ for (const [appId, dependencies] of [
+ ["app1", ["cowsay==6.1"]],
+ ["app2", ["rich[jupyter]>=13"]],
+ ] as const) {
+ container.appendChild(
+ createMockIslandElement({ appId, cellId: "cell-1" }),
+ );
+ appendPayload(container, {
+ schemaVersion: 1,
+ appId,
+ dependencies,
+ cells: [createPayloadCell()],
+ });
+ }
+
+ const apps = parseMarimoIslandApps(container);
+ expect(apps.map((app) => [app.id, app.dependencies])).toEqual([
+ ["app1", ["cowsay==6.1"]],
+ ["app2", ["rich[jupyter]>=13"]],
+ ]);
+ expect(createMarimoFile(apps[0])).toContain(
+ '# /// script\n# dependencies = ["cowsay==6.1"]\n# ///\n',
+ );
+ });
+
+ it.each([null, "cowsay", [123], ["cowsay", null]])(
+ "should ignore payloads with malformed dependencies: %j",
+ (dependencies) => {
+ const island = createMockIslandElement({
+ appId: "app1",
+ cellId: "cell-1",
+ code: "import cowsay",
+ innerHTML: "<div>dom</div>",
+ });
+ island.setAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE, "true");
+ container.appendChild(island);
+ appendPayload(container, {
+ schemaVersion: 1,
+ appId: "app1",
+ dependencies,
+ cells: [createPayloadCell()],
+ });
+
+ expect(parseMarimoIslandApps(container)).toEqual([
+ {
+ id: "app1",
+ cells: [{ code: "import cowsay", output: "<div>dom</div>", idx: 0 }],
+ },
+ ]);
+ },
+ );
+
+ it("should merge dependencies from payloads belonging to the same app", () => {
+ for (const [cellId, dependencies] of [
+ ["cell-1", ["cowsay"]],
+ ["cell-2", ["cowsay", "rich"]],
+ ] as const) {
+ container.appendChild(createMockIslandElement({ appId: "app1", cellId }));
+ appendPayload(container, {
+ schemaVersion: 1,
+ appId: "app1",
+ dependencies,
+ cells: [createPayloadCell({ cellId })],
+ });
+ }
+
+ expect(
+ parseMarimoIslandApps(container).map((app) => app.dependencies),
+ ).toEqual([["cowsay", "rich"]]);
+ });
+
it("should fall back to DOM islands for unsupported payload versions", () => {
const island = createMockIslandElement({
appId: "app1",
@@ -990,6 +1121,7 @@ describe("parseMarimoIslandApps", () => {
outputHtml: "<div>payload only</div>",
}),
],
+ dependencies: ["cowsay"],
});
const result = parseMarimoIslandApps(container);
@@ -1076,6 +1208,7 @@ describe("parseMarimoIslandApps", () => {
reactive: false,
}),
],
+ dependencies: ["cowsay"],
});
const result = parseMarimoIslandApps(container);
diff --git a/frontend/src/core/islands/parse.ts b/frontend/src/core/islands/parse.ts
index d6237caa16..9b1987a93d 100644
--- a/frontend/src/core/islands/parse.ts
+++ b/frontend/src/core/islands/parse.ts
@@ -30,6 +30,8 @@ export interface MarimoIslandApp {
* Whether cells came from a supported JSON payload instead of DOM parsing.
*/
payloadBacked?: boolean;
+ /** Explicit notebook dependencies to install before starting the app. */
+ dependencies?: string[];
/**
* Cells in the app.
*/
@@ -62,6 +64,7 @@ interface MarimoIslandCell {
interface MarimoIslandPayload {
schemaVersion: 1;
appId: string;
+ dependencies?: string[];
cells: MarimoIslandPayloadCell[];
}
@@ -235,6 +238,12 @@ function parsePayloadBackedApps({
embed?.setAttribute(ISLAND_DATA_ATTRIBUTES.CELL_IDX, idx.toString());
}
}
+ const app = apps.get(payload.appId);
+ if (app && payload.dependencies?.length) {
+ app.dependencies = [
+ ...new Set([...(app.dependencies ?? []), ...payload.dependencies]),
+ ];
+ }
}
// A supported payload is the runtime source for its app. Extra same-app DOM
@@ -371,6 +380,7 @@ export function parseIslandElement(
export function createMarimoFile(app: {
cells: { code: string; disabled?: boolean }[];
+ dependencies?: string[];
}): string {
const lines = [
"import marimo",
@@ -402,6 +412,13 @@ export function createMarimoFile(app: {
.join("\n"),
];
+ if (app.dependencies?.length) {
+ lines.unshift(
+ "# /// script",
+ `# dependencies = ${JSON.stringify(app.dependencies)}`,
+ "# ///",
+ );
+ }
return lines.join("\n");
}
@@ -507,6 +524,9 @@ function isMarimoIslandPayload(
return (
payload.schemaVersion === 1 &&
typeof payload.appId === "string" &&
+ (payload.dependencies === undefined ||
+ (Array.isArray(payload.dependencies) &&
+ payload.dependencies.every((dep) => typeof dep === "string"))) &&
Array.isArray(payload.cells) &&
payload.cells.every(isMarimoIslandPayloadCell)
);
diff --git a/marimo/_islands/_island_generator.py b/marimo/_islands/_island_generator.py
index 9556173737..1b0f7cee09 100644
--- a/marimo/_islands/_island_generator.py
+++ b/marimo/_islands/_island_generator.py
@@ -14,6 +14,7 @@ from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import Cell, CellConfig
from marimo._ast.compiler import compile_cell
from marimo._ast.load import load_notebook_ir
+from marimo._convert.script import _header_for_script
from marimo._messaging.cell_output import CellOutput
from marimo._output.utils import uri_encode_component
from marimo._schemas.islands import (
@@ -26,6 +27,7 @@ from marimo._schemas.serialization import NotebookSerialization
from marimo._session.notebook import AppFileManager, load_notebook
from marimo._templates import json_script
from marimo._types.ids import CellId_t
+from marimo._utils.inline_script_metadata import PyProjectReader
from marimo._utils.marimo_path import MarimoPath
from marimo._version import __version__
@@ -315,6 +317,7 @@ class MarimoIslandGenerator:
self._app = InternalApp(App())
self._stubs: list[MarimoIslandStub] = []
self._config = _AppConfig()
+ self._dependencies: list[str] = []
# When constructed via ``from_file``, this records the notebook
# source path so cells see ``__file__`` / ``mo.notebook_dir()``
# resolve to the notebook rather than to the host process.
@@ -357,6 +360,9 @@ class MarimoIslandGenerator:
generator._stubs = stubs
generator._config = file_manager.app.config
+ generator._dependencies = _notebook_dependencies(
+ file_manager.app.to_ir()
+ )
return generator
@@ -384,6 +390,7 @@ class MarimoIslandGenerator:
)
generator = MarimoIslandGenerator(app_id=app_id)
+ generator._dependencies = _notebook_dependencies(notebook)
generator._source_filename = source_filename
internal_app = InternalApp(app)
generator._app = internal_app
@@ -725,11 +732,14 @@ class MarimoIslandGenerator:
def render_payload(self) -> MarimoIslandPayload:
"""Return the JSON payload consumed by the islands runtime."""
- return {
+ payload: MarimoIslandPayload = {
"schemaVersion": ISLANDS_JSON_SCHEMA_VERSION,
"appId": self._app_id,
"cells": [stub.to_payload() for stub in self._stubs],
}
+ if self._dependencies:
+ payload["dependencies"] = self._dependencies.copy()
+ return payload
def render_payload_script(self) -> str:
"""Render the island app payload in a JSON script tag."""
@@ -737,6 +747,19 @@ class MarimoIslandGenerator:
return f'<script type="{ISLANDS_JSON_SCRIPT_TYPE}">{payload}</script>'
+def _notebook_dependencies(notebook: NotebookSerialization) -> list[str]:
+ if notebook.header is None:
+ return []
+ try:
+ reader = PyProjectReader.from_script(_header_for_script(notebook))
+ # Evaluate markers in Pyodide, whose Python version may differ
+ # from the exporter's.
+ return reader.dependencies
+ except Exception as e:
+ LOGGER.warning("Error parsing script metadata: %s", e)
+ return []
+
+
def remove_empty_lines(text: str) -> str:
return "\n".join([line for line in text.split("\n") if line.strip() != ""])
diff --git a/marimo/_schemas/islands.py b/marimo/_schemas/islands.py
index 0f4af5f1b2..ed8a34a931 100644
--- a/marimo/_schemas/islands.py
+++ b/marimo/_schemas/islands.py
@@ -1,8 +1,14 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import sys
from typing import Literal, TypedDict
+if sys.version_info >= (3, 11):
+ from typing import NotRequired
+else:
+ from typing_extensions import NotRequired
+
ISLANDS_JSON_SCRIPT_TYPE: str = "application/vnd.marimo.islands+json"
ISLANDS_JSON_SCHEMA_VERSION: Literal[1] = 1
@@ -20,4 +26,5 @@ class MarimoIslandCellPayload(TypedDict):
class MarimoIslandPayload(TypedDict):
schemaVersion: Literal[1]
appId: str
+ dependencies: NotRequired[list[str]]
cells: list[MarimoIslandCellPayload]
diff --git a/tests/_islands/snapshots/body-dependencies.txt b/tests/_islands/snapshots/body-dependencies.txt
new file mode 100644
index 0000000000..cd20a1b8a7
--- /dev/null
+++ b/tests/_islands/snapshots/body-dependencies.txt
@@ -0,0 +1,12 @@
+<div style="margin: auto; max-width: 740px;">
+ <marimo-island
+ data-app-id="main"
+ data-cell-id="Hbol"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ </marimo-cell-output>
+ <marimo-cell-code hidden>import%20cowsay</marimo-cell-code>
+</marimo-island>
+<script type="application/vnd.marimo.islands+json">{"appId": "main", "cells": [{"cellId": "Hbol", "code": "import cowsay", "displayCode": false, "displayOutput": true, "outputHtml": "", "outputMimetype": "text/plain", "reactive": true}], "dependencies": ["cowsay==6.1; sys_platform == \"emscripten\"", "rich[jupyter]\u003E=13", "desktop; sys_platform != 'emscripten'", "older-python; python_version \u003C '3.13'", "newer-python; python_version \u003E= '3.13'"], "schemaVersion": 1}</script>
+ </div>
\ No newline at end of file
diff --git a/tests/_islands/snapshots/notebook-dependencies.txt b/tests/_islands/snapshots/notebook-dependencies.txt
new file mode 100644
index 0000000000..4e58d924d6
--- /dev/null
+++ b/tests/_islands/snapshots/notebook-dependencies.txt
@@ -0,0 +1,9 @@
+# /// script
+# dependencies = ["cowsay==6.1; sys_platform == \"emscripten\"","rich[jupyter]>=13","desktop; sys_platform != 'emscripten'","older-python; python_version < '3.13'","newer-python; python_version >= '3.13'"]
+# ///
+import marimo
+app = marimo.App()
+def __():
+ import cowsay
+ return
\ No newline at end of file
diff --git a/tests/_islands/test_island_generator.py b/tests/_islands/test_island_generator.py
index fb78650517..d1fbf5fa2d 100644
--- a/tests/_islands/test_island_generator.py
+++ b/tests/_islands/test_island_generator.py
@@ -1,12 +1,16 @@
from __future__ import annotations
import json
+from textwrap import dedent
from typing import TYPE_CHECKING, get_type_hints
import pytest
+import yaml
from marimo import __version__
from marimo._ast.app_config import _AppConfig
+from marimo._convert.markdown.to_ir import convert_from_md_to_marimo_ir
+from marimo._environments import script_metadata
from marimo._islands._island_generator import MarimoIslandGenerator
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.errors import MarimoExceptionRaisedError
@@ -14,6 +18,7 @@ from marimo._schemas.islands import ISLANDS_JSON_SCRIPT_TYPE
from marimo._schemas.serialization import (
AppInstantiation,
CellDef,
+ Header,
NotebookSerialization,
)
from tests.mocks import snapshotter
@@ -141,6 +146,229 @@ async def test_render_payload():
assert payload["cells"][1]["reactive"] is True
[email protected]("from_file", [True, False])
+ ("header", "dependencies"),
+ [
+ ("", []),
+ ("# /// script\n# dependencies = []\n# ///\n", []),
+ ("# /// script\n# dependencies = [\n# ///\n", []),
+ (
+ script_metadata.dumps(
+ {"dependencies": ["desktop; sys_platform != 'emscripten'"]}
+ ),
+ ["desktop; sys_platform != 'emscripten'"],
+ ),
+ (
+ dedent("""\
+ # /// script
+ # dependencies = [
+ # "cowsay==6.1",
+ # "rich[jupyter]>=13",
+ # "pyodide-only; sys_platform == 'emscripten'",
+ # "desktop-only; sys_platform != 'emscripten'",
+ # ]
+ # ///
+ """),
+ [
+ "cowsay==6.1",
+ "rich[jupyter]>=13",
+ "pyodide-only; sys_platform == 'emscripten'",
+ "desktop-only; sys_platform != 'emscripten'",
+ ],
+ ),
+ (
+ script_metadata.dumps(
+ {
+ "dependencies": [
+ "older-python; python_version < '3.13'",
+ "newer-python; python_version >= '3.13'",
+ ]
+ }
+ ),
+ [
+ "older-python; python_version < '3.13'",
+ "newer-python; python_version >= '3.13'",
+ ],
+ ),
+ ],
+)
+def test_render_payload_dependencies(
+ tmp_path: Path,
+ from_file: bool,
+ header: str,
+ dependencies: list[str],
+) -> None:
+ if from_file:
+ path = tmp_path / "notebook.py"
+ path.write_text(
+ header
+ + "\n"
+ + dedent("""\
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def _():
+ import cowsay
+ return
+ """),
+ encoding="utf-8",
+ )
+ generator = MarimoIslandGenerator.from_file(str(path))
+ else:
+ generator = MarimoIslandGenerator._from_ir(
+ NotebookSerialization(
+ app=AppInstantiation(),
+ header=Header(value=header) if header else None,
+ cells=[CellDef(code="import cowsay")],
+ )
+ )
+
+ payload = _parse_payload_from_body(
+ generator.render_body(include_payload=True)
+ )
+ assert payload == {
+ "schemaVersion": 1,
+ "appId": "main",
+ "cells": [stub.to_payload() for stub in generator.stubs],
+ **({"dependencies": dependencies} if dependencies else {}),
+ }
+
+
[email protected]("from_file", [True, False])
[email protected]("extension", ["md", "qmd"])
+ ("frontmatter", "dependencies"),
+ [
+ ({"title": "Notebook"}, []),
+ ({"pyproject": 'dependencies = ["cowsay==6.1"]'}, ["cowsay==6.1"]),
+ (
+ {
+ "pyproject": script_metadata.dumps(
+ {"dependencies": ["cowsay==6.1"]}
+ )
+ },
+ ["cowsay==6.1"],
+ ),
+ (
+ {
+ "header": script_metadata.dumps(
+ {"dependencies": ["rich[jupyter]>=13"]}
+ )
+ },
+ ["rich[jupyter]>=13"],
+ ),
+ (
+ {
+ "pyproject": 'dependencies = ["cowsay==6.1"]',
+ "header": script_metadata.dumps(
+ {"dependencies": ["rich[jupyter]>=13"]}
+ ),
+ },
+ ["cowsay==6.1"],
+ ),
+ (
+ {
+ "pyproject": "",
+ "header": script_metadata.dumps(
+ {"dependencies": ["rich[jupyter]>=13"]}
+ ),
+ },
+ ["rich[jupyter]>=13"],
+ ),
+ (
+ {
+ "pyproject": "dependencies = []",
+ "header": script_metadata.dumps(
+ {"dependencies": ["rich[jupyter]>=13"]}
+ ),
+ },
+ [],
+ ),
+ ],
+)
+def test_render_payload_markdown_dependencies(
+ tmp_path: Path,
+ from_file: bool,
+ extension: str,
+ frontmatter: dict[str, str],
+ dependencies: list[str],
+) -> None:
+ path = tmp_path / f"notebook.{extension}"
+ contents = (
+ "---\n"
+ + yaml.safe_dump(frontmatter)
+ + "---\n\n```{python}\nimport cowsay\n```\n"
+ )
+ if from_file:
+ path.write_text(contents, encoding="utf-8")
+ generator = MarimoIslandGenerator.from_file(str(path))
+ else:
+ generator = MarimoIslandGenerator._from_ir(
+ convert_from_md_to_marimo_ir(contents, filepath=str(path))
+ )
+
+ assert _parse_payload_from_body(
+ generator.render_body(include_payload=True)
+ ) == {
+ "schemaVersion": 1,
+ "appId": "main",
+ "cells": [stub.to_payload() for stub in generator.stubs],
+ **({"dependencies": dependencies} if dependencies else {}),
+ }
+
+
+def test_render_dependency_payload_snapshot() -> None:
+ generator = MarimoIslandGenerator._from_ir(
+ NotebookSerialization(
+ app=AppInstantiation(),
+ header=Header(
+ value=script_metadata.dumps(
+ {
+ "dependencies": [
+ 'cowsay==6.1; sys_platform == "emscripten"',
+ "rich[jupyter]>=13",
+ "desktop; sys_platform != 'emscripten'",
+ "older-python; python_version < '3.13'",
+ "newer-python; python_version >= '3.13'",
+ ]
+ }
+ )
+ ),
+ cells=[CellDef(code="import cowsay")],
+ )
+ )
+ # Shared with the frontend parser test to cover the export contract.
+ snapshot(
+ "body-dependencies.txt",
+ generator.render_body(include_payload=True, include_init_island=False),
+ )
+
+
+def test_render_payload_script_escapes_dependencies() -> None:
+ dependencies = ["pkg @ https://example.com/</script>?a=1&b=2"]
+ generator = MarimoIslandGenerator._from_ir(
+ NotebookSerialization(
+ app=AppInstantiation(),
+ header=Header(
+ value=script_metadata.dumps({"dependencies": dependencies})
+ ),
+ )
+ )
+
+ script = generator.render_payload_script()
+
+ assert script.count("</script>") == 1
+ assert "&" not in script
+ assert _parse_payload_script(script) == {
+ "schemaVersion": 1,
+ "appId": "main",
+ "cells": [],
+ "dependencies": dependencies,
+ }
+
+
def test_render_payload_preserves_error_output_mimetype():
generator = MarimoIslandGenerator()
stub = generator.add_code("0 / 0")
diff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.py
index 3f3f290283..0b7a3838c5 100644
--- a/tests/_pyodide/test_pyodide_session.py
+++ b/tests/_pyodide/test_pyodide_session.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import json
import unittest.mock
+from pathlib import Path
from textwrap import dedent
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any
@@ -58,7 +59,6 @@ from tests._server.templates.utils import parse_mount_config
if TYPE_CHECKING:
from collections.abc import AsyncGenerator, Generator
- from pathlib import Path
@pytest.fixture
@@ -414,6 +414,40 @@ async def test_pyodide_session_find_packages_with_script_metadata(
mock_pyodide.code.find_imports.assert_not_called()
+ ("python_version", "expected_package"),
+ [("3.12", "older-python"), ("3.13", "newer-python")],
+)
+async def test_find_packages_from_island_notebook(
+ pyodide_session: PyodideSession,
+ mock_pyodide: MagicMock,
+ python_version: str,
+ expected_package: str,
+) -> None:
+ from packaging.markers import default_environment
+
+ # Generated by the frontend from a Python-rendered island payload.
+ code = (
+ Path(__file__).parent.parent
+ / "_islands/snapshots/notebook-dependencies.txt"
+ ).read_text(encoding="utf-8")
+
+ environment = {
+ **default_environment(),
+ "python_version": python_version,
+ "python_full_version": f"{python_version}.0",
+ }
+ with patch(
+ "packaging.markers.default_environment", return_value=environment
+ ):
+ assert pyodide_session.find_packages(code) == [
+ "cowsay",
+ "rich[jupyter]",
+ expected_package,
+ ]
+ mock_pyodide.code.find_imports.assert_not_called()
+
+
async def test_complex_find_packages(pyodide_session: PyodideSession) -> None:
code = dedent(
"""