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
improvement: errors should stay internal in marimo run and logged to console (#3150)
Myles Scolnick6af7f9148a61
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsxindex 8a9ba2f5e1..36d4126638 100644--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx@@ -156,6 +156,10 @@ export const MarimoErrorOutput = ({</Tip></div>);+ case "internal":+ titleContents = "An internal error occurred";+ return <p key={idx}>{error.msg}</p>;+case "ancestor-prevented":titleContents = "Ancestor prevented from running";alertVariant = "default";diff --git a/frontend/src/components/ui/toast.tsx b/frontend/src/components/ui/toast.tsxindex 5da6e6f0b8..7f5a499f1f 100644--- a/frontend/src/components/ui/toast.tsx+++ b/frontend/src/components/ui/toast.tsx@@ -15,7 +15,7 @@ const ToastViewport = React.forwardRef<<ToastPrimitives.Viewportref={ref}className={cn(- "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",+ "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:w-fit md:max-w-[420px]",className,)}{...props}diff --git a/frontend/src/core/cells/logs.ts b/frontend/src/core/cells/logs.tsindex 48f4402114..241f01b681 100644--- a/frontend/src/core/cells/logs.ts+++ b/frontend/src/core/cells/logs.ts@@ -4,6 +4,7 @@ import type { CellMessage, OutputMessage } from "../kernel/messages";import type { CellId } from "./ids";import { fromUnixTime } from "date-fns";import { isErrorMime } from "../mime";+import { toast } from "@/components/ui/use-toast";export interface CellLog {timestamp: number;@@ -12,6 +13,8 @@ export interface CellLog {cellId: CellId;}+let didAlreadyToastError = false;+export function getCellLogsForMessage(cell: CellMessage): CellLog[] {const logs: CellLog[] = [];const consoleOutputs: OutputMessage[] = [cell.console].filter(Boolean).flat();@@ -56,6 +59,19 @@ export function getCellLogsForMessage(cell: CellMessage): CellLog[] {message: JSON.stringify(error),});});++ const shouldToast = cell.output.data.some(+ (error) => error.type === "internal",+ );+ if (!didAlreadyToastError && shouldToast) {+ didAlreadyToastError = true;+ toast({+ title: "An internal error occurred",+ description: "See console for details.",+ className:+ "text-xs text-background bg-[var(--red-10)] py-2 pl-3 [&>*]:flex [&>*]:gap-3",+ });+ }}return logs;diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex 73e008063b..10fbef596d 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -59,6 +59,7 @@ def _generate_schema() -> dict[str, Any]:errors.MultipleDefinitionError,errors.DeleteNonlocalError,errors.MarimoInterruptionError,+ errors.MarimoInternalError,errors.MarimoAncestorStoppedError,errors.MarimoAncestorPreventedError,errors.MarimoStrictExecutionError,diff --git a/marimo/_messaging/errors.py b/marimo/_messaging/errors.pyindex 0349372078..d6e9ff6aac 100644--- a/marimo/_messaging/errors.py+++ b/marimo/_messaging/errors.py@@ -107,6 +107,50 @@ class MarimoStrictExecutionError:return self.msg+@dataclass+class MarimoInternalError:+ """+ An internal error that should be hidden from the user.+ The error is logged to the console and then a new error is broadcasted+ such that the data is hidden.++ They can be linked back to the original error by the error_id.+ """++ error_id: str+ type: Literal["internal"] = "internal"+ msg: str = ""++ def __post_init__(self) -> None:+ self.msg = f"An internal error occurred: {self.error_id}"++ def describe(self) -> str:+ return self.msg+++def is_unexpected_error(error: Error) -> bool:+ """+ These errors are unexpected, in that they are not intentional.+ mo.stop and interrupt are intentional.+ """+ return error.type not in [+ "ancestor-prevented",+ "ancestor-stopped",+ "interruption",+ ]+++def is_sensitive_error(error: Error) -> bool:+ """+ These errors are sensitive, in that they are intentional.+ """+ return error.type not in [+ "ancestor-prevented",+ "ancestor-stopped",+ "internal",+ ]++Error = Union[CycleError,MultipleDefinitionError,@@ -117,5 +161,6 @@ Error = Union[MarimoStrictExecutionError,MarimoInterruptionError,MarimoSyntaxError,+ MarimoInternalError,UnknownError,]diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 7496b6c654..7d84e623f5 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -23,6 +23,7 @@ from typing import (Union,cast,)+from uuid import uuid4from marimo import _loggers as loggersfrom marimo._ast.app import _AppConfig@@ -31,7 +32,11 @@ from marimo._data.models import ColumnSummary, DataTable, DataTableSourcefrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.completion_option import CompletionOption-from marimo._messaging.errors import Error+from marimo._messaging.errors import (+ Error,+ MarimoInternalError,+ is_sensitive_error,+)from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._messaging.streams import OUTPUT_MAX_BYTESfrom marimo._messaging.types import Stream@@ -41,6 +46,7 @@ from marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._plugins.ui._impl.tables.utils import get_table_manager_or_nonefrom marimo._runtime.context import get_context+from marimo._runtime.context.utils import get_modefrom marimo._runtime.layout.layout import LayoutConfigfrom marimo._utils.platform import is_pyodide, is_windows@@ -248,12 +254,32 @@ class CellOp(Op):cell_id: CellId_t,) -> None:console: Optional[list[CellOutput]] = [] if clear_console else None++ # In run mode, we don't want to broadcast the error. Instead we want to print the error to the console+ # and then broadcast a new error such that the data is hidden.+ safe_errors: list[Error] = []+ if get_mode() == "run":+ for error in data:+ # Skip non-sensitive errors+ if not is_sensitive_error(error):+ safe_errors.append(error)+ continue++ error_id = uuid4()+ LOGGER.error(+ f"(error_id={error_id}) {error.describe()}",+ extra={"error_id": error_id},+ )+ safe_errors.append(MarimoInternalError(error_id=str(error_id)))+ else:+ safe_errors = list(data)+CellOp(cell_id=cell_id,output=CellOutput(channel=CellChannel.MARIMO_ERROR,mimetype="application/vnd.marimo+error",- data=data,+ data=safe_errors,),console=console,status=None,diff --git a/marimo/_runtime/context/utils.py b/marimo/_runtime/context/utils.pyindex 80f7cff110..67b20636ba 100644--- a/marimo/_runtime/context/utils.py+++ b/marimo/_runtime/context/utils.py@@ -5,8 +5,8 @@ from typing import Literal, Optionalfrom marimo._output.rich_help import mddocfrom marimo._runtime.context import ContextNotInitializedError, get_context-from marimo._runtime.context.kernel_context import KernelRuntimeContext-from marimo._runtime.context.script_context import ScriptRuntimeContext+from marimo._server.model import SessionMode+from marimo._utils.assert_never import assert_never@mddoc@@ -18,6 +18,8 @@ def running_in_notebook() -> bool:except ContextNotInitializedError:return Falseelse:+ from marimo._runtime.context.kernel_context import KernelRuntimeContext+return isinstance(ctx, KernelRuntimeContext)@@ -29,9 +31,18 @@ def get_mode() -> Optional[Literal["run", "edit", "script"]]:or None if marimo has no context initialized."""try:+ from marimo._runtime.context.kernel_context import KernelRuntimeContext+ from marimo._runtime.context.script_context import ScriptRuntimeContext+context = get_context()if isinstance(context, KernelRuntimeContext):- return context.session_mode # type: ignore+ if context.session_mode == SessionMode.RUN:+ return "run"+ elif context.session_mode == SessionMode.EDIT:+ return "edit"+ else:+ assert_never(context.session_mode)+if isinstance(context, ScriptRuntimeContext):return "script"except ContextNotInitializedError:diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.pyindex 759a95b03b..c466a85a07 100644--- a/marimo/_server/asgi.py+++ b/marimo/_server/asgi.py@@ -501,6 +501,7 @@ def create_asgi_app(# to each applicationcli_args={},auth_token=auth_token,+ redirect_console_to_browser=False,)app = create_starlette_app(base_url="",diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex e15221f586..2b57a7918b 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -4,14 +4,14 @@ from __future__ import annotationsimport asyncioimport sysfrom dataclasses import dataclass-from typing import Any, Callable, Literal, Optional, cast+from typing import Any, Callable, Literal, Optional, Union, castfrom marimo._cli.print import echofrom marimo._config.manager import (get_default_config_manager,)from marimo._messaging.cell_output import CellChannel-from marimo._messaging.errors import Error+from marimo._messaging.errors import Error, is_unexpected_errorfrom marimo._messaging.ops import MessageOperationfrom marimo._messaging.types import KernelMessagefrom marimo._output.hypertext import patch_html_for_non_interactive_output@@ -109,18 +109,22 @@ def export_as_wasm(async def run_app_then_export_as_ipynb(- path: MarimoPath,+ path_or_file_manager: Union[MarimoPath, AppFileManager],sort_mode: Literal["top-down", "topological"],cli_args: SerializedCLIArgs,) -> ExportResult:- file_router = AppFileRouter.from_filename(path)- file_key = file_router.get_unique_file_key()- assert file_key is not None- file_manager = file_router.get_file_manager(file_key)+ if isinstance(path_or_file_manager, AppFileManager):+ file_manager = path_or_file_manager+ else:+ file_router = AppFileRouter.from_filename(path_or_file_manager)+ file_key = file_router.get_unique_file_key()+ assert file_key is not None+ file_manager = file_router.get_file_manager(file_key)with patch_html_for_non_interactive_output():(session_view, did_error) = await run_app_until_completion(- file_manager, cli_args+ file_manager,+ cli_args,)result = Exporter().export_as_ipynb(@@ -146,7 +150,8 @@ async def run_app_then_export_as_html(config = get_default_config_manager(current_path=file_manager.path)session_view, did_error = await run_app_until_completion(- file_manager, cli_args+ file_manager,+ cli_args,)# Export the session as HTMLhtml, filename = Exporter().export_as_html(@@ -222,10 +227,7 @@ async def run_app_until_completion(for err in errors:parsed = parse_raw({"error": err}, Container)# Not all errors are fatal- if parsed.error.type not in [- "ancestor-prevented",- "ancestor-stopped",- ]:+ if is_unexpected_error(parsed.error):echo(f"{parsed.error.__class__.__name__}: {parsed.error.describe()}",file=sys.stderr,diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 96b72e3d42..e777948e96 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -164,7 +164,7 @@ class KernelManager:app_metadata: AppMetadata,user_config_manager: MarimoConfigReader,virtual_files_supported: bool,- redirect_console_to_browser: bool = False,+ redirect_console_to_browser: bool,) -> None:self.kernel_task: Optional[threading.Thread] | Optional[mp.Process]self.queue_manager = queue_manager@@ -661,7 +661,7 @@ class SessionManager:user_config_manager: MarimoConfigReader,cli_args: SerializedCLIArgs,auth_token: Optional[AuthToken],- redirect_console_to_browser: bool = False,+ redirect_console_to_browser: bool,) -> None:self.file_router = file_routerself.mode = modediff --git a/openapi/api.yaml b/openapi/api.yamlindex 8758460155..f26d70ad71 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -505,6 +505,7 @@ components:- $ref: '#/components/schemas/MarimoStrictExecutionError'- $ref: '#/components/schemas/MarimoInterruptionError'- $ref: '#/components/schemas/MarimoSyntaxError'+ - $ref: '#/components/schemas/MarimoInternalError'- $ref: '#/components/schemas/UnknownError'ExecuteMultipleRequest:properties:@@ -1269,6 +1270,21 @@ components:- name- pathtype: object+ MarimoInternalError:+ properties:+ error_id:+ type: string+ msg:+ type: string+ type:+ enum:+ - internal+ type: string+ required:+ - error_id+ - type+ - msg+ type: objectMarimoInterruptionError:properties:type:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex da72e81f54..f0a3d2ac45 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2249,6 +2249,7 @@ export interface components {| components["schemas"]["MarimoStrictExecutionError"]| components["schemas"]["MarimoInterruptionError"]| components["schemas"]["MarimoSyntaxError"]+ | components["schemas"]["MarimoInternalError"]| components["schemas"]["UnknownError"];ExecuteMultipleRequest: {cellIds: string[];@@ -2555,6 +2556,12 @@ export interface components {path: string;sessionId?: string | null;};+ MarimoInternalError: {+ error_id: string;+ msg: string;+ /** @enum {string} */+ type: "internal";+ };MarimoInterruptionError: {/** @enum {string} */type: "interruption";diff --git a/tests/_runtime/test_app_mode.py b/tests/_runtime/test_app_mode.pyindex 108eba1b88..aae5cc2b72 100644--- a/tests/_runtime/test_app_mode.py+++ b/tests/_runtime/test_app_mode.py@@ -8,12 +8,13 @@ from marimo._runtime.context import (from marimo._runtime.context.kernel_context import KernelRuntimeContextfrom marimo._runtime.context.script_context import ScriptRuntimeContextfrom marimo._runtime.context.utils import get_mode+from marimo._server.model import SessionModedef test_get_mode_kernel_run():"""Test get_mode() returns 'run' when in kernel run mode"""mock_context = Mock(spec=KernelRuntimeContext)- mock_context.session_mode = "run"+ mock_context.session_mode = SessionMode.RUNwith patch("marimo._runtime.context.utils.get_context", return_value=mock_context@@ -24,7 +25,7 @@ def test_get_mode_kernel_run():def test_get_mode_kernel_edit():"""Test get_mode() returns 'edit' when in kernel edit mode"""mock_context = Mock(spec=KernelRuntimeContext)- mock_context.session_mode = "edit"+ mock_context.session_mode = SessionMode.EDITwith patch("marimo._runtime.context.utils.get_context", return_value=mock_contextdiff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 8ae2c641fc..0f89ea8e87 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -3,12 +3,14 @@ from __future__ import annotationsimport sysimport textwrap+from dataclasses import dataclassfrom typing import TYPE_CHECKING, Sequenceimport pytestfrom marimo._config.config import DEFAULT_CONFIGfrom marimo._dependencies.dependencies import DependencyManager+from marimo._messaging.cell_output import CellChannelfrom marimo._messaging.errors import (CycleError,DeleteNonlocalError,@@ -2541,3 +2543,78 @@ class TestStateTransitions:stream.messages.clear()await k.delete_cell(DeleteCellRequest(cell_id=er_2.cell_id))assert sum(1 for m in stream.messages if m[0] == "variables") == 1+++class TestErrorHandling:+ async def test_error_handling(+ self, mocked_kernel: MockedKernel, exec_req: ExecReqProvider+ ) -> None:+ k = mocked_kernel.k+ await k.run([exec_req.get("raise ValueError('some secret error')")])+ cell_ops = mocked_kernel.stream.cell_ops+ error_cell_op = _filter_to_error_ops(cell_ops)+ assert len(error_cell_op) == 1+ errors = _parse_error_output(error_cell_op[0])++ assert len(errors) == 1+ assert errors[0].type == "exception"+ assert (+ errors[0].msg+ == "This cell raised an exception: ValueError('some secret error')"+ )++ async def test_error_handling_in_run_mode(+ self, run_mode_kernel: MockedKernel, exec_req: ExecReqProvider+ ) -> None:+ k = run_mode_kernel.k+ await k.run([exec_req.get("raise ValueError('some secret error')")])+ cell_ops = run_mode_kernel.stream.cell_ops+ error_cell_op = _filter_to_error_ops(cell_ops)+ assert len(error_cell_op) == 1+ errors = _parse_error_output(error_cell_op[0])++ assert len(errors) == 1+ assert errors[0].type == "internal"+ assert errors[0].msg.startswith("An internal error occurred: ")++ async def test_error_handling_in_run_mode_stop(+ self, run_mode_kernel: MockedKernel, exec_req: ExecReqProvider+ ) -> None:+ k = run_mode_kernel.k+ await k.run(+ [+ exec_req.get("x = 10"),+ exec_req.get("x = 20"),+ ]+ )+ cell_ops = run_mode_kernel.stream.cell_ops+ error_cell_op = _filter_to_error_ops(cell_ops)+ assert len(error_cell_op) == 2+ for op in error_cell_op:+ errors = _parse_error_output(op)+ assert len(errors) == 1+ assert errors[0].type == "internal"+ assert errors[0].msg.startswith("An internal error occurred: ")+++def _parse_error_output(cell_op: CellOp) -> list[Error]:+ error_output = cell_op.output+ assert error_output is not None+ assert error_output.channel == CellChannel.MARIMO_ERROR+ assert error_output.mimetype == "application/vnd.marimo+error"+ data = error_output.data++ @dataclass+ class Container:+ errors: list[Error]++ return parse_raw({"errors": data}, Container).errors+++def _filter_to_error_ops(cell_ops: list[CellOp]) -> list[CellOp]:+ return [+ op+ for op in cell_ops+ if op.output is not None+ and op.output.channel == CellChannel.MARIMO_ERROR+ ]diff --git a/tests/_server/export/snapshots/run_until_completion_with_stack_trace.txt b/tests/_server/export/snapshots/run_until_completion_with_stack_trace.txtnew file mode 100644index 0000000000..0c5705ad8b--- /dev/null+++ b/tests/_server/export/snapshots/run_until_completion_with_stack_trace.txt@@ -0,0 +1,30 @@+[+ {+ "output": "",+ "console": [+ "running internal tests\n"+ ],+ "status": "idle"+ },+ {+ "output": "<pre style='font-size: 12px'>15</pre>",+ "console": [+ "internal error\n"+ ],+ "status": "idle"+ },+ {+ "output": [+ {+ "msg": "This cell raised an exception: ValueError('Failed to authenticate. The correct password is 's3cret'.')",+ "exception_type": "ValueError",+ "raising_cell": null,+ "type": "exception"+ }+ ],+ "console": [+ "<span class=\"codehilite\"><div class=\"highlight\"><pre><span></span><span class=\"gt\">Traceback (most recent call last):</span>\n "</span>, line <span class=\"m\">3</span>, in <span class=\"n\"><module></span>\n<span class=\"w\"> </span><span class=\"k\">raise</span> <span class=\"ne\">ValueError</span><span class=\"p\">(</span>\n<span class=\"gr\">ValueError</span>: <span class=\"n\">Failed to authenticate. The correct password is 's3cret'.</span>\n</pre></div>\n</span>"+ ],+ "status": "idle"+ }+]\ No newline at end of filediff --git a/tests/_server/export/snapshots/run_until_completion_with_stop.txt b/tests/_server/export/snapshots/run_until_completion_with_stop.txtindex ab296d9de4..043bc215dd 100644--- a/tests/_server/export/snapshots/run_until_completion_with_stop.txt+++ b/tests/_server/export/snapshots/run_until_completion_with_stop.txt@@ -1 +1,23 @@-["", "", [{"msg": "This cell wasn't run because an ancestor was stopped with `mo.stop`: ", "raising_cell": "MJUe", "type": "ancestor-stopped"}]]\ No newline at end of file+[+ {+ "output": "",+ "console": [],+ "status": "idle"+ },+ {+ "output": "",+ "console": [],+ "status": "idle"+ },+ {+ "output": [+ {+ "msg": "This cell wasn't run because an ancestor was stopped with `mo.stop`: ",+ "raising_cell": "MJUe",+ "type": "ancestor-stopped"+ }+ ],+ "console": [],+ "status": "idle"+ }+]\ No newline at end of filediff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.pyindex 3e6ac873be..497c89b319 100644--- a/tests/_server/export/test_exporter.py+++ b/tests/_server/export/test_exporter.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+from typing import Anyimport pytest@@ -8,8 +9,10 @@ from marimo._ast.app import App, InternalAppfrom marimo._config.config import DEFAULT_CONFIGfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.ops import CellOp-from marimo._output.hypertext import patch_html_for_non_interactive_output-from marimo._server.export import run_app_until_completion+from marimo._server.export import (+ run_app_then_export_as_ipynb,+ run_app_until_completion,+)from marimo._server.export.exporter import Exporterfrom marimo._server.file_manager import AppFileManagerfrom tests.mocks import snapshotter@@ -212,18 +215,14 @@ async def test_export_ipynb_with_outputs():file_manager, sort_mode="top-down", session_view=None)assert filename == "notebook.ipynb"+ assert content is not None- # Create a session view with outputs- with patch_html_for_non_interactive_output():- session_view, did_error = await run_app_until_completion(- file_manager, cli_args={}- )- content, filename = exporter.export_as_ipynb(- file_manager, sort_mode="top-down", session_view=session_view+ result = await run_app_then_export_as_ipynb(+ file_manager, sort_mode="top-down", cli_args={})- assert not did_error- assert filename == "notebook.ipynb"- snapshot("notebook_with_outputs.ipynb.txt", content)+ assert not result.did_error+ assert result.download_filename == "notebook.ipynb"+ snapshot("notebook_with_outputs.ipynb.txt", result.contents)async def test_run_until_completion_with_stop():@@ -253,13 +252,46 @@ async def test_run_until_completion_with_stop():file_manager, cli_args={})assert did_error is False- output_data = [- op for op in session_view.operations if isinstance(op, CellOp)- ]- serialized_out = json.dumps(- [op.output.data for op in output_data if op.output is not None]+ cell_ops = [op for op in session_view.operations if isinstance(op, CellOp)]+ snapshot("run_until_completion_with_stop.txt", _print_messages(cell_ops))+++async def test_run_until_completion_with_stack_trace():+ app = App()++ @app.cell()+ def _():+ print("running internal tests")+ return++ @app.cell()+ def _():+ import sys++ sys.stderr.write("internal error\n")+ return++ @app.cell()+ def _():+ given_password = "test"+ if given_password != "s3cret":+ raise ValueError(+ "Failed to authenticate. The correct password is 's3cret'."+ )+ return++ file_manager = AppFileManager.from_app(InternalApp(app))++ # When not redirected, the stack trace is not included in the output+ session_view, did_error = await run_app_until_completion(+ file_manager, cli_args={}+ )+ assert did_error is True+ cell_ops = [op for op in session_view.operations if isinstance(op, CellOp)]+ snapshot(+ "run_until_completion_with_stack_trace.txt",+ _delete_lines_with_files(_print_messages(cell_ops)),)- snapshot("run_until_completion_with_stop.txt", serialized_out)async def test_export_wasm_edit():@@ -306,3 +338,43 @@ async def test_export_wasm_run():assert filename == "notebook.wasm.html"assert "alert(" in contentassert "mode='read'" in content+++def _print_messages(messages: list[CellOp]) -> 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,+ }+ )+ return json.dumps(result, indent=2)+++def _as_list(data: Any) -> list[Any]:+ if isinstance(data, list):+ return data # type: ignore+ return [data]+++def _delete_lines_with_files(output: str) -> str:+ # Remove any line that contains "File " up until a .py ending+ def remove_file_name(line: str) -> str:+ if "File " not in line:+ return line+ start = line.index("File ")+ end = line.rindex(".py") + 3+ return line[0:start] + line[end:]++ return "\n".join(remove_file_name(line) for line in output.splitlines())diff --git a/tests/_server/mocks.py b/tests/_server/mocks.pyindex 2b9ec87800..ab825d84e5 100644--- a/tests/_server/mocks.py+++ b/tests/_server/mocks.py@@ -56,6 +56,7 @@ if __name__ == "__main__":user_config_manager=get_default_config_manager(current_path=None),cli_args={},auth_token=AuthToken("fake-token"),+ redirect_console_to_browser=False,)sm.skew_protection_token = SkewProtectionToken("skew-id-1")return smdiff --git a/tests/_server/test_session_manager.py b/tests/_server/test_session_manager.pyindex 3329083f55..827f358482 100644--- a/tests/_server/test_session_manager.py+++ b/tests/_server/test_session_manager.py@@ -37,6 +37,7 @@ def session_manager():user_config_manager=get_default_config_manager(current_path=None),cli_args={},auth_token=None,+ redirect_console_to_browser=False,)diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex 2457f1190a..0e1dac549b 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -76,6 +76,7 @@ def test_kernel_manager_run_mode() -> None:app_metadata,get_default_config_manager(current_path=None),virtual_files_supported=True,+ redirect_console_to_browser=False,)kernel_manager.start_kernel()@@ -108,6 +109,7 @@ def test_kernel_manager_edit_mode() -> None:app_metadata,get_default_config_manager(current_path=None),virtual_files_supported=True,+ redirect_console_to_browser=False,)kernel_manager.start_kernel()@@ -139,6 +141,7 @@ def test_kernel_manager_interrupt(tmp_path) -> None:app_metadata,get_default_config_manager(current_path=None),virtual_files_supported=True,+ redirect_console_to_browser=False,)# Assert startup@@ -224,6 +227,7 @@ def test_session() -> None:app_metadata,get_default_config_manager(current_path=None),virtual_files_supported=True,+ redirect_console_to_browser=False,)# Instantiate a Session@@ -268,6 +272,7 @@ def test_session_disconnect_reconnect() -> None:AppMetadata(query_params={}, cli_args={}),get_default_config_manager(current_path=None),virtual_files_supported=True,+ redirect_console_to_browser=False,)# Instantiate a Session@@ -323,6 +328,7 @@ def test_session_with_kiosk_consumers() -> None:app_metadata,get_default_config_manager(current_path=None),virtual_files_supported=True,+ redirect_console_to_browser=False,)# Instantiate a Sessiondiff --git a/tests/conftest.py b/tests/conftest.pyindex 3cbc84e832..18f6c71313 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -16,6 +16,7 @@ from marimo._ast.app import CellManagerfrom marimo._ast.cell import CellId_tfrom marimo._config.config import DEFAULT_CONFIGfrom marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.ops import CellOp, MessageOperationfrom marimo._messaging.streams import (ThreadSafeStderr,ThreadSafeStdin,@@ -31,6 +32,7 @@ from marimo._runtime.marimo_pdb import MarimoPdbfrom marimo._runtime.requests import AppMetadata, ExecutionRequestfrom marimo._runtime.runtime import Kernelfrom marimo._server.model import SessionMode+from marimo._utils.parse_dataclass import parse_raw# register import hooks for third-party module formattersregister_formatters()@@ -47,6 +49,21 @@ class _MockStream(ThreadSafeStream):def write(self, op: str, data: dict[Any, Any]) -> None:self.messages.append((op, data))+ @property+ def operations(self) -> list[MessageOperation]:+ @dataclasses.dataclass+ class Container:+ operation: MessageOperation++ return [+ parse_raw({"operation": op_data}, Container).operation+ for _op_name, op_data in self.messages+ ]++ @property+ def cell_ops(self) -> list[CellOp]:+ return [op for op in self.operations if isinstance(op, CellOp)]+class MockStdout(ThreadSafeStdout):"""Captures the output sent through the stream"""@@ -99,6 +116,7 @@ class MockedKernel:"""Should only be created in fixtures b/c inits a runtime context"""stream: _MockStream = dataclasses.field(default_factory=_MockStream)+ session_mode: SessionMode = SessionMode.EDITdef __post_init__(self) -> None:self.stdout = MockStdout(self.stream)@@ -130,7 +148,7 @@ class MockedKernel:stdout=self.stdout, # type: ignorestderr=self.stderr, # type: ignorevirtual_files_supported=True,- mode=SessionMode.EDIT,+ mode=self.session_mode,)def teardown(self) -> None:@@ -169,6 +187,14 @@ def strict_kernel() -> Generator[Kernel, None, None]:mocked.teardown()+# kernel configured in SessionMode.RUN mode+def run_mode_kernel() -> Generator[MockedKernel, None, None]:+ mocked = MockedKernel(session_mode=SessionMode.RUN)+ yield mocked+ mocked.teardown()++@pytest.fixture(params=["k", "strict_kernel"])def execution_kernel(request: Any) -> Kernel:return request.getfixturevalue(request.param)