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.

perf: non-blocking formatting and auto-export (#6022)

Myles Scolnickb73d25ad091b
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 0ea2b1060d..935a82130c 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -8,7 +8,7 @@ import json
import re
import signal
from pathlib import Path
-from typing import Callable
+from typing import Any, Callable, TypeVar
from marimo import _loggers
from marimo._ast.cell import CellConfig
@@ -197,6 +197,9 @@ class PyodideSession:
return []
+T = TypeVar("T")
+
+
class PyodideBridge:
def __init__(
self,
@@ -217,35 +220,35 @@ class PyodideBridge:
self.session.put_input(text)
def code_complete(self, request: str) -> None:
- parsed = parse_raw(json.loads(request), requests.CodeCompletionRequest)
+ parsed = self._parse(request, requests.CodeCompletionRequest)
self.session.put_completion_request(parsed)
def read_code(self) -> str:
contents: str = self.session.app_manager.read_file()
response = ReadCodeResponse(contents=contents)
- return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
+ return self._dump(response)
async def read_snippets(self) -> str:
snippets = await read_snippets()
- return json.dumps(deep_to_camel_case(dataclasses.asdict(snippets)))
+ return self._dump(snippets)
- def format(self, request: str) -> str:
- parsed = parse_raw(json.loads(request), FormatRequest)
+ async def format(self, request: str) -> str:
+ parsed = self._parse(request, FormatRequest)
formatter = DefaultFormatter(line_length=parsed.line_length)
- response = FormatResponse(codes=formatter.format(parsed.codes))
- return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
+ response = FormatResponse(codes=await formatter.format(parsed.codes))
+ return self._dump(response)
def save(self, request: str) -> None:
- parsed = parse_raw(json.loads(request), SaveNotebookRequest)
+ parsed = self._parse(request, SaveNotebookRequest)
self.session.app_manager.save(parsed)
def save_app_config(self, request: str) -> None:
- parsed = parse_raw(json.loads(request), SaveAppConfigurationRequest)
+ parsed = self._parse(request, SaveAppConfigurationRequest)
self.session.app_manager.save_app_config(parsed.config)
def save_user_config(self, request: str) -> None:
- parsed = parse_raw(json.loads(request), requests.SetUserConfigRequest)
+ parsed = self._parse(request, requests.SetUserConfigRequest)
config = merge_default_config(parsed.config)
self.session.put_control_request(SetUserConfigRequest(config=config))
@@ -260,7 +263,7 @@ class PyodideBridge:
root = body.path or self.file_system.get_root()
files = self.file_system.list_files(root)
response = FileListResponse(files=files, root=root)
- return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
+ return self._dump(response)
def file_details(
self,
@@ -268,7 +271,7 @@ class PyodideBridge:
) -> str:
body = parse_raw(json.loads(request), FileDetailsRequest)
response = self.file_system.get_details(body.path)
- return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
+ return self._dump(response)
def create_file_or_directory(
self,
@@ -290,7 +293,7 @@ class PyodideBridge:
response = FileCreateResponse(success=True, info=info)
except Exception as e:
response = FileCreateResponse(success=False, message=str(e))
- return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
+ return self._dump(response)
def delete_file_or_directory(
self,
@@ -299,7 +302,7 @@ class PyodideBridge:
body = parse_raw(json.loads(request), FileDeleteRequest)
success = self.file_system.delete_file_or_directory(body.path)
response = FileDeleteResponse(success=success)
- return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
+ return self._dump(response)
def move_file_or_directory(
self,
@@ -313,7 +316,7 @@ class PyodideBridge:
response = FileMoveResponse(success=True, info=info)
except Exception as e:
response = FileMoveResponse(success=False, message=str(e))
- return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
+ return self._dump(response)
def update_file(
self,
@@ -325,7 +328,7 @@ class PyodideBridge:
response = FileUpdateResponse(success=True)
except Exception as e:
response = FileUpdateResponse(success=False, message=str(e))
- return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
+ return self._dump(response)
def export_html(self, request: str) -> str:
parsed = parse_raw(json.loads(request), ExportAsHTMLRequest)
@@ -346,6 +349,12 @@ class PyodideBridge:
)
return json.dumps(md)
+ def _parse(self, request: str, cls: type[T]) -> T:
+ return parse_raw(json.loads(request), cls)
+
+ def _dump(self, response: Any) -> str:
+ return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
+
def _launch_pyodide_kernel(
control_queue: asyncio.Queue[ControlRequest],
diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.py
index bc209eb236..528a8699e0 100644
--- a/marimo/_server/api/endpoints/editing.py
+++ b/marimo/_server/api/endpoints/editing.py
@@ -129,7 +129,7 @@ async def format_cell(request: Request) -> FormatResponse:
body = await parse_request(request, cls=FormatRequest)
formatter = DefaultFormatter(line_length=body.line_length)
- return FormatResponse(codes=formatter.format(body.codes))
+ return FormatResponse(codes=await formatter.format(body.codes))
@router.post("/set_cell_config")
diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.py
index 96e34ddbe0..dbebf17273 100644
--- a/marimo/_server/api/endpoints/export.py
+++ b/marimo/_server/api/endpoints/export.py
@@ -4,8 +4,9 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from starlette.authentication import requires
+from starlette.background import BackgroundTask
from starlette.exceptions import HTTPException
-from starlette.responses import HTMLResponse, PlainTextResponse
+from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse
from marimo import _loggers
from marimo._server.api.deps import AppState
@@ -94,7 +95,7 @@ async def export_as_html(
async def auto_export_as_html(
*,
request: Request,
-) -> SuccessResponse | PlainTextResponse:
+) -> JSONResponse | PlainTextResponse:
"""
requestBody:
content:
@@ -135,22 +136,26 @@ async def auto_export_as_html(
LOGGER.info("No outputs to export")
return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)
- html, _filename = Exporter().export_as_html(
- app=session.app_file_manager.app,
- filename=session.app_file_manager.filename,
- session_view=session_view,
- display_config=session.config_manager.get_config()["display"],
- request=body,
- )
+ async def _background_export() -> None:
+ html, _filename = Exporter().export_as_html(
+ app=session.app_file_manager.app,
+ filename=session.app_file_manager.filename,
+ session_view=session_view,
+ display_config=session.config_manager.get_config()["display"],
+ request=body,
+ )
- # Save the HTML file to disk, at `.marimo/<filename>.html`
- await auto_exporter.save_html(
- filename=session.app_file_manager.filename,
- html=html,
- )
- session_view.mark_auto_export_html()
+ # Save the HTML file to disk, at `.marimo/<filename>.html`
+ await auto_exporter.save_html(
+ filename=session.app_file_manager.filename,
+ html=html,
+ )
+ session_view.mark_auto_export_html()
- return SuccessResponse()
+ return JSONResponse(
+ content=SuccessResponse().as_camel_case(),
+ background=BackgroundTask(_background_export),
+ )
@router.post("/script")
@@ -252,7 +257,7 @@ async def export_as_markdown(
async def auto_export_as_markdown(
*,
request: Request,
-) -> SuccessResponse | PlainTextResponse:
+) -> JSONResponse | PlainTextResponse:
"""
requestBody:
content:
@@ -284,22 +289,26 @@ async def auto_export_as_markdown(
LOGGER.debug("Already auto-exported to Markdown")
return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)
- # Reload the file manager to get the latest state
- session.app_file_manager.reload()
+ async def _background_export() -> None:
+ # Reload the file manager to get the latest state
+ session.app_file_manager.reload()
- markdown, _filename = Exporter().export_as_md(
- notebook=session.app_file_manager.app.to_ir(),
- filename=session.app_file_manager.filename,
- )
+ markdown, _filename = Exporter().export_as_md(
+ notebook=session.app_file_manager.app.to_ir(),
+ filename=session.app_file_manager.filename,
+ )
- # Save the Markdown file to disk, at `.marimo/<filename>.md`
- await auto_exporter.save_md(
- filename=session.app_file_manager.filename,
- markdown=markdown,
- )
- session_view.mark_auto_export_md()
+ # Save the Markdown file to disk, at `.marimo/<filename>.md`
+ await auto_exporter.save_md(
+ filename=session.app_file_manager.filename,
+ markdown=markdown,
+ )
+ session_view.mark_auto_export_md()
- return SuccessResponse()
+ return JSONResponse(
+ content=SuccessResponse().as_camel_case(),
+ background=BackgroundTask(_background_export),
+ )
@router.post("/auto_export/ipynb")
@@ -307,7 +316,7 @@ async def auto_export_as_markdown(
async def auto_export_as_ipynb(
*,
request: Request,
-) -> SuccessResponse | PlainTextResponse:
+) -> JSONResponse | PlainTextResponse:
"""
requestBody:
content:
@@ -339,21 +348,25 @@ async def auto_export_as_ipynb(
LOGGER.debug("Already auto-exported to IPYNB")
return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)
- # Reload the file manager to get the latest state
- session.app_file_manager.reload()
+ async def _background_export() -> None:
+ # Reload the file manager to get the latest state
+ session.app_file_manager.reload()
- ipynb, _filename = Exporter().export_as_ipynb(
- app=session.app_file_manager.app,
- filename=session.app_file_manager.filename,
- sort_mode="top-down",
- session_view=session_view,
- )
+ ipynb, _filename = Exporter().export_as_ipynb(
+ app=session.app_file_manager.app,
+ filename=session.app_file_manager.filename,
+ sort_mode="top-down",
+ session_view=session_view,
+ )
- # Save the IPYNB file to disk, at `.marimo/<filename>.ipynb`
- await auto_exporter.save_ipynb(
- filename=session.app_file_manager.filename,
- ipynb=ipynb,
- )
- session_view.mark_auto_export_ipynb()
+ # Save the IPYNB file to disk, at `.marimo/<filename>.ipynb`
+ await auto_exporter.save_ipynb(
+ filename=session.app_file_manager.filename,
+ ipynb=ipynb,
+ )
+ session_view.mark_auto_export_ipynb()
- return SuccessResponse()
+ return JSONResponse(
+ content=SuccessResponse().as_camel_case(),
+ background=BackgroundTask(_background_export),
+ )
diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.py
index 9ad5a6ff36..32a6ae1d0e 100644
--- a/marimo/_server/models/models.py
+++ b/marimo/_server/models/models.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import dataclasses
import os
from dataclasses import dataclass
from typing import Any, Optional
@@ -13,6 +14,7 @@ from marimo._runtime.requests import (
RenameRequest,
)
from marimo._types.ids import CellId_t, UIElementId
+from marimo._utils.case import deep_to_camel_case
@dataclass
@@ -41,6 +43,9 @@ class InstantiateRequest(UpdateComponentValuesRequest):
class BaseResponse:
success: bool
+ def as_camel_case(self) -> dict[str, Any]:
+ return deep_to_camel_case(dataclasses.asdict(self))
+
@dataclass
class SuccessResponse(BaseResponse):
diff --git a/marimo/_utils/formatter.py b/marimo/_utils/formatter.py
index 37dc98ead8..d59cf16c55 100644
--- a/marimo/_utils/formatter.py
+++ b/marimo/_utils/formatter.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import asyncio
import subprocess
import sys
@@ -14,16 +15,64 @@ LOGGER = _loggers.marimo_logger()
CellCodes = dict[CellId_t, str]
-def ruff(codes: CellCodes, *cmd: str) -> CellCodes:
+async def _run_subprocess_safe(
+ *args: str, input_data: bytes | None = None
+) -> tuple[bytes, bytes, int]:
+ """Run subprocess safely on all platforms, including Windows."""
+ try:
+ # Try asyncio first (works on most platforms)
+ if input_data is not None:
+ process = await asyncio.create_subprocess_exec(
+ *args,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ stdout, stderr = await process.communicate(input_data)
+ else:
+ process = await asyncio.create_subprocess_exec(
+ *args,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ stdout, stderr = await process.communicate()
+
+ return stdout, stderr, process.returncode or 0
+ except NotImplementedError:
+ # Windows may throw NotImplementedError if using _WindowsSelectorEventLoop
+ def run_sync() -> tuple[bytes, bytes, int]:
+ if input_data is not None:
+ result = subprocess.run(
+ args,
+ input=input_data,
+ capture_output=True,
+ timeout=30, # Add reasonable timeout
+ )
+ else:
+ result = subprocess.run(
+ args,
+ capture_output=True,
+ timeout=30,
+ )
+ return result.stdout, result.stderr, result.returncode
+
+ return await asyncio.to_thread(run_sync)
+
+
+async def ruff(codes: CellCodes, *cmd: str) -> CellCodes:
# Try with sys.executable first
ruff_cmd = [sys.executable, "-m", "ruff"]
- process = subprocess.run([*ruff_cmd, "--help"], capture_output=True)
+ stdout, _stderr, returncode = await _run_subprocess_safe(
+ *ruff_cmd, "--help"
+ )
# If that fails, try global ruff
- if process.returncode != 0:
+ if returncode != 0:
ruff_cmd = ["ruff"]
- process = subprocess.run([*ruff_cmd, "--help"], capture_output=True)
- if process.returncode != 0:
+ stdout, _stderr, returncode = await _run_subprocess_safe(
+ *ruff_cmd, "--help"
+ )
+ if returncode != 0:
raise ModuleNotFoundError(
"To enable code formatting, please install ruff", name="ruff"
)
@@ -31,20 +80,14 @@ def ruff(codes: CellCodes, *cmd: str) -> CellCodes:
formatted_codes: CellCodes = {}
for key, code in codes.items():
try:
- process = subprocess.run(
- [
- *ruff_cmd,
- *cmd,
- "-",
- ],
- input=code.encode(),
- capture_output=True,
- check=True,
+ stdout, _stderr, returncode = await _run_subprocess_safe(
+ *ruff_cmd, *cmd, "-", input_data=code.encode()
)
- if process.returncode != 0:
+
+ if returncode != 0:
raise FormatError("Failed to format code with ruff")
- formatted = process.stdout.decode()
+ formatted = stdout.decode()
formatted_codes[key] = formatted.strip()
except Exception as e:
LOGGER.error("Failed to format code with ruff")
@@ -58,7 +101,7 @@ class Formatter:
def __init__(self, line_length: int) -> None:
self.line_length = line_length
- def format(self, codes: CellCodes) -> CellCodes:
+ async def format(self, codes: CellCodes) -> CellCodes:
return codes
@@ -67,13 +110,13 @@ class DefaultFormatter(Formatter):
Tries ruff, then black, then no formatting.
"""
- def format(self, codes: CellCodes) -> CellCodes:
+ async def format(self, codes: CellCodes) -> CellCodes:
# Ruff may be installed in venv or globally
if DependencyManager.ruff.has() or DependencyManager.which("ruff"):
- return RuffFormatter(self.line_length).format(codes)
+ return await RuffFormatter(self.line_length).format(codes)
# Black must be installed in venv
elif DependencyManager.black.has():
- return BlackFormatter(self.line_length).format(codes)
+ return await BlackFormatter(self.line_length).format(codes)
else:
raise ModuleNotFoundError(
"To enable code formatting, please install ruff or black",
@@ -82,12 +125,14 @@ class DefaultFormatter(Formatter):
class RuffFormatter(Formatter):
- def format(self, codes: CellCodes) -> CellCodes:
- return ruff(codes, "format", "--line-length", str(self.line_length))
+ async def format(self, codes: CellCodes) -> CellCodes:
+ return await ruff(
+ codes, "format", "--line-length", str(self.line_length)
+ )
class BlackFormatter(Formatter):
- def format(self, codes: CellCodes) -> CellCodes:
+ async def format(self, codes: CellCodes) -> CellCodes:
DependencyManager.black.require("to enable code formatting")
import black
@@ -95,8 +140,11 @@ class BlackFormatter(Formatter):
formatted_codes: CellCodes = {}
for key, code in codes.items():
try:
+ # Run black formatting in a thread pool to avoid blocking
mode = black.Mode(line_length=self.line_length) # type: ignore
- formatted = black.format_str(code, mode=mode)
+ formatted = await asyncio.to_thread(
+ black.format_str, code, mode=mode
+ )
formatted_codes[key] = formatted.strip()
except Exception:
formatted_codes[key] = code
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index 0342558cce..f5ac75b566 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -2,11 +2,11 @@
from __future__ import annotations
import json
-import os
from functools import partial
from inspect import cleandoc
+from pathlib import Path
from textwrap import dedent
-from typing import TYPE_CHECKING, Any, Optional
+from typing import Any, Optional
import codegen_data.test_main as mod
import pytest
@@ -19,17 +19,13 @@ from marimo._ast.cell import CellConfig
from marimo._ast.names import is_internal_cell_name
from marimo._schemas.notebook import NotebookV1
-if TYPE_CHECKING:
- from pathlib import Path
-
compile_cell = partial(compiler.compile_cell, cell_id="0")
-DIR_PATH = os.path.dirname(os.path.realpath(__file__))
+DIR_PATH = Path(__file__).parent
def get_expected_filecontents(name: str) -> str:
- with open(os.path.join(DIR_PATH, f"codegen_data/{name}.py")) as f:
- contents = f.read()
+ contents = get_filepath(name).read_text()
lines = contents.split("\n")
break_index = None
for i, line in enumerate(lines):
@@ -44,8 +40,8 @@ def get_expected_filecontents(name: str) -> str:
)
-def get_filepath(name: str) -> str:
- return os.path.join(DIR_PATH, f"codegen_data/{name}.py")
+def get_filepath(name: str) -> Path:
+ return Path(DIR_PATH) / f"codegen_data/{name}.py"
def sanitized_version(output: str) -> str:
@@ -73,11 +69,11 @@ def wrap_generate_filecontents(
return filecontents
-def get_idempotent_marimo_source(name: str) -> str:
+async def get_idempotent_marimo_source(name: str) -> str:
from marimo._utils.formatter import Formatter
path = get_filepath(name)
- app = load.load_app(path)
+ app = load.load_app(str(path))
header_comments = codegen.get_header_comments(path)
generated_contents = codegen.generate_filecontents(
codes=list(app._cell_manager.codes()),
@@ -88,10 +84,9 @@ def get_idempotent_marimo_source(name: str) -> str:
)
generated_contents = sanitized_version(generated_contents)
- with open(path) as f:
- python_source = sanitized_version(f.read())
+ python_source = sanitized_version(path.read_text())
- formatted = Formatter(codegen.MAX_LINE_LENGTH).format(
+ formatted = await Formatter(codegen.MAX_LINE_LENGTH).format(
{"source": python_source, "generated": generated_contents}
)
@@ -418,8 +413,8 @@ class TestGeneration:
assert "def __" not in contents
@staticmethod
- def test_generate_filecontents_toplevel() -> None:
- source = get_idempotent_marimo_source(
+ async def test_generate_filecontents_toplevel() -> None:
+ source = await get_idempotent_marimo_source(
"test_generate_filecontents_toplevel"
)
assert "import marimo" in source
@@ -428,15 +423,15 @@ class TestGeneration:
assert len(split) == 3
@staticmethod
- def test_generate_filecontents_toplevel_pytest() -> None:
- source = get_idempotent_marimo_source(
+ async def test_generate_filecontents_toplevel_pytest() -> None:
+ source = await get_idempotent_marimo_source(
"test_generate_filecontents_toplevel_pytest"
)
assert "import marimo" in source
@staticmethod
- def test_generate_filecontents_with_annotation_typing() -> None:
- source = get_idempotent_marimo_source(
+ async def test_generate_filecontents_with_annotation_typing() -> None:
+ source = await get_idempotent_marimo_source(
"test_app_with_annotation_typing"
)
assert "import marimo" in source
diff --git a/tests/_utils/test_formatter.py b/tests/_utils/test_formatter.py
new file mode 100644
index 0000000000..089bdf07ce
--- /dev/null
+++ b/tests/_utils/test_formatter.py
@@ -0,0 +1,447 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import sys
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from marimo._utils.formatter import (
+ BlackFormatter,
+ CellCodes,
+ DefaultFormatter,
+ FormatError,
+ Formatter,
+ RuffFormatter,
+ ruff,
+)
+
+
+class TestFormatter:
+ """Test the base Formatter class."""
+
+ async def test_base_formatter_returns_unchanged_codes(self):
+ """Test that base Formatter returns codes unchanged."""
+ formatter = Formatter(line_length=88)
+ codes: CellCodes = {"cell1": "x = 1\ny = 2", "cell2": "z = 3"}
+
+ result = await formatter.format(codes)
+
+ assert result == codes
+ assert result is codes # Should be the same object
+
+
+class TestDefaultFormatter:
+ """Test the DefaultFormatter class that tries ruff, then black."""
+
+ @patch("marimo._utils.formatter.RuffFormatter")
+ @patch("marimo._dependencies.dependencies.DependencyManager.which")
+ @patch("marimo._dependencies.dependencies.DependencyManager.ruff")
+ async def test_uses_ruff_when_available(
+ self,
+ mock_ruff: MagicMock,
+ mock_which: MagicMock,
+ mock_ruff_formatter: MagicMock,
+ ) -> None:
+ """Test DefaultFormatter uses RuffFormatter when ruff is available."""
+ # Mock ruff as available
+ mock_ruff.has.return_value = True
+ mock_which.return_value = "/usr/bin/ruff"
+
+ # Mock RuffFormatter
+ mock_instance = AsyncMock()
+ mock_ruff_formatter.return_value = mock_instance
+ mock_instance.format.return_value = {"cell1": "formatted_code"}
+
+ formatter = DefaultFormatter(line_length=88)
+ codes: CellCodes = {"cell1": "x=1"}
+
+ result = await formatter.format(codes)
+
+ mock_ruff_formatter.assert_called_once_with(88)
+ mock_instance.format.assert_called_once_with(codes)
+ assert result == {"cell1": "formatted_code"}
+
+ @patch("marimo._utils.formatter.BlackFormatter")
+ @patch("marimo._dependencies.dependencies.DependencyManager.black")
+ @patch("marimo._dependencies.dependencies.DependencyManager.which")
+ @patch("marimo._dependencies.dependencies.DependencyManager.ruff")
+ async def test_uses_black_when_ruff_unavailable_but_black_available(
+ self,
+ mock_ruff: MagicMock,
+ mock_which: MagicMock,
+ mock_black: MagicMock,
+ mock_black_formatter: MagicMock,
+ ) -> None:
+ """Test DefaultFormatter uses BlackFormatter when ruff unavailable but black available."""
+ # Mock ruff as unavailable, black as available
+ mock_ruff.has.return_value = False
+ mock_which.return_value = None
+ mock_black.has.return_value = True
+
+ # Mock BlackFormatter
+ mock_instance = AsyncMock()
+ mock_black_formatter.return_value = mock_instance
+ mock_instance.format.return_value = {"cell1": "formatted_code"}
+
+ formatter = DefaultFormatter(line_length=88)
+ codes: CellCodes = {"cell1": "x=1"}
+
+ result = await formatter.format(codes)
+
+ mock_black_formatter.assert_called_once_with(88)
+ mock_instance.format.assert_called_once_with(codes)
+ assert result == {"cell1": "formatted_code"}
+
+ @patch("marimo._dependencies.dependencies.DependencyManager.black")
+ @patch("marimo._dependencies.dependencies.DependencyManager.which")
+ @patch("marimo._dependencies.dependencies.DependencyManager.ruff")
+ async def test_raises_module_not_found_when_no_formatters_available(
+ self,
+ mock_ruff: MagicMock,
+ mock_which: MagicMock,
+ mock_black: MagicMock,
+ ) -> None:
+ """Test DefaultFormatter raises ModuleNotFoundError when no formatters available."""
+ # Mock both ruff and black as unavailable
+ mock_ruff.has.return_value = False
+ mock_which.return_value = None
+ mock_black.has.return_value = False
+
+ formatter = DefaultFormatter(line_length=88)
+ codes: CellCodes = {"cell1": "x=1"}
+
+ with pytest.raises(ModuleNotFoundError) as exc_info:
+ await formatter.format(codes)
+
+ assert "ruff or black" in str(exc_info.value)
+ assert exc_info.value.name == "ruff"
+
+
+class TestRuffFormatter:
+ """Test the RuffFormatter class."""
+
+ @patch("marimo._utils.formatter.ruff")
+ async def test_ruff_formatter_calls_ruff_function(
+ self, mock_ruff: MagicMock
+ ) -> None:
+ """Test RuffFormatter calls the ruff function with correct arguments."""
+ mock_ruff.return_value = {"cell1": "formatted_code"}
+
+ formatter = RuffFormatter(line_length=100)
+ codes: CellCodes = {"cell1": "x=1"}
+
+ result = await formatter.format(codes)
+
+ mock_ruff.assert_called_once_with(
+ codes, "format", "--line-length", "100"
+ )
+ assert result == {"cell1": "formatted_code"}
+
+ @patch("marimo._utils.formatter.ruff")
+ async def test_ruff_formatter_propagates_exceptions(
+ self, mock_ruff: MagicMock
+ ) -> None:
+ """Test RuffFormatter propagates exceptions from ruff function."""
+ mock_ruff.side_effect = ModuleNotFoundError("ruff not found")
+
+ formatter = RuffFormatter(line_length=88)
+ codes: CellCodes = {"cell1": "x=1"}
+
+ with pytest.raises(ModuleNotFoundError):
+ await formatter.format(codes)
+
+
+class TestBlackFormatter:
+ """Test the BlackFormatter class."""
+
+ @patch("marimo._dependencies.dependencies.DependencyManager.black")
+ async def test_black_formatter_requires_dependency(
+ self, mock_black: MagicMock
+ ):
+ """Test BlackFormatter calls require on black dependency."""
+ mock_black.require.side_effect = ModuleNotFoundError("black required")
+
+ formatter = BlackFormatter(line_length=88)
+ codes: CellCodes = {"cell1": "x=1"}
+
+ with pytest.raises(ModuleNotFoundError):
+ await formatter.format(codes)
+
+ mock_black.require.assert_called_once_with("to enable code formatting")
+
+ @patch("asyncio.to_thread")
+ @patch("marimo._dependencies.dependencies.DependencyManager.black")
+ async def test_black_formatter_formats_code_successfully(
+ self, mock_black_dep: MagicMock, mock_to_thread: MagicMock
+ ):
+ """Test BlackFormatter successfully formats code using black."""
+ # Mock dependency requirement to pass
+ mock_black_dep.require.return_value = None
+
+ # Mock black module with __spec__ attribute
+ mock_black = MagicMock()
+ mock_black.__spec__ = MagicMock()
+ mock_mode = MagicMock()
+ mock_black.Mode.return_value = mock_mode
+ mock_black.format_str.return_value = "formatted_code\n"
+
+ with patch.dict(sys.modules, {"black": mock_black}):
+ mock_to_thread.return_value = "formatted_code\n"
+
+ formatter = BlackFormatter(line_length=100)
+ codes: CellCodes = {"cell1": "x=1", "cell2": "y=2"}
+
+ result = await formatter.format(codes)
+
+ assert result == {
+ "cell1": "formatted_code",
+ "cell2": "formatted_code",
+ }
+ mock_black.Mode.assert_called_with(line_length=100)
+ assert mock_to_thread.call_count == 2
+
+ @patch("asyncio.to_thread")
+ @patch("marimo._dependencies.dependencies.DependencyManager.black")
+ async def test_black_formatter_handles_formatting_errors_gracefully(
+ self, mock_black_dep: MagicMock, mock_to_thread: MagicMock
+ ):
+ """Test BlackFormatter handles black formatting errors gracefully."""
+ # Mock dependency requirement to pass
+ mock_black_dep.require.return_value = None
+
+ # Mock black module with __spec__ attribute
+ mock_black = MagicMock()
+ mock_black.__spec__ = MagicMock()
+ mock_mode = MagicMock()
+ mock_black.Mode.return_value = mock_mode
+
+ with patch.dict(sys.modules, {"black": mock_black}):
+ # First call succeeds, second call fails
+ mock_to_thread.side_effect = [
+ "formatted_code\n",
+ Exception("Black error"),
+ ]
+
+ formatter = BlackFormatter(line_length=88)
+ codes: CellCodes = {"cell1": "x=1", "cell2": "y=2"}
+
+ result = await formatter.format(codes)
+
+ # Should return formatted code for successful cells, original for failed
+ assert result == {
+ "cell1": "formatted_code",
+ "cell2": "y=2",
+ }
+
+
+class TestRuffFunction:
+ """Test the ruff async function."""
+
+ @patch("marimo._utils.formatter._run_subprocess_safe")
+ async def test_ruff_function_with_module_ruff_available(
+ self, mock_subprocess_safe: MagicMock
+ ):
+ """Test ruff function when ruff is available as a module."""
+ # Mock help command success, then format command success
+ mock_subprocess_safe.side_effect = [
+ (b"", b"", 0), # help command success
+ (b"formatted_code\n", b"", 0), # format command success
+ ]
+
+ codes: CellCodes = {"cell1": "x=1"}
+ result = await ruff(codes, "format", "--line-length", "88")
+
+ assert result == {"cell1": "formatted_code"}
+
+ # Check that help command was called first
+ help_call = mock_subprocess_safe.call_args_list[0]
+ assert help_call[0] == (sys.executable, "-m", "ruff", "--help")
+
+ # Check that format command was called
+ format_call = mock_subprocess_safe.call_args_list[1]
+ assert format_call[0] == (
+ sys.executable,
+ "-m",
+ "ruff",
+ "format",
+ "--line-length",
+ "88",
+ "-",
+ )
+ assert format_call[1]["input_data"] == b"x=1"
+
+ @patch("marimo._utils.formatter._run_subprocess_safe")
+ async def test_ruff_function_falls_back_to_global_ruff(
+ self, mock_subprocess_safe: MagicMock
+ ):
+ """Test ruff function falls back to global ruff when module unavailable."""
+ # Mock module ruff failing, global ruff succeeding for help, then format success
+ mock_subprocess_safe.side_effect = [
+ (b"", b"", 1), # module help fails
+ (b"", b"", 0), # global help succeeds
+ (b"formatted_code\n", b"", 0), # format succeeds
+ ]
+
+ codes: CellCodes = {"cell1": "x=1"}
+ result = await ruff(codes, "format")
+
+ assert result == {"cell1": "formatted_code"}
+
+ # Check that global ruff was used for format command
+ format_call = mock_subprocess_safe.call_args_list[2]
+ assert format_call[0] == ("ruff", "format", "-")
+ assert format_call[1]["input_data"] == b"x=1"
+
+ @patch("marimo._utils.formatter._run_subprocess_safe")
+ async def test_ruff_function_raises_module_not_found_when_unavailable(
+ self, mock_subprocess_safe: MagicMock
+ ):
+ """Test ruff function raises ModuleNotFoundError when ruff is unavailable."""
+ # Mock both module and global ruff failing
+ mock_subprocess_safe.return_value = (b"", b"", 1)
+
+ codes: CellCodes = {"cell1": "x=1"}
+
+ with pytest.raises(ModuleNotFoundError) as exc_info:
+ await ruff(codes, "format")
+
+ assert "ruff" in str(exc_info.value)
+ assert exc_info.value.name == "ruff"
+
+ @patch("marimo._utils.formatter._run_subprocess_safe")
+ async def test_ruff_function_handles_format_failures_gracefully(
+ self, mock_subprocess_safe: MagicMock
+ ):
+ """Test ruff function handles individual cell formatting failures gracefully."""
+ # Mock help command success, then format commands - one success, one failure
+ mock_subprocess_safe.side_effect = [
+ (b"", b"", 0), # help succeeds
+ (b"formatted_code\n", b"", 0), # first format succeeds
+ (b"", b"syntax error", 1), # second format fails
+ ]
+
+ codes: CellCodes = {"cell1": "x=1", "cell2": "invalid syntax"}
+ result = await ruff(codes, "format")
+
+ # Should only include successfully formatted code
+ assert result == {"cell1": "formatted_code"}
+
+ @patch("marimo._utils.formatter.LOGGER")
+ @patch("marimo._utils.formatter._run_subprocess_safe")
+ async def test_ruff_function_handles_communication_exceptions(
+ self, mock_subprocess_safe: MagicMock, mock_logger: MagicMock
+ ):
+ """Test ruff function handles communication exceptions gracefully."""
+ del mock_logger
+ # Mock help command success, then format command that raises exception
+ mock_subprocess_safe.side_effect = [
+ (b"", b"", 0), # help succeeds
+ Exception("Communication failed"), # format fails with exception
+ ]
+
+ codes: CellCodes = {"cell1": "x=1"}
+ result = await ruff(codes, "format")
+
+ # Should return empty dict when all cells fail
+ assert result == {}
+
+ @patch("marimo._utils.formatter._run_subprocess_safe")
+ async def test_ruff_function_strips_whitespace_from_output(
+ self, mock_subprocess_safe: MagicMock
+ ):
+ """Test ruff function strips whitespace from formatted output."""
+ # Mock help command success, then format with whitespace in output
+ mock_subprocess_safe.side_effect = [
+ (b"", b"", 0), # help succeeds
+ (b" formatted_code \n\n", b"", 0), # format with whitespace
+ ]
+
+ codes: CellCodes = {"cell1": "x=1"}
+ result = await ruff(codes, "format")
+
+ assert result == {"cell1": "formatted_code"}
+
+ @patch("marimo._utils.formatter.LOGGER")
+ @patch("marimo._utils.formatter._run_subprocess_safe")
+ async def test_ruff_function_raises_format_error_on_non_zero_exit(
+ self, mock_subprocess_safe: MagicMock, mock_logger: MagicMock
+ ):
+ """Test ruff function raises FormatError when format command fails."""
+ del mock_logger
+ # Mock help command success, then format command that fails
+ mock_subprocess_safe.side_effect = [
+ (b"", b"", 0), # help succeeds
+ (b"", b"format error", 1), # format fails
+ ]
+
+ codes: CellCodes = {"cell1": "x=1"}
+ result = await ruff(codes, "format")
+
+ # Should skip failed cells
+ assert result == {}
+
+ @patch("asyncio.to_thread")
+ @patch("asyncio.create_subprocess_exec")
+ async def test_run_subprocess_safe_falls_back_on_windows(
+ self, mock_subprocess_exec: MagicMock, mock_to_thread: MagicMock
+ ):
+ """Test _run_subprocess_safe falls back to subprocess.run on Windows."""
+ from marimo._utils.formatter import _run_subprocess_safe
+
+ # Mock asyncio.create_subprocess_exec to raise NotImplementedError (Windows behavior)
+ mock_subprocess_exec.side_effect = NotImplementedError()
+
+ # Mock asyncio.to_thread to return subprocess result
+ mock_to_thread.return_value = (b"output", b"error", 0)
+
+ result = await _run_subprocess_safe("python", "--version")
+
+ assert result == (b"output", b"error", 0)
+ mock_to_thread.assert_called_once()
+
+
+class TestFormatError:
+ """Test the FormatError exception class."""
+
+ def test_format_error_is_exception(self) -> None:
+ """Test FormatError is a proper Exception subclass."""
+ error = FormatError("test message")
+ assert isinstance(error, Exception)
+ assert str(error) == "test message"
+
+ def test_format_error_can_be_raised_and_caught(self) -> None:
+ """Test FormatError can be raised and caught properly."""
+ with pytest.raises(FormatError) as exc_info:
+ raise FormatError("test formatting error")
+
+ assert str(exc_info.value) == "test formatting error"
+
+
+class TestFormatterIntegration:
+ """Integration tests for formatter classes working together."""
+
+ async def test_formatter_inheritance_structure(self) -> None:
+ """Test that all formatter classes inherit from base Formatter properly."""
+ assert issubclass(DefaultFormatter, Formatter)
+ assert issubclass(RuffFormatter, Formatter)
+ assert issubclass(BlackFormatter, Formatter)
+
+ async def test_all_formatters_accept_line_length_parameter(self) -> None:
+ """Test all formatters accept and store line_length parameter."""
+ formatters = [
+ Formatter(100),
+ DefaultFormatter(100),
+ RuffFormatter(100),
+ BlackFormatter(100),
+ ]
+
+ for formatter in formatters:
+ assert formatter.line_length == 100
+
+ async def test_cell_codes_type_alias_works_correctly(self) -> None:
+ """Test CellCodes type alias works as expected."""
+ codes: CellCodes = {"cell1": "code1", "cell2": "code2"}
+ assert isinstance(codes, dict)
+ assert all(isinstance(k, str) for k in codes.keys())
+ assert all(isinstance(v, str) for v in codes.values())