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.

wasm: check platform instead of sys.modules for pyodide check (#9404)

Myles Scolnick4a52d084e184
diff --git a/marimo/_utils/platform.py b/marimo/_utils/platform.py
index 8b1b6d2fea..98440b6fa2 100644
--- a/marimo/_utils/platform.py
+++ b/marimo/_utils/platform.py
@@ -10,7 +10,7 @@ def is_windows() -> bool:
def is_pyodide() -> bool:
- return "pyodide" in sys.modules
+ return sys.platform == "emscripten"
def check_shared_memory_available() -> tuple[bool, str]:
diff --git a/tests/_runtime/test_manage_script_metadata.py b/tests/_runtime/test_manage_script_metadata.py
index c57ccbcd2d..f78bb03f0d 100644
--- a/tests/_runtime/test_manage_script_metadata.py
+++ b/tests/_runtime/test_manage_script_metadata.py
@@ -2,7 +2,6 @@
from __future__ import annotations
import pathlib
-import sys
from typing import TYPE_CHECKING, Any, cast
from unittest.mock import AsyncMock, Mock, call, patch
@@ -27,7 +26,7 @@ from marimo._runtime.packages.pypi_package_manager import (
)
from marimo._runtime.packages.utils import is_python_isolated
from marimo._runtime.runner import cell_runner
-from tests.conftest import MockedKernel
+from tests.conftest import MockedKernel, mock_pyodide
if TYPE_CHECKING:
import pathlib
@@ -235,7 +234,7 @@ async def test_manage_script_metadata_pip_noop(
assert "" == f.read()
[email protected](sys.modules, {"pyodide": Mock()})
+@mock_pyodide()
async def test_install_missing_packages_micropip(
mocked_kernel: MockedKernel,
) -> None:
@@ -255,7 +254,7 @@ async def test_install_missing_packages_micropip(
]
[email protected](sys.modules, {"pyodide": Mock()})
+@mock_pyodide()
async def test_install_missing_packages_micropip_with_versions(
mocked_kernel: MockedKernel,
) -> None:
@@ -275,7 +274,7 @@ async def test_install_missing_packages_micropip_with_versions(
]
[email protected](sys.modules, {"pyodide": Mock(), "already_installed": Mock()})
+@mock_pyodide(already_installed=Mock())
async def test_install_missing_packages_micropip_other_modules(
mocked_kernel: MockedKernel,
) -> None:
@@ -299,7 +298,7 @@ async def test_install_missing_packages_micropip_other_modules(
]
[email protected](sys.modules, {"pyodide": Mock()})
+@mock_pyodide()
async def test_missing_packages_hook(
mocked_kernel: MockedKernel,
) -> None:
diff --git a/tests/_runtime/test_patches.py b/tests/_runtime/test_patches.py
index 8065d724c0..a7a4d17001 100644
--- a/tests/_runtime/test_patches.py
+++ b/tests/_runtime/test_patches.py
@@ -2,9 +2,8 @@
from __future__ import annotations
import io
-import sys
from typing import TYPE_CHECKING
-from unittest.mock import Mock, patch
+from unittest.mock import patch
import pytest
@@ -14,7 +13,7 @@ from marimo._runtime.patches import patch_polars_write_json
from marimo._runtime.runtime import Kernel
from marimo._utils.platform import is_pyodide
from tests._messaging.mocks import MockStream
-from tests.conftest import ExecReqProvider
+from tests.conftest import ExecReqProvider, mock_pyodide
if TYPE_CHECKING:
from pathlib import Path
@@ -211,7 +210,7 @@ async def test_webbrowser_easter_egg(
not DependencyManager.polars.has(),
reason="Polars is not installed",
)
[email protected](sys.modules, {"pyodide": Mock()})
+@mock_pyodide()
def test_polars_write_json_patch(tmp_path: Path):
import polars as pl
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 1babc42f0b..2e419a5db9 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -56,7 +56,7 @@ from marimo._runtime.scratch import SCRATCH_CELL_ID
from marimo._session.model import SessionMode
from marimo._utils.parse_dataclass import parse_raw
from tests._messaging.mocks import MockStderr, MockStream
-from tests.conftest import ExecReqProvider, MockedKernel
+from tests.conftest import ExecReqProvider, MockedKernel, mock_pyodide
if TYPE_CHECKING:
from collections.abc import Coroutine, Sequence
@@ -1342,14 +1342,10 @@ except NameError:
@pytest.mark.skipif(
sys.platform == "win32", reason="Windows paths behave differently"
)
- @patch.dict(
- sys.modules,
- {
- "pyodide": Mock(),
- "js": Mock(
- location="https://marimo-team.github.io/marimo-gh-pages-template/notebooks/assets/worker-BxJ8HeOy.js"
- ),
- },
+ @mock_pyodide(
+ js=Mock(
+ location="https://marimo-team.github.io/marimo-gh-pages-template/notebooks/assets/worker-BxJ8HeOy.js"
+ ),
)
async def test_notebook_location_for_pyodide(
self, any_kernel: Kernel, exec_req: ExecReqProvider
diff --git a/tests/_utils/test_platform.py b/tests/_utils/test_platform.py
index 96f07788f5..e404cac1bf 100644
--- a/tests/_utils/test_platform.py
+++ b/tests/_utils/test_platform.py
@@ -32,14 +32,12 @@ class TestIsWindows:
class TestIsPyodide:
- def test_is_pyodide_when_not_loaded(self) -> None:
- # By default, pyodide should not be in sys.modules
+ def test_is_pyodide_on_normal_platform(self) -> None:
+ # By default, sys.platform is not emscripten in the test environment
assert not is_pyodide()
- def test_is_pyodide_when_loaded(self) -> None:
- with patch(
- "marimo._utils.platform.sys.modules", {"pyodide": object()}
- ):
+ def test_is_pyodide_on_emscripten(self) -> None:
+ with patch("marimo._utils.platform.sys.platform", "emscripten"):
assert is_pyodide()
diff --git a/tests/conftest.py b/tests/conftest.py
index ee1cc4809e..0b8699c807 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,13 +1,17 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import contextlib
import dataclasses
+import functools
+import inspect
import re
import shutil
import sys
import textwrap
from pathlib import Path
from typing import TYPE_CHECKING, Any
+from unittest.mock import Mock, patch
import pytest
from _pytest import runner
@@ -50,6 +54,8 @@ if TYPE_CHECKING:
from collections.abc import Generator
from types import ModuleType
+ from typing_extensions import Self
+
# register import hooks for third-party module formatters
register_formatters()
@@ -544,6 +550,73 @@ def exec_req() -> ExecReqProvider:
return ExecReqProvider()
+class MockPyodide:
+ """Simulate running in a Pyodide environment.
+
+ Patches ``sys.platform`` to ``"emscripten"`` so ``is_pyodide()`` returns
+ True, and stubs ``pyodide`` (plus any ``extra_modules``) in
+ ``sys.modules`` so ``import pyodide`` (and friends) succeeds.
+
+ Usable as a context manager or as a decorator on sync or async tests::
+
+ with mock_pyodide():
+ ...
+
+ @mock_pyodide()
+ async def test_foo(...): ...
+
+ @mock_pyodide(already_installed=Mock())
+ def test_bar(...): ...
+ """
+
+ def __init__(self, **extra_modules: Any) -> None:
+ self._extra_modules = extra_modules
+ self._stack: contextlib.ExitStack | None = None
+
+ def __enter__(self) -> Self:
+ modules = {"pyodide": Mock(), **self._extra_modules}
+ stack = contextlib.ExitStack()
+ stack.__enter__()
+ stack.enter_context(patch.object(sys, "platform", "emscripten"))
+ stack.enter_context(patch.dict(sys.modules, modules))
+ self._stack = stack
+ return self
+
+ def __exit__(self, *exc: Any) -> None:
+ assert self._stack is not None
+ self._stack.__exit__(*exc)
+ self._stack = None
+
+ def __call__(self, func: Any) -> Any:
+ extra = self._extra_modules
+ if inspect.iscoroutinefunction(func):
+
+ @functools.wraps(func)
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
+ with MockPyodide(**extra):
+ return await func(*args, **kwargs)
+
+ return async_wrapper
+
+ @functools.wraps(func)
+ def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
+ with MockPyodide(**extra):
+ return func(*args, **kwargs)
+
+ return sync_wrapper
+
+
+# Lowercase alias for context-manager-style usage at call sites.
+mock_pyodide = MockPyodide
+
+
+def pyodide_env() -> Generator[None, None, None]:
+ """Pytest fixture that simulates running in a Pyodide environment."""
+ with mock_pyodide():
+ yield
+
+
# Library fixtures for direct marimo integration with pytest.
@pytest.fixture
def mo_fixture() -> ModuleType: