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
Add tests for missing coverage in marimo/_messaging (#4010)
devin-ai-integration[bot]4e001e2120ad
diff --git a/tests/_messaging/test_completion_option.py b/tests/_messaging/test_completion_option.pynew file mode 100644index 0000000000..7bfbb73d09--- /dev/null+++ b/tests/_messaging/test_completion_option.py@@ -0,0 +1,62 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from marimo._messaging.completion_option import CompletionOption+++class TestCompletionOption:+ def test_initialization(self) -> None:+ # Test basic initialization+ option = CompletionOption(+ name="test_function",+ type="function",+ completion_info="test_function(arg1, arg2) -> None",+ )++ assert option.name == "test_function"+ assert option.type == "function"+ assert option.completion_info == "test_function(arg1, arg2) -> None"++ def test_initialization_without_completion_info(self) -> None:+ # Test initialization without completion_info+ option = CompletionOption(+ name="test_var",+ type="variable",+ completion_info=None,+ )++ assert option.name == "test_var"+ assert option.type == "variable"+ assert option.completion_info is None++ def test_post_init_strips_trailing_quotes(self) -> None:+ # Test that __post_init__ strips trailing quotes+ option1 = CompletionOption(+ name='test_string"',+ type="string",+ completion_info=None,+ )+ assert option1.name == "test_string"++ option2 = CompletionOption(+ name="test_string'",+ type="string",+ completion_info=None,+ )+ assert option2.name == "test_string"++ # Test with multiple quotes+ option3 = CompletionOption(+ name='test_string"""',+ type="string",+ completion_info=None,+ )+ assert option3.name == "test_string"++ # Test with no quotes+ option4 = CompletionOption(+ name="test_string",+ type="string",+ completion_info=None,+ )+ assert option4.name == "test_string"diff --git a/tests/_messaging/test_console_output_worker.py b/tests/_messaging/test_console_output_worker.pynew file mode 100644index 0000000000..2267e01827--- /dev/null+++ b/tests/_messaging/test_console_output_worker.py@@ -0,0 +1,250 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import threading+import time+from collections import deque+from typing import Optional++from marimo._messaging.cell_output import CellChannel+from marimo._messaging.console_output_worker import (+ TIMEOUT_S,+ ConsoleMsg,+ _add_output_to_buffer,+ _can_merge_outputs,+ _write_console_output,+ buffered_writer,+)+from marimo._messaging.types import Stream+++class MockStream(Stream):+ def __init__(self) -> None:+ self.messages: list[tuple[str, dict]] = []++ def write(self, op: str, data: dict) -> None:+ self.messages.append((op, data))+++class TestConsoleOutputWorker:+ def test_can_merge_outputs(self) -> None:+ # Same stream and mimetype should be mergeable+ msg1 = ConsoleMsg(+ stream=CellChannel.STDOUT,+ cell_id="cell1",+ data="Hello",+ mimetype="text/plain",+ )+ msg2 = ConsoleMsg(+ stream=CellChannel.STDOUT,+ cell_id="cell1",+ data=" World",+ mimetype="text/plain",+ )+ assert _can_merge_outputs(msg1, msg2) is True++ # Different stream should not be mergeable+ msg3 = ConsoleMsg(+ stream=CellChannel.STDERR,+ cell_id="cell1",+ data="Error",+ mimetype="text/plain",+ )+ assert _can_merge_outputs(msg1, msg3) is False++ # Different mimetype should not be mergeable+ msg4 = ConsoleMsg(+ stream=CellChannel.STDOUT,+ cell_id="cell1",+ data="<h1>Hello</h1>",+ mimetype="text/html",+ )+ assert _can_merge_outputs(msg1, msg4) is False++ def test_add_output_to_buffer_new_cell(self) -> None:+ # Test adding output for a new cell+ outputs_buffered_per_cell = {}+ msg = ConsoleMsg(+ stream=CellChannel.STDOUT,+ cell_id="cell1",+ data="Hello",+ mimetype="text/plain",+ )++ _add_output_to_buffer(msg, outputs_buffered_per_cell)++ assert "cell1" in outputs_buffered_per_cell+ assert len(outputs_buffered_per_cell["cell1"]) == 1+ assert outputs_buffered_per_cell["cell1"][0].data == "Hello"++ def test_add_output_to_buffer_merge(self) -> None:+ # Test merging output for an existing cell with same stream and mimetype+ outputs_buffered_per_cell = {+ "cell1": [+ ConsoleMsg(+ stream=CellChannel.STDOUT,+ cell_id="cell1",+ data="Hello",+ mimetype="text/plain",+ )+ ]+ }+ msg = ConsoleMsg(+ stream=CellChannel.STDOUT,+ cell_id="cell1",+ data=" World",+ mimetype="text/plain",+ )++ _add_output_to_buffer(msg, outputs_buffered_per_cell)++ assert len(outputs_buffered_per_cell["cell1"]) == 1+ assert outputs_buffered_per_cell["cell1"][0].data == "Hello World"++ def test_add_output_to_buffer_no_merge(self) -> None:+ # Test adding output for an existing cell with different stream or mimetype+ outputs_buffered_per_cell = {+ "cell1": [+ ConsoleMsg(+ stream=CellChannel.STDOUT,+ cell_id="cell1",+ data="Hello",+ mimetype="text/plain",+ )+ ]+ }+ msg = ConsoleMsg(+ stream=CellChannel.STDERR,+ cell_id="cell1",+ data="Error",+ mimetype="text/plain",+ )++ _add_output_to_buffer(msg, outputs_buffered_per_cell)++ assert len(outputs_buffered_per_cell["cell1"]) == 2+ assert outputs_buffered_per_cell["cell1"][0].data == "Hello"+ assert outputs_buffered_per_cell["cell1"][1].data == "Error"++ def test_write_console_output(self) -> None:+ # Test writing console output to stream+ stream = MockStream()+ _write_console_output(+ stream,+ CellChannel.STDOUT,+ "cell1",+ "Hello",+ "text/plain",+ )++ assert len(stream.messages) == 1+ assert stream.messages[0][0] == "cell-op" # op+ assert stream.messages[0][1]["cell_id"] == "cell1"+ assert stream.messages[0][1]["console"]["channel"] == "stdout"+ assert stream.messages[0][1]["console"]["mimetype"] == "text/plain"+ assert stream.messages[0][1]["console"]["data"] == "Hello"++ def test_buffered_writer_basic(self) -> None:+ # Test basic functionality of buffered writer+ stream = MockStream()+ msg_queue: deque[Optional[ConsoleMsg]] = deque()+ cv = threading.Condition()++ # Start the buffered writer in a separate thread+ thread = threading.Thread(+ target=buffered_writer, args=(msg_queue, stream, cv)+ )+ thread.daemon = True+ thread.start()++ try:+ # Add a message to the queue+ with cv:+ msg_queue.append(+ ConsoleMsg(+ stream=CellChannel.STDOUT,+ cell_id="cell1",+ data="Hello",+ mimetype="text/plain",+ )+ )+ cv.notify()++ # Wait for the timeout to expire and the message to be written+ # Use a longer timeout to ensure the message is processed+ time.sleep(TIMEOUT_S * 5)++ # Check that the message was written to the stream+ assert len(stream.messages) == 1+ assert stream.messages[0][1]["console"]["data"] == "Hello"++ finally:+ # Signal the writer to terminate+ with cv:+ msg_queue.append(None)+ cv.notify()+ thread.join(timeout=1.0)++ def test_buffered_writer_multiple_messages(self) -> None:+ # Test buffered writer with multiple messages+ stream = MockStream()+ msg_queue: deque[Optional[ConsoleMsg]] = deque()+ cv = threading.Condition()++ # Start the buffered writer in a separate thread+ thread = threading.Thread(+ target=buffered_writer, args=(msg_queue, stream, cv)+ )+ thread.daemon = True+ thread.start()++ try:+ # Add multiple messages to the queue+ with cv:+ msg_queue.append(+ ConsoleMsg(+ stream=CellChannel.STDOUT,+ cell_id="cell1",+ data="Hello",+ mimetype="text/plain",+ )+ )+ msg_queue.append(+ ConsoleMsg(+ stream=CellChannel.STDOUT,+ cell_id="cell1",+ data=" World",+ mimetype="text/plain",+ )+ )+ msg_queue.append(+ ConsoleMsg(+ stream=CellChannel.STDERR,+ cell_id="cell1",+ data="Error",+ mimetype="text/plain",+ )+ )+ cv.notify()++ # Wait for the timeout to expire and the messages to be written+ # Use a longer timeout to ensure the messages are processed+ time.sleep(TIMEOUT_S * 5)++ # Check that the messages were written to the stream+ assert len(stream.messages) == 2 # Merged stdout messages + stderr++ # First message should be the merged stdout messages+ assert stream.messages[0][1]["console"]["channel"] == "stdout"+ assert stream.messages[0][1]["console"]["data"] == "Hello World"++ # Second message should be the stderr message+ assert stream.messages[1][1]["console"]["channel"] == "stderr"+ assert stream.messages[1][1]["console"]["data"] == "Error"++ finally:+ # Signal the writer to terminate+ with cv:+ msg_queue.append(None)+ cv.notify()+ thread.join(timeout=1.0)diff --git a/tests/_messaging/test_messaging_context.py b/tests/_messaging/test_messaging_context.pynew file mode 100644index 0000000000..be8458a1f8--- /dev/null+++ b/tests/_messaging/test_messaging_context.py@@ -0,0 +1,168 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import uuid++import pytest # noqa: F401++from marimo._messaging.context import (+ HTTP_REQUEST_CTX,+ RUN_ID_CTX,+ http_request_context,+ run_id_context,+)+from marimo._runtime.requests import HTTPRequest+++class TestRunIDContext:+ def test_run_id_context_manager(self) -> None:+ # Test that run_id_context sets and unsets the run ID+ with run_id_context() as ctx:+ # Run ID should be set within the context+ run_id = RUN_ID_CTX.get()+ assert run_id is not None+ assert isinstance(run_id, str)++ # Should be a valid UUID+ uuid_obj = uuid.UUID(run_id)+ assert str(uuid_obj) == run_id++ # Run ID should be unset outside the context+ with pytest.raises(LookupError):+ RUN_ID_CTX.get()++ def test_run_id_context_generates_unique_ids(self) -> None:+ # Test that run_id_context generates unique IDs+ with run_id_context() as ctx1:+ run_id1 = RUN_ID_CTX.get()++ with run_id_context() as ctx2:+ run_id2 = RUN_ID_CTX.get()++ # IDs should be different+ assert run_id1 != run_id2++ # Should restore the outer context+ assert RUN_ID_CTX.get() == run_id1++ # Run ID should be unset outside the context+ with pytest.raises(LookupError):+ RUN_ID_CTX.get()+++class TestHTTPRequestContext:+ def test_http_request_context_manager_with_request(self) -> None:+ # Test that http_request_context sets and unsets the HTTP request+ request = HTTPRequest(+ url={+ "path": "/test",+ "port": None,+ "scheme": "http",+ "netloc": "localhost",+ "query": "",+ "hostname": "localhost",+ },+ base_url={+ "path": "",+ "port": None,+ "scheme": "http",+ "netloc": "localhost",+ "query": "",+ "hostname": "localhost",+ },+ headers={},+ query_params={},+ path_params={},+ cookies={},+ meta={},+ user=None,+ )++ with http_request_context(request):+ # Request should be set within the context+ ctx_request = HTTP_REQUEST_CTX.get()+ assert ctx_request is not None+ assert ctx_request is request+ assert ctx_request.url["path"] == "/test"++ # Request should be unset outside the context+ with pytest.raises(LookupError):+ HTTP_REQUEST_CTX.get()++ def test_http_request_context_manager_with_none(self) -> None:+ # Test that http_request_context can set None+ with http_request_context(None):+ # Request should be None within the context+ ctx_request = HTTP_REQUEST_CTX.get()+ assert ctx_request is None++ # Request should be unset outside the context+ with pytest.raises(LookupError):+ HTTP_REQUEST_CTX.get()++ def test_nested_http_request_contexts(self) -> None:+ # Test nested http_request_contexts+ request1 = HTTPRequest(+ url={+ "path": "/test1",+ "port": None,+ "scheme": "http",+ "netloc": "localhost",+ "query": "",+ "hostname": "localhost",+ },+ base_url={+ "path": "",+ "port": None,+ "scheme": "http",+ "netloc": "localhost",+ "query": "",+ "hostname": "localhost",+ },+ headers={},+ query_params={},+ path_params={},+ cookies={},+ meta={},+ user=None,+ )++ request2 = HTTPRequest(+ url={+ "path": "/test2",+ "port": None,+ "scheme": "http",+ "netloc": "localhost",+ "query": "",+ "hostname": "localhost",+ },+ base_url={+ "path": "",+ "port": None,+ "scheme": "http",+ "netloc": "localhost",+ "query": "",+ "hostname": "localhost",+ },+ headers={},+ query_params={},+ path_params={},+ cookies={},+ meta={},+ user=None,+ )++ with http_request_context(request1):+ # Outer context should have request1+ assert HTTP_REQUEST_CTX.get() is request1++ with http_request_context(request2):+ # Inner context should have request2+ assert HTTP_REQUEST_CTX.get() is request2++ # Should restore the outer context+ assert HTTP_REQUEST_CTX.get() is request1++ # Request should be unset outside the context+ with pytest.raises(LookupError):+ HTTP_REQUEST_CTX.get()diff --git a/tests/_messaging/test_context_vars.py b/tests/_messaging/test_messaging_context_vars.pysimilarity index 96%rename from tests/_messaging/test_context_vars.pyrename to tests/_messaging/test_messaging_context_vars.pyindex 850b879156..e28a1cee92 100644--- a/tests/_messaging/test_context_vars.py+++ b/tests/_messaging/test_messaging_context_vars.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.from __future__ import annotationsimport uuid@@ -13,7 +14,7 @@ from marimo._messaging.context import (from marimo._runtime.requests import HTTPRequest-class TestRunIDContext:+class TestMessagingContextVarsRunID:def test_run_id_is_uuid(self):with run_id_context():run_id = RUN_ID_CTX.get()@@ -43,7 +44,7 @@ class TestRunIDContext:RUN_ID_CTX.get()-class TestHTTPRequestContext:+class TestMessagingContextVarsHTTP:@pytest.fixturedef mock_request(self):return HTTPRequest(diff --git a/tests/_messaging/test_messaging_errors.py b/tests/_messaging/test_messaging_errors.pynew file mode 100644index 0000000000..bc8ddbeae4--- /dev/null+++ b/tests/_messaging/test_messaging_errors.py@@ -0,0 +1,188 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from marimo._messaging.errors import (+ CycleError,+ DeleteNonlocalError,+ ImportStarError,+ MarimoAncestorPreventedError,+ MarimoAncestorStoppedError,+ MarimoExceptionRaisedError,+ MarimoInternalError,+ MarimoInterruptionError,+ MarimoStrictExecutionError,+ MarimoSyntaxError,+ MultipleDefinitionError,+ UnknownError,+ is_sensitive_error,+ is_unexpected_error,+)+++class TestErrorClasses:+ def test_cycle_error(self) -> None:+ # Create a cycle error with mock edges+ # EdgeWithVar is a tuple of (start_cell_id, variables, end_cell_id)+ edge1 = ("cell1", ["var1"], "cell2")+ edge2 = ("cell2", ["var2"], "cell1")++ error = CycleError(edges_with_vars=(edge1, edge2))++ # Test properties+ assert error.type == "cycle"+ assert "cycle" in error.describe().lower()+ assert isinstance(error.describe(), str)++ def test_multiple_definition_error(self) -> None:+ error = MultipleDefinitionError(+ name="test_var", cells=("cell1", "cell2")+ )++ # Test properties+ assert error.type == "multiple-defs"+ assert "test_var" in error.describe()+ assert "defined by another cell" in error.describe()++ def test_import_star_error(self) -> None:+ error = ImportStarError(msg="Cannot use import * in this context")++ # Test properties+ assert error.type == "import-star"+ assert error.describe() == "Cannot use import * in this context"++ def test_delete_nonlocal_error(self) -> None:+ error = DeleteNonlocalError(name="test_var", cells=("cell1", "cell2"))++ # Test properties+ assert error.type == "delete-nonlocal"+ assert "test_var" in error.describe()+ assert "can't be deleted" in error.describe()++ def test_marimo_interruption_error(self) -> None:+ error = MarimoInterruptionError()++ # Test properties+ assert error.type == "interruption"+ assert "interrupted" in error.describe().lower()+ assert "re-run" in error.describe().lower()++ def test_marimo_ancestor_prevented_error(self) -> None:+ error = MarimoAncestorPreventedError(+ msg="Execution prevented by ancestor",+ raising_cell="cell1",+ blamed_cell="cell2",+ )++ # Test properties+ assert error.type == "ancestor-prevented"+ assert error.describe() == "Execution prevented by ancestor"+ assert error.raising_cell == "cell1"+ assert error.blamed_cell == "cell2"++ def test_marimo_ancestor_stopped_error(self) -> None:+ error = MarimoAncestorStoppedError(+ msg="Execution stopped by ancestor",+ raising_cell="cell1",+ )++ # Test properties+ assert error.type == "ancestor-stopped"+ assert error.describe() == "Execution stopped by ancestor"+ assert error.raising_cell == "cell1"++ def test_marimo_exception_raised_error(self) -> None:+ error = MarimoExceptionRaisedError(+ msg="ValueError: invalid value",+ exception_type="ValueError",+ raising_cell="cell1",+ )++ # Test properties+ assert error.type == "exception"+ assert error.describe() == "ValueError: invalid value"+ assert error.raising_cell == "cell1"+ assert error.exception_type == "ValueError"++ def test_marimo_syntax_error(self) -> None:+ error = MarimoSyntaxError(msg="Invalid syntax")++ # Test properties+ assert error.type == "syntax"+ assert error.describe() == "Invalid syntax"++ def test_unknown_error(self) -> None:+ error = UnknownError(msg="Something went wrong")++ # Test properties+ assert error.type == "unknown"+ assert error.describe() == "Something went wrong"++ def test_marimo_strict_execution_error(self) -> None:+ error = MarimoStrictExecutionError(+ msg="Strict execution error",+ ref="some_reference",+ blamed_cell="cell1",+ )++ # Test properties+ assert error.type == "strict-exception"+ assert error.describe() == "Strict execution error"+ assert error.ref == "some_reference"+ assert error.blamed_cell == "cell1"++ def test_marimo_internal_error(self) -> None:+ error = MarimoInternalError(+ error_id="test-error-id",+ msg="Original error message",+ )++ # Test properties+ assert error.type == "internal"+ assert "An internal error occurred" in error.describe()+ assert "test-error-id" in error.describe()+ # The original message should be replaced with a generic one+ assert error.describe() != "Original error message"+++class TestErrorUtilityFunctions:+ def test_is_unexpected_error(self) -> None:+ # These errors are expected/intentional+ assert not is_unexpected_error(+ MarimoAncestorPreventedError(+ msg="", raising_cell="cell1", blamed_cell=None+ )+ )+ assert not is_unexpected_error(+ MarimoAncestorStoppedError(msg="", raising_cell="cell1")+ )+ assert not is_unexpected_error(MarimoInterruptionError())++ # These errors are unexpected+ assert is_unexpected_error(+ MarimoExceptionRaisedError(+ msg="", exception_type="", raising_cell=None+ )+ )+ assert is_unexpected_error(MarimoSyntaxError(msg=""))+ assert is_unexpected_error(UnknownError(msg=""))++ def test_is_sensitive_error(self) -> None:+ # These errors are not sensitive+ assert not is_sensitive_error(+ MarimoAncestorPreventedError(+ msg="", raising_cell="cell1", blamed_cell=None+ )+ )+ assert not is_sensitive_error(+ MarimoAncestorStoppedError(msg="", raising_cell="cell1")+ )+ assert not is_sensitive_error(MarimoInternalError(error_id=""))++ # These errors are sensitive+ assert is_sensitive_error(+ MarimoExceptionRaisedError(+ msg="", exception_type="", raising_cell=None+ )+ )+ assert is_sensitive_error(MarimoSyntaxError(msg=""))+ assert is_sensitive_error(UnknownError(msg=""))diff --git a/tests/_messaging/test_run_id_context.py b/tests/_messaging/test_messaging_run_id_context.pysimilarity index 70%rename from tests/_messaging/test_run_id_context.pyrename to tests/_messaging/test_messaging_run_id_context.pyindex f12b70c9b5..79966ce282 100644--- a/tests/_messaging/test_run_id_context.py+++ b/tests/_messaging/test_messaging_run_id_context.py@@ -1,10 +1,13 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import pytestfrom marimo._messaging.context import RUN_ID_CTX, run_id_context-class TestRunIDContext:- def test_run_id_context(self):+class TestMessagingRunIDContext:+ def test_run_id_context(self) -> None:with run_id_context():run_id = RUN_ID_CTX.get()assert run_id is not None, (diff --git a/tests/_messaging/test_mimetypes.py b/tests/_messaging/test_mimetypes.pynew file mode 100644index 0000000000..e653f95aba--- /dev/null+++ b/tests/_messaging/test_mimetypes.py@@ -0,0 +1,63 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any, cast++from marimo._messaging.mimetypes import (+ KnownMimeType,+ MimeBundle,+ MimeBundleOrTuple,+)+++class TestMimeTypes:+ def test_known_mime_type(self) -> None:+ # Test that KnownMimeType can be used as a type annotation+ def accepts_mime_type(mime_type: KnownMimeType) -> KnownMimeType:+ return mime_type++ # Test with various known mime types+ assert accepts_mime_type("text/plain") == "text/plain"+ assert accepts_mime_type("text/html") == "text/html"+ assert accepts_mime_type("application/json") == "application/json"+ assert accepts_mime_type("image/png") == "image/png"++ # The following would fail type checking but not at runtime+ # This test is just to verify the runtime behavior+ assert (+ accepts_mime_type(cast(KnownMimeType, "unknown/type"))+ == "unknown/type"+ )++ def test_mime_bundle(self) -> None:+ # Test that MimeBundle can be used as a type annotation+ def accepts_mime_bundle(bundle: MimeBundle) -> MimeBundle:+ return bundle++ # Create a valid mime bundle+ bundle: MimeBundle = {+ "text/plain": "Hello, world!",+ "text/html": "<h1>Hello, world!</h1>",+ }++ assert accepts_mime_bundle(bundle) == bundle++ # Test with empty bundle+ empty_bundle: MimeBundle = {}+ assert accepts_mime_bundle(empty_bundle) == empty_bundle++ def test_mime_bundle_or_tuple(self) -> None:+ # Test that MimeBundleOrTuple can be used as a type annotation+ def accepts_mime_bundle_or_tuple(+ bundle_or_tuple: MimeBundleOrTuple,+ ) -> MimeBundleOrTuple:+ return bundle_or_tuple++ # Test with a bundle+ bundle: MimeBundle = {"text/plain": "Hello, world!"}+ assert accepts_mime_bundle_or_tuple(bundle) == bundle++ # Test with a tuple+ metadata = {"key": "value"}+ bundle_tuple: tuple[MimeBundle, Any] = (bundle, metadata)+ assert accepts_mime_bundle_or_tuple(bundle_tuple) == bundle_tuplediff --git a/tests/_messaging/test_print_override.py b/tests/_messaging/test_print_override.pynew file mode 100644index 0000000000..66b0ffe9ee--- /dev/null+++ b/tests/_messaging/test_print_override.py@@ -0,0 +1,200 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import threading+from unittest.mock import MagicMock, patch++from marimo._messaging.print_override import print_override+from marimo._messaging.types import Stream+from marimo._runtime.context.types import (+ ContextNotInitializedError,+ ExecutionContext,+ RuntimeContext,+)+from marimo._runtime.threads import THREADS+++class MockStream(Stream):+ def __init__(self) -> None:+ self.messages: list[tuple[str, dict]] = []++ def write(self, op: str, data: dict) -> None:+ self.messages.append((op, data))+++class TestPrintOverride:+ def test_print_override_normal(self) -> None:+ # Test print_override when not in a marimo thread+ with patch(+ "marimo._messaging.print_override._original_print"+ ) as mock_print:+ print_override("Hello, world!")+ mock_print.assert_called_once_with("Hello, world!")++ def test_print_override_with_thread_no_context(self) -> None:+ # Test print_override when in a marimo thread but no context+ thread_id = threading.get_ident()+ THREADS.add(thread_id)++ try:+ with patch(+ "marimo._messaging.print_override._original_print"+ ) as mock_print:+ with patch(+ "marimo._messaging.print_override.get_context",+ side_effect=ContextNotInitializedError,+ ):+ print_override("Hello, world!")++ # Original print should be called as a fallback+ mock_print.assert_called_once_with("Hello, world!")+ finally:+ # Clean up+ if thread_id in THREADS:+ THREADS.remove(thread_id)++ def test_print_override_with_thread_and_context(self) -> None:+ # Test print_override when in a marimo thread with context+ thread_id = threading.get_ident()+ THREADS.add(thread_id)++ try:+ stream = MockStream()++ # Create a mock context+ context = MagicMock(spec=RuntimeContext)+ context.stream = stream+ context.execution_context = MagicMock(spec=ExecutionContext)+ context.execution_context.cell_id = "cell1"++ with patch(+ "marimo._messaging.print_override._original_print"+ ) as mock_print:+ with patch(+ "marimo._messaging.print_override.get_context",+ return_value=context,+ ):+ print_override("Hello, world!")++ # Original print should not be called+ mock_print.assert_not_called()++ # Message should be sent to the stream+ assert len(stream.messages) == 1+ assert stream.messages[0][0] == "cell-op" # op+ assert stream.messages[0][1]["cell_id"] == "cell1"+ assert (+ stream.messages[0][1]["console"]["channel"] == "stdout"+ )+ assert (+ stream.messages[0][1]["console"]["mimetype"]+ == "text/plain"+ )+ assert (+ stream.messages[0][1]["console"]["data"]+ == "Hello, world!\n"+ )+ finally:+ # Clean up+ if thread_id in THREADS:+ THREADS.remove(thread_id)++ def test_print_override_with_thread_no_execution_context(self) -> None:+ # Test print_override when in a marimo thread with context but no execution context+ thread_id = threading.get_ident()+ THREADS.add(thread_id)++ try:+ # Create a mock context with no execution context+ context = MagicMock(spec=RuntimeContext)+ context.execution_context = None++ with patch(+ "marimo._messaging.print_override._original_print"+ ) as mock_print:+ with patch(+ "marimo._messaging.print_override.get_context",+ return_value=context,+ ):+ print_override("Hello, world!")++ # Original print should be called+ mock_print.assert_called_once_with("Hello, world!")+ finally:+ # Clean up+ if thread_id in THREADS:+ THREADS.remove(thread_id)++ def test_print_override_with_custom_sep_and_end(self) -> None:+ # Test print_override with custom separator and end+ thread_id = threading.get_ident()+ THREADS.add(thread_id)++ try:+ stream = MockStream()++ # Create a mock context+ context = MagicMock(spec=RuntimeContext)+ context.stream = stream+ context.execution_context = MagicMock(spec=ExecutionContext)+ context.execution_context.cell_id = "cell1"++ with patch(+ "marimo._messaging.print_override._original_print"+ ) as mock_print:+ with patch(+ "marimo._messaging.print_override.get_context",+ return_value=context,+ ):+ print_override("Hello", "world", sep="-", end="!")++ # Original print should not be called+ mock_print.assert_not_called()++ # Message should be sent to the stream with custom sep and end+ assert len(stream.messages) == 1+ assert (+ stream.messages[0][1]["console"]["data"]+ == "Hello-world!"+ )+ finally:+ # Clean up+ if thread_id in THREADS:+ THREADS.remove(thread_id)++ def test_print_override_with_multiple_args(self) -> None:+ # Test print_override with multiple arguments+ thread_id = threading.get_ident()+ THREADS.add(thread_id)++ try:+ stream = MockStream()++ # Create a mock context+ context = MagicMock(spec=RuntimeContext)+ context.stream = stream+ context.execution_context = MagicMock(spec=ExecutionContext)+ context.execution_context.cell_id = "cell1"++ with patch(+ "marimo._messaging.print_override._original_print"+ ) as mock_print:+ with patch(+ "marimo._messaging.print_override.get_context",+ return_value=context,+ ):+ print_override("Hello", 123, True, None)++ # Original print should not be called+ mock_print.assert_not_called()++ # Message should be sent to the stream with all args converted to strings+ assert len(stream.messages) == 1+ assert (+ stream.messages[0][1]["console"]["data"]+ == "Hello 123 True None\n"+ )+ finally:+ # Clean up+ if thread_id in THREADS:+ THREADS.remove(thread_id)diff --git a/tests/_messaging/test_tracebacks.py b/tests/_messaging/test_tracebacks.pynew file mode 100644index 0000000000..7c887b9abd--- /dev/null+++ b/tests/_messaging/test_tracebacks.py@@ -0,0 +1,81 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from unittest.mock import MagicMock, patch++from marimo._messaging.tracebacks import (+ _highlight_traceback,+ is_code_highlighting,+ write_traceback,+)+from marimo._messaging.types import Stderr+++class TestTracebacks:+ def test_highlight_traceback(self) -> None:+ # Test that _highlight_traceback adds HTML formatting+ traceback = 'Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\nValueError: invalid value'++ highlighted = _highlight_traceback(traceback)++ # Should contain HTML formatting+ assert '<span class="codehilite">' in highlighted+ assert "</span>" in highlighted++ # Should contain the original traceback text+ assert "Traceback" in highlighted+ # The ValueError text is present but with HTML tags around it+ assert "ValueError" in highlighted+ assert "invalid value" in highlighted++ def test_write_traceback_to_stderr(self) -> None:+ # Test writing traceback to Stderr+ mock_stderr = MagicMock(spec=Stderr)++ with patch("sys.stderr", mock_stderr):+ traceback = 'Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\nValueError: invalid value'+ write_traceback(traceback)++ # Should call _write_with_mimetype with highlighted traceback+ mock_stderr._write_with_mimetype.assert_called_once()++ # First argument should be the highlighted traceback+ args, _ = mock_stderr._write_with_mimetype.call_args+ assert '<span class="codehilite">' in args[0]+ assert "Traceback" in args[0]++ # Second argument should be the mimetype+ _, kwargs = mock_stderr._write_with_mimetype.call_args+ assert kwargs["mimetype"] == "application/vnd.marimo+traceback"++ def test_write_traceback_to_regular_stderr(self) -> None:+ # Test writing traceback to regular stderr (not Stderr)+ mock_stderr = MagicMock()+ mock_stderr.write = MagicMock()++ with patch("sys.stderr", mock_stderr):+ traceback = 'Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\nValueError: invalid value'+ write_traceback(traceback)++ # Should call write with the original traceback+ mock_stderr.write.assert_called_once_with(traceback)++ def test_is_code_highlighting(self) -> None:+ # Test is_code_highlighting function++ # Should return True for strings containing the codehilite class+ assert (+ is_code_highlighting('<span class="codehilite">code</span>')+ is True+ )+ assert (+ is_code_highlighting(+ 'before <span class="codehilite">code</span> after'+ )+ is True+ )++ # Should return False for strings not containing the codehilite class+ assert is_code_highlighting("<span>code</span>") is False+ assert is_code_highlighting("") is False+ assert is_code_highlighting('class="not-codehilite"') is Falsediff --git a/tests/_messaging/test_types.py b/tests/_messaging/test_types.pynew file mode 100644index 0000000000..16dcf353a0--- /dev/null+++ b/tests/_messaging/test_types.py@@ -0,0 +1,107 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.types import (+ KernelMessage,+ NoopStream,+ Stderr,+ Stdin,+ Stdout,+)+++class TestStream:+ def test_noop_stream(self) -> None:+ # Test that NoopStream implements Stream+ stream = NoopStream()++ # Should not raise any exceptions+ stream.write("test_op", {"key": "value"})+ stream.stop()++ # cell_id should be None by default+ assert stream.cell_id is None++ # Set cell_id+ stream.cell_id = "test_cell"+ assert stream.cell_id == "test_cell"+++class TestStdoutStderr:+ class MockStdout(Stdout):+ def __init__(self) -> None:+ self.written_data: list[tuple[str, KnownMimeType]] = []++ def _write_with_mimetype(+ self, data: str, mimetype: KnownMimeType+ ) -> int:+ self.written_data.append((data, mimetype))+ return len(data)++ class MockStderr(Stderr):+ def __init__(self) -> None:+ self.written_data: list[tuple[str, KnownMimeType]] = []++ def _write_with_mimetype(+ self, data: str, mimetype: KnownMimeType+ ) -> int:+ self.written_data.append((data, mimetype))+ return len(data)++ def test_stdout_write(self) -> None:+ stdout = self.MockStdout()++ # Test write method+ result = stdout.write("Hello, world!")++ # Should return the length of the string+ assert result == 13++ # Should call _write_with_mimetype with text/plain mimetype+ assert len(stdout.written_data) == 1+ assert stdout.written_data[0] == ("Hello, world!", "text/plain")++ def test_stderr_write(self) -> None:+ stderr = self.MockStderr()++ # Test write method+ result = stderr.write("Error message")++ # Should return the length of the string+ assert result == 13++ # Should call _write_with_mimetype with text/plain mimetype+ assert len(stderr.written_data) == 1+ assert stderr.written_data[0] == ("Error message", "text/plain")++ def test_stdout_name(self) -> None:+ stdout = self.MockStdout()+ assert stdout.name == "stdout"++ def test_stderr_name(self) -> None:+ stderr = self.MockStderr()+ assert stderr.name == "stderr"+++class TestStdin:+ def test_stdin_name(self) -> None:+ stdin = Stdin()+ assert stdin.name == "stdin"++ def test_stdin_stop(self) -> None:+ stdin = Stdin()+ # Should not raise any exceptions+ stdin.stop()+++class TestKernelMessage:+ def test_kernel_message_type(self) -> None:+ # Test that KernelMessage can be used as a type annotation+ def accepts_kernel_message(message: KernelMessage) -> KernelMessage:+ return message++ # Create a valid kernel message+ message: KernelMessage = ("test_op", {"key": "value"})++ assert accepts_kernel_message(message) == message