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
tests: add some more validation tests for msgspec serialization (#6514)
Myles Scolnick4c77d6bc5242
diff --git a/tests/_data/test_models.py b/tests/_data/test_models.pyindex 427a7c13ba..858993062e 100644--- a/tests/_data/test_models.py+++ b/tests/_data/test_models.py@@ -1,4 +1,5 @@from marimo._data.models import DataTableColumn+from tests.utils import assert_serialize_roundtripdef test_data_table_column_post_init() -> None:@@ -9,3 +10,5 @@ def test_data_table_column_post_init() -> None:sample_values=[],)assert column.name == "123"++ assert_serialize_roundtrip(column)diff --git a/tests/_data/test_preview_column.py b/tests/_data/test_preview_column.pyindex 5c8ae7a765..1738e4b891 100644--- a/tests/_data/test_preview_column.py+++ b/tests/_data/test_preview_column.py@@ -20,6 +20,7 @@ from marimo._plugins.ui._impl.charts.altair_transformer import (from marimo._runtime.requests import PreviewDatasetColumnRequestfrom marimo._utils.platform import is_windowsfrom tests.mocks import snapshotter+from tests.utils import assert_serialize_roundtripif TYPE_CHECKING:from collections.abc import Generator@@ -84,6 +85,7 @@ def test_get_column_preview_for_dataframe() -> None:assert result.chart_spec is not Noneassert result.stats is not Noneassert result.error is None+ assert_serialize_roundtrip(result)@pytest.mark.skipif(@@ -148,6 +150,8 @@ def test_get_column_preview(column_name: str, snapshot_prefix: str) -> None:# Verify vegafusion was checkedmock_dm.vegafusion.has.assert_called_once()+ assert_serialize_roundtrip(result)+result_with_vegafusion = get_column_preview_dataset(table=get_table_manager(df),table_name="table",@@ -168,6 +172,7 @@ def test_get_column_preview(column_name: str, snapshot_prefix: str) -> None:)assert result_with_vegafusion.chart_code == result.chart_codeassert result_with_vegafusion.chart_spec != result.chart_spec+ assert_serialize_roundtrip(result_with_vegafusion)@pytest.mark.skipif(@@ -194,6 +199,7 @@ def test_get_column_preview_for_duckdb() -> None:assert result is not Noneassert result.stats is not Noneassert result.error is None+ assert_serialize_roundtrip(result)# Check if summary contains expected statistics for the alternating patternassert result.stats.total == 100@@ -211,6 +217,8 @@ def test_get_column_preview_for_duckdb() -> None:assert result_id.error is Noneassert result_id.chart_spec is not None+ assert_serialize_roundtrip(result_id)+# Not implemented yetassert result.chart_code is None@@ -243,6 +251,7 @@ def test_get_column_preview_for_duckdb_categorical() -> None:assert result_categorical is not Noneassert result_categorical.stats is not Noneassert result_categorical.error is None+ assert_serialize_roundtrip(result_categorical)# Check if summary contains expected statistics for the categorical patternassert result_categorical.stats.total == 100@@ -292,6 +301,7 @@ def test_get_column_preview_for_duckdb_date() -> None:assert result_date is not Noneassert result_date.stats is not Noneassert result_date.error is None+ assert_serialize_roundtrip(result_date)# Check if summary contains expected statistics for the date patternassert result_date.stats.total == 100@@ -343,6 +353,7 @@ def test_get_column_preview_for_duckdb_datetime() -> None:assert result_datetime is not Noneassert result_datetime.stats is not Noneassert result_datetime.error is None+ assert_serialize_roundtrip(result_datetime)# Check if summary contains expected statistics for the datetime patternassert result_datetime.stats.total == 100@@ -393,6 +404,7 @@ def test_get_column_preview_for_duckdb_time() -> None:assert result_time is not Noneassert result_time.stats is not Noneassert result_time.error is None+ assert_serialize_roundtrip(result_time)# Check if summary contains expected statistics for the time patternassert result_time.stats.total == 100@@ -429,6 +441,7 @@ def test_get_column_preview_for_duckdb_bool() -> None:assert result_bool is not Noneassert result_bool.stats is not Noneassert result_bool.error is None+ assert_serialize_roundtrip(result_bool)# Check if summary contains expected statistics for the boolean patternassert result_bool.stats.total == 100@@ -477,6 +490,7 @@ def test_get_column_preview_for_duckdb_over_limit() -> None:)assert result.missing_packages == ["vegafusion", "vl_convert_python"]assert result.chart_spec is None+ assert_serialize_roundtrip(result)# Not implemented yetassert result.chart_code is None@@ -499,7 +513,6 @@ def test_sanitize_dtypes() -> None:# Sanitize the dtypesresult = _sanitize_data(nw_df, "cat_col")assert result.collect_schema()["cat_col"] == nw.String-result = _sanitize_data(nw_df, "int128_col")assert result.collect_schema()["int128_col"] == nw.Int64@@ -555,6 +568,9 @@ def test_preview_column_duration_dtype() -> None:table_name="table",column_name=column_name,)- assert result is not None- assert result.chart_code is not None- assert result.chart_spec is not None++ assert result is not None+ assert result.chart_code is not None+ assert result.chart_spec is not None++ assert_serialize_roundtrip(result)diff --git a/tests/_messaging/mocks.py b/tests/_messaging/mocks.pyindex 2eb34aaf7b..1a76784f98 100644--- a/tests/_messaging/mocks.py+++ b/tests/_messaging/mocks.py@@ -3,9 +3,12 @@ from __future__ import annotationsfrom typing import Any, Optionalfrom marimo._messaging.mimetypes import ConsoleMimeType-from marimo._messaging.ops import CellOp, MessageOperation+from marimo._messaging.ops import (+ CellOp,+ MessageOperation,+ deserialize_kernel_message,+)from marimo._messaging.types import KernelMessage, Stderr, Stream-from marimo._utils.parse_dataclass import parse_rawclass MockStream(Stream):@@ -17,6 +20,8 @@ class MockStream(Stream):def write(self, data: KernelMessage) -> None:self.messages.append(data)+ # Attempt to deserialize the message to ensure it is valid+ deserialize_kernel_message(data)@propertydef operations(self) -> list[dict[str, Any]]:@@ -27,7 +32,7 @@ class MockStream(Stream):@propertydef parsed_operations(self) -> list[MessageOperation]:return [- parse_raw(op_data, MessageOperation) for op_data in self.messages+ deserialize_kernel_message(op_data) for op_data in self.messages]@propertydiff --git a/tests/_runtime/test_complete.py b/tests/_runtime/test_complete.pyindex 30a69a7682..6953f6da75 100644--- a/tests/_runtime/test_complete.py+++ b/tests/_runtime/test_complete.py@@ -13,7 +13,7 @@ import pytestimport marimofrom marimo._dependencies.dependencies import DependencyManager-from marimo._messaging.ops import CompletionResult+from marimo._messaging.ops import CompletionResult, deserialize_kernel_messagefrom marimo._messaging.types import KernelMessage, Streamfrom marimo._runtime.complete import (_build_docstring_cached,@@ -367,6 +367,8 @@ class CaptureStream(Stream):def write(self, data: KernelMessage) -> None:self.messages.append(data)+ # Attempt to deserialize the message to ensure it is valid+ deserialize_kernel_message(data)@propertydef operations(self) -> list[dict[str, Any]]:diff --git a/tests/_server/conftest.py b/tests/_server/conftest.pyindex a8dd108b0f..f554709a64 100644--- a/tests/_server/conftest.py+++ b/tests/_server/conftest.py@@ -1,8 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import osimport sys+from pathlib import Pathfrom tempfile import TemporaryDirectoryfrom typing import TYPE_CHECKING@@ -14,9 +14,11 @@ from marimo._config.manager import MarimoConfigManager, UserConfigManagerfrom marimo._config.utils import CONFIG_FILENAMEfrom marimo._server.api.deps import AppStatefrom marimo._server.main import create_starlette_app+from marimo._server.session.session_view import SessionViewfrom marimo._server.sessions import SessionManagerfrom marimo._server.utils import initialize_asynciofrom tests._server.mocks import get_mock_session_manager+from tests.utils import assert_serialize_roundtripif TYPE_CHECKING:from collections.abc import Generator, Iterator@@ -39,16 +41,15 @@ def client_with_lifespans() -> Generator[TestClient, None, None]:@pytest.fixturedef user_config_manager() -> Iterator[UserConfigManager]:tmp = TemporaryDirectory()- config_path = os.path.join(tmp.name, CONFIG_FILENAME)- with open(config_path, "w") as f:- f.write("")+ config_path = Path(tmp.name) / CONFIG_FILENAME+ config_path.write_text("")class TestUserConfigManager(UserConfigManager):def __init__(self) -> None:super().__init__()def get_config_path(self) -> str:- return config_path+ return str(config_path)yield TestUserConfigManager()@@ -89,3 +90,14 @@ def get_session_config_manager(client: TestClient) -> UserConfigManager:def get_user_config_manager(client: TestClient) -> UserConfigManager:return client.app.state.config_manager # type: ignore+++def session_view() -> Generator[SessionView, None, None]:+ sv = SessionView()++ yield sv++ # Test all operations can be serialized/deserialized+ for operation in sv.operations:+ assert_serialize_roundtrip(operation)diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.pyindex 8683842c58..6150f84dbc 100644--- a/tests/_server/export/test_exporter.py+++ b/tests/_server/export/test_exporter.py@@ -495,7 +495,7 @@ async def test_run_until_completion_with_console_output(mock_echo: MagicMock):)-def test_export_as_html_with_serialization():+def test_export_as_html_with_serialization(session_view: SessionView):"""Test HTML export uses new serialization approach correctly."""app = App()@@ -512,7 +512,6 @@ def test_export_as_html_with_serialization():return (mo,)file_manager = AppFileManager.from_app(InternalApp(app))- session_view = SessionView()# Add some test data to session viewcell_ids = list(file_manager.app.cell_manager.cell_ids())@@ -574,7 +573,7 @@ def test_export_as_html_with_serialization():assert 'data-marimo="true"' in html-def test_export_as_html_without_code():+def test_export_as_html_without_code(session_view: SessionView):"""Test HTML export clears code when include_code=False."""app = App()@@ -585,7 +584,6 @@ def test_export_as_html_without_code():return secret_valuefile_manager = AppFileManager.from_app(InternalApp(app))- session_view = SessionView()cell_ids = list(file_manager.app.cell_manager.cell_ids())session_view.cell_operations[cell_ids[0]] = CellOp(@@ -636,7 +634,7 @@ def test_export_as_html_without_code():# The exact format depends on template implementation-def test_export_as_html_with_files():+def test_export_as_html_with_files(session_view: SessionView):"""Test HTML export includes virtual files."""app = App()@@ -645,7 +643,6 @@ def test_export_as_html_with_files():return "test"file_manager = AppFileManager.from_app(InternalApp(app))- session_view = SessionView()cell_ids = list(file_manager.app.cell_manager.cell_ids())session_view.cell_operations[cell_ids[0]] = CellOp(@@ -684,7 +681,7 @@ def test_export_as_html_with_files():assert "data:" in html-def test_export_as_html_with_cell_configs():+def test_export_as_html_with_cell_configs(session_view: SessionView):"""Test HTML export preserves cell configurations through serialization."""app = App()@@ -693,7 +690,6 @@ def test_export_as_html_with_cell_configs():return "configured"file_manager = AppFileManager.from_app(InternalApp(app))- session_view = SessionView()cell_ids = list(file_manager.app.cell_manager.cell_ids())session_view.cell_operations[cell_ids[0]] = CellOp(@@ -733,7 +729,7 @@ def test_export_as_html_with_cell_configs():assert "configured" in html-def test_export_as_html_preserves_output_order():+def test_export_as_html_preserves_output_order(session_view: SessionView):"""Test HTML export preserves cell execution order in session snapshot."""app = App()@@ -750,7 +746,6 @@ def test_export_as_html_preserves_output_order():return "third"file_manager = AppFileManager.from_app(InternalApp(app))- session_view = SessionView()cell_ids = list(file_manager.app.cell_manager.cell_ids())@@ -792,7 +787,7 @@ def test_export_as_html_preserves_output_order():assert "output_2" in html-def test_export_as_html_with_error_outputs():+def test_export_as_html_with_error_outputs(session_view: SessionView):"""Test HTML export handles error outputs correctly."""app = App()@@ -801,7 +796,6 @@ def test_export_as_html_with_error_outputs():raise ValueError("Test error")file_manager = AppFileManager.from_app(InternalApp(app))- session_view = SessionView()cell_ids = list(file_manager.app.cell_manager.cell_ids())@@ -846,7 +840,7 @@ def test_export_as_html_with_error_outputs():assert "Test error" in html or "ValueError" in html-def test_export_as_html_code_hash_consistency():+def test_export_as_html_code_hash_consistency(session_view: SessionView):"""Test HTML export includes correct code hash regardless of include_code setting."""app = App()@@ -855,7 +849,6 @@ def test_export_as_html_code_hash_consistency():return "test"file_manager = AppFileManager.from_app(InternalApp(app))- session_view = SessionView()cell_ids = list(file_manager.app.cell_manager.cell_ids())session_view.cell_operations[cell_ids[0]] = CellOp(diff --git a/tests/_server/session/snapshots/mixed_error_session.json b/tests/_server/session/snapshots/mixed_error_session.jsonindex 29ab6b621e..500eae5ad5 100644--- a/tests/_server/session/snapshots/mixed_error_session.json+++ b/tests/_server/session/snapshots/mixed_error_session.json@@ -10,24 +10,18 @@"outputs": [{"type": "error",- "ename": "ValueError",+ "ename": "exception","evalue": "Invalid value",- "traceback": ["line 1", "line 2"]+ "traceback": []},{"type": "error","ename": "RuntimeError","evalue": "Runtime error occurred","traceback": []- },- {- "type": "error",- "ename": "TypeError",- "evalue": "Type mismatch",- "traceback": []}],"console": []}]-}+}\ No newline at end of filediff --git a/tests/_server/session/test_serialize_session.py b/tests/_server/session/test_serialize_session.pyindex ce1afdd8c1..dbf184e2d9 100644--- a/tests/_server/session/test_serialize_session.py+++ b/tests/_server/session/test_serialize_session.py@@ -33,9 +33,9 @@ from tests.mocks import snapshottersnapshot = snapshotter(__file__)-def test_serialize_basic_session():+def test_serialize_basic_session(session_view: SessionView):"""Test serialization of a basic session with a single cell with data output"""- view = SessionView()+ view = session_viewview.cell_operations[CellId_t("cell1")] = CellOp(cell_id=CellId_t("cell1"),status="idle",@@ -53,9 +53,9 @@ def test_serialize_basic_session():snapshot("basic_session.json", json.dumps(result, indent=2))-def test_serialize_session_with_error():+def test_serialize_session_with_error(session_view: SessionView):"""Test serialization of a session with an error output"""- view = SessionView()+ view = session_viewview.cell_operations[CellId_t("cell1")] = CellOp(cell_id=CellId_t("cell1"),status="idle",@@ -75,9 +75,9 @@ def test_serialize_session_with_error():snapshot("error_session.json", json.dumps(result, indent=2))-def test_serialize_session_with_console():+def test_serialize_session_with_console(session_view: SessionView):"""Test serialization of a session with console output"""- view = SessionView()+ view = session_viewview.cell_operations["cell1"] = CellOp(cell_id="cell1",status="idle",@@ -102,9 +102,9 @@ def test_serialize_session_with_console():snapshot("console_session.json", json.dumps(result, indent=2))-def test_serialize_session_with_mime_bundle():+def test_serialize_session_with_mime_bundle(session_view: SessionView):"""Test serialization of a session with a mime bundle output"""- view = SessionView()+ view = session_viewview.cell_operations["cell1"] = CellOp(cell_id="cell1",status="idle",@@ -125,9 +125,9 @@ def test_serialize_session_with_mime_bundle():snapshot("mime_bundle_session.json", json.dumps(result, indent=2))-def test_serialize_notebook_basic():+def test_serialize_notebook_basic(session_view: SessionView):"""Test serialization of a SessionView to a Notebook with basic cell"""- view = SessionView()+ view = session_viewcell_manager = CellManager()# Register cell with cell manager@@ -168,9 +168,9 @@ def test_serialize_notebook_basic():assert cell["config"]["hide_code"] is True-def test_serialize_notebook_multiple_cells():+def test_serialize_notebook_multiple_cells(session_view: SessionView):"""Test serialization of a SessionView to a Notebook with multiple cells"""- view = SessionView()+ view = session_viewcell_manager = CellManager()# Register first cell@@ -234,7 +234,9 @@ def test_serialize_notebook_multiple_cells():assert cell2["config"]["hide_code"] is True-def test_serialize_notebook_multiple_cells_not_top_down():+def test_serialize_notebook_multiple_cells_not_top_down(+ session_view: SessionView,+):"""Test serializing an "out-of-order" notebook.Serialize a notebook in which the topological sort@@ -242,7 +244,7 @@ def test_serialize_notebook_multiple_cells_not_top_down():the serialized notebook is in notebook order."""- view = SessionView()+ view = session_viewcell_manager = CellManager()cell_id1 = CellId_t("cell1")@@ -303,9 +305,9 @@ def test_serialize_notebook_multiple_cells_not_top_down():assert cell2["config"]["disabled"] is False-def test_serialize_notebook_empty_code():+def test_serialize_notebook_empty_code(session_view: SessionView):"""Test serialization when cells have no executed code"""- view = SessionView()+ view = session_viewcell_manager = CellManager()# Register cell with cell manager but with different code@@ -341,9 +343,9 @@ def test_serialize_notebook_empty_code():assert cell["config"]["hide_code"] is False # Default value-def test_serialize_notebook_no_cells():+def test_serialize_notebook_no_cells(session_view: SessionView):"""Test serialization of an empty SessionView"""- view = SessionView()+ view = session_viewcell_manager = CellManager()result = serialize_notebook(view, cell_manager)@@ -362,9 +364,9 @@ def test_serialize_notebook_no_cells():"the cell manager's view of cells differs from the session view. ""The session view doesn't know the order of cells in the notebook.")-def test_serialize_notebook_missing_cell_data():+def test_serialize_notebook_missing_cell_data(session_view: SessionView):"""Test serialization when cell exists in SessionView but not in CellManager"""- view = SessionView()+ view = session_viewcell_manager = CellManager()# Add cell to session view but don't register it with cell manager@@ -497,9 +499,9 @@ def test_deserialize_session_with_console():assert console_outputs[1].mimetype == "text/plain"-async def test_session_cache_writer():+async def test_session_cache_writer(session_view: SessionView):"""Test AsyncWriter writes session data periodically"""- view = SessionView()+ view = session_viewview.cell_operations["cell1"] = CellOp(cell_id="cell1",status="idle",@@ -530,9 +532,9 @@ async def test_session_cache_writer():await writer.stop()-async def test_session_cache_writer_no_writes():+async def test_session_cache_writer_no_writes(session_view: SessionView):"""Test AsyncWriter does not write when no changes"""- view = SessionView()+ view = session_viewview.mark_auto_export_session()with tempfile.TemporaryDirectory() as tmpdir:path = Path(tmpdir) / "session.json"@@ -719,22 +721,21 @@ def test_serialize_session_with_dict_error():assert result["cells"][0]["outputs"][0]["evalue"] == "Something went wrong"-def test_serialize_session_with_mixed_error_formats():+def test_serialize_session_with_mixed_error_formats(session_view: SessionView):"""Test serialization of a session with mixed error formats (dict and object)"""- view = SessionView()+ view = session_view# Test with both dictionary and object error formatsmixed_errors = [# Dictionary format error{- "type": "ValueError",+ "type": "exception",+ "exception_type": "ValueError","msg": "Invalid value",- "traceback": ["line 1", "line 2"],+ "raising_cell": "cell1",},# Object format errorUnknownError(msg="Runtime error occurred", error_type="RuntimeError"),- # Dictionary without traceback- {"type": "TypeError", "msg": "Type mismatch"},]view.cell_operations[CellId_t("cell1")] = CellOp(@@ -757,14 +758,14 @@ def test_serialize_session_with_mixed_error_formats():# Verify the error normalization worked correctlyassert len(result["cells"]) == 1cell = result["cells"][0]- assert len(cell["outputs"]) == 3+ assert len(cell["outputs"]) == 2# Check first error (dictionary with traceback)error1 = cell["outputs"][0]assert error1["type"] == "error"- assert error1["ename"] == "ValueError"+ assert error1["ename"] == "exception"assert error1["evalue"] == "Invalid value"- assert error1["traceback"] == ["line 1", "line 2"]+ assert error1["traceback"] == []# Check second error (object format)error2 = cell["outputs"][1]@@ -775,29 +776,22 @@ def test_serialize_session_with_mixed_error_formats():error2["traceback"] == []) # UnknownError doesn't have traceback by default- # Check third error (dictionary without traceback)- error3 = cell["outputs"][2]- assert error3["type"] == "error"- assert error3["ename"] == "TypeError"- assert error3["evalue"] == "Type mismatch"- assert error3["traceback"] == []-snapshot("mixed_error_session.json", json.dumps(result, indent=2))class TestSessionCacheManager:"""Test SessionCacheManager functionality"""- def test_init_without_path(self):+ def test_init_without_path(self, session_view: SessionView):"""Test initialization without path"""- view = SessionView()+ view = session_viewmanager = SessionCacheManager(view, None, 0.1)manager.start()assert manager.session_cache_writer is None- async def test_rename_path(self):+ async def test_rename_path(self, session_view: SessionView):"""Test renaming path updates writer"""- view = SessionView()+ view = session_viewwith tempfile.TemporaryDirectory() as tmpdir:old_path = Path(tmpdir) / "old.py"new_path = Path(tmpdir) / "new.py"@@ -812,9 +806,9 @@ class TestSessionCacheManager:assert manager.session_cache_writer != old_writerassert manager.path == new_path- def test_read_session_view_no_path(self):+ def test_read_session_view_no_path(self, session_view: SessionView):"""Test reading session view without path"""- view = SessionView()+ view = session_viewmanager = SessionCacheManager(view, None, 0.1)assert (manager.read_session_view(@@ -823,9 +817,9 @@ class TestSessionCacheManager:== view)- def test_read_session_view_no_cache(self):+ def test_read_session_view_no_cache(self, session_view: SessionView):"""Test reading session view with no cache file"""- view = SessionView()+ view = session_viewwith tempfile.TemporaryDirectory() as tmpdir:path = Path(tmpdir) / "notebook.py"manager = SessionCacheManager(view, path, 0.1)@@ -836,9 +830,11 @@ class TestSessionCacheManager:== view)- async def test_read_session_view_with_cache(self):+ async def test_read_session_view_with_cache(+ self, session_view: SessionView+ ):"""Test reading session view from cache file"""- view = SessionView()+ view = session_viewview.cell_operations["cell1"] = CellOp(cell_id="cell1",status="idle",@@ -870,9 +866,11 @@ class TestSessionCacheManager:assert cell.output is not Noneassert cell.output.data == "test data"- async def test_read_session_view_cache_miss_code(self):+ async def test_read_session_view_cache_miss_code(+ self, session_view: SessionView+ ):"""Test reading session view from cache file"""- view = SessionView()+ view = session_viewview.cell_operations["cell1"] = CellOp(cell_id="cell1",status="idle",@@ -905,9 +903,11 @@ class TestSessionCacheManager:)assert not loaded_view.cell_operations- async def test_read_session_view_cache_miss_version(self):+ async def test_read_session_view_cache_miss_version(+ self, session_view: SessionView+ ):"""Test reading session view from cache file"""- view = SessionView()+ view = session_viewview.add_control_request(ExecuteMultipleRequest(cell_ids=["1", "2"], codes=["a", "b"]))@@ -934,9 +934,11 @@ class TestSessionCacheManager:)assert not loaded_view.cell_operations- async def test_read_session_view_cache_hit(self):+ async def test_read_session_view_cache_hit(+ self, session_view: SessionView+ ):"""Test reading session view from cache file"""- view = SessionView()+ view = session_viewview.cell_operations["cell1"] = CellOp(cell_id="cell1",status="idle",diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.pyindex d482462436..82b129df5f 100644--- a/tests/_server/session/test_session_view.py+++ b/tests/_server/session/test_session_view.py@@ -52,8 +52,7 @@ initial_status: RuntimeStateType = "running"updated_status: RuntimeStateType = "running"-def test_cell_ids() -> None:- session_view = SessionView()+def test_cell_ids(session_view: SessionView) -> None:assert session_view.cell_ids is Nonesession_view.add_operation(@@ -66,9 +65,7 @@ def test_cell_ids() -> None:assert operation.cell_ids == [cell_id]-def test_session_view_cell_op() -> None:- session_view = SessionView()-+def test_session_view_cell_op(session_view: SessionView) -> None:# Create initial CellOpinitial_cell_op = CellOp(cell_id=cell_id, output=initial_output, status=initial_status@@ -86,9 +83,7 @@ def test_session_view_cell_op() -> None:# Test adding Variables to SessionView-def test_session_view_variables() -> None:- session_view = SessionView()-+def test_session_view_variables(session_view: SessionView) -> None:# Create Variables operationvariables_op = Variables(variables=[@@ -102,8 +97,7 @@ def test_session_view_variables() -> None:# Test adding VariableValues to SessionView-def test_session_view_variable_values() -> None:- session_view = SessionView()+def test_session_view_variable_values(session_view: SessionView) -> None:# Create Variables operationvariables_op = Variables(variables=[@@ -147,8 +141,7 @@ def test_session_view_variable_values() -> None:assert list(variables_names) == ["var2"]-def test_ui_values() -> None:- session_view = SessionView()+def test_ui_values(session_view: SessionView) -> None:session_view.add_control_request(SetUIElementValueRequest.from_ids_and_values([("test_ui", 123)]))@@ -180,8 +173,7 @@ def test_ui_values() -> None:assert "test_ui3" in session_view.ui_values-def test_model_message_values() -> None:- session_view = SessionView()+def test_model_message_values(session_view: SessionView) -> None:model_id = WidgetModelId("test_model")model_id2 = WidgetModelId("test_model2")@@ -222,8 +214,7 @@ def test_model_message_values() -> None:}-def test_last_run_code() -> None:- session_view = SessionView()+def test_last_run_code(session_view: SessionView) -> None:session_view.add_control_request(ExecuteMultipleRequest(cell_ids=[cell_id],@@ -265,9 +256,7 @@ def test_serialize_parse_variable_value() -> None:assert parsed == original-def test_add_variables() -> None:- session_view = SessionView()-+def test_add_variables(session_view: SessionView) -> None:session_view.add_raw_operation(serialize_kernel_message(Variables(@@ -301,9 +290,7 @@ def test_add_variables() -> None:assert session_view.variable_values["var2"].datatype == "str"-def test_add_datasets() -> None:- session_view = SessionView()-+def test_add_datasets(session_view: SessionView) -> None:session_view.add_raw_operation(serialize_kernel_message(Datasets(@@ -412,8 +399,7 @@ def test_add_datasets() -> None:assert session_view.datasets.tables[0].name == "table2"-def test_add_datasets_clear_channel() -> None:- session_view = SessionView()+def test_add_datasets_clear_channel(session_view: SessionView) -> None:session_view.add_raw_operation(serialize_kernel_message(Datasets(@@ -473,9 +459,7 @@ def test_add_datasets_clear_channel() -> None:assert "db.table2" in names-def test_add_data_source_connections() -> None:- session_view = SessionView()-+def test_add_data_source_connections(session_view: SessionView) -> None:# Add initial connectionssession_view.add_raw_operation(serialize_kernel_message(@@ -574,8 +558,7 @@ def test_add_data_source_connections() -> None:assert INTERNAL_DUCKDB_ENGINE in session_view_names-def test_add_cell_op() -> None:- session_view = SessionView()+def test_add_cell_op(session_view: SessionView) -> None:session_view.add_raw_operation(serialize_kernel_message(CellOp(@@ -590,9 +573,10 @@ def test_add_cell_op() -> None:# patch time@patch("time.time", return_value=123)-def test_combine_console_outputs(time_mock: Any) -> None:+def test_combine_console_outputs(+ time_mock: Any, session_view: SessionView+) -> None:del time_mock- session_view = SessionView()session_view.add_operation(CellOp(cell_id=cell_id,@@ -651,9 +635,8 @@ def test_combine_console_outputs(time_mock: Any) -> None:@patch("time.time", return_value=123)-def test_stdin(time_mock: Any) -> None:+def test_stdin(time_mock: Any, session_view: SessionView) -> None:del time_mock- session_view = SessionView()session_view.add_operation(CellOp(cell_id=cell_id,@@ -683,10 +666,9 @@ def test_stdin(time_mock: Any) -> None:@patch("time.time", return_value=123)-def test_get_cell_outputs(time_mock: Any) -> None:+def test_get_cell_outputs(time_mock: Any, session_view: SessionView) -> None:del time_mockcell_2_id = "cell_2"- session_view = SessionView()session_view.add_operation(CellOp(cell_id=cell_id,@@ -731,10 +713,11 @@ def test_get_cell_outputs(time_mock: Any) -> None:@patch("time.time", return_value=123)-def test_get_cell_console_outputs(time_mock: Any) -> None:+def test_get_cell_console_outputs(+ time_mock: Any, session_view: SessionView+) -> None:del time_mockcell_2_id = "cell_2"- session_view = SessionView()session_view.add_operation(CellOp(cell_id=cell_id,@@ -778,8 +761,7 @@ def test_get_cell_console_outputs(time_mock: Any) -> None:}-def test_mark_auto_export():- session_view = SessionView()+def test_mark_auto_export(session_view: SessionView):assert session_view.needs_export("html")assert session_view.needs_export("md")@@ -812,9 +794,8 @@ def test_mark_auto_export():assert session_view.needs_export("session")-def test_stale_code() -> None:+def test_stale_code(session_view: SessionView) -> None:"""Test that stale code is properly tracked and included in operations."""- session_view = SessionView()assert session_view.stale_code is None# Add stale code operation@@ -855,9 +836,9 @@ def test_stale_code() -> None:assert stale_code_op not in session_view.operations-def test_dataset_filter_by_engine_and_variable() -> None:- session_view = SessionView()-+def test_dataset_filter_by_engine_and_variable(+ session_view: SessionView,+) -> None:# Initially add three tables: one with an engine, one with a variable name, and one with neithersession_view.add_raw_operation(serialize_kernel_message(@@ -936,9 +917,8 @@ def test_dataset_filter_by_engine_and_variable() -> None:assert table_names == ["table_none"]-def test_is_empty() -> None:+def test_is_empty(session_view: SessionView) -> None:"""Test that SessionView.is_empty() correctly detects empty session views."""- session_view = SessionView()# Initially emptyassert session_view.is_empty()@@ -963,8 +943,8 @@ def test_is_empty() -> None:# No longer emptyassert not session_view.is_empty()- # Clear operations by creating a new session view- session_view = SessionView()++def test_is_empty_multiple_operations(session_view: SessionView) -> None:assert session_view.is_empty()# Add multiple operations - should still not be empty@@ -985,9 +965,7 @@ def test_is_empty() -> None:assert not session_view.is_empty()-def test_session_view_startup_logs() -> None:- session_view = SessionView()-+def test_session_view_startup_logs(session_view: SessionView) -> None:# Test adding a startup log with "start" statusstart_log = StartupLogs(content="Starting process...", status="start")session_view.add_operation(start_log)@@ -1018,9 +996,9 @@ def test_session_view_startup_logs() -> None:assert session_view.startup_logs.status == "done"-def test_session_view_startup_logs_operations_exclude_done() -> None:- session_view = SessionView()-+def test_session_view_startup_logs_operations_exclude_done(+ session_view: SessionView,+) -> None:# Add startup log in progressstart_log = StartupLogs(content="Starting...", status="start")session_view.add_operation(start_log)@@ -1041,9 +1019,9 @@ def test_session_view_startup_logs_operations_exclude_done() -> None:assert len(startup_ops) == 0-def test_session_view_startup_logs_standalone_done() -> None:- session_view = SessionView()-+def test_session_view_startup_logs_standalone_done(+ session_view: SessionView,+) -> None:# Add a standalone "done" log without prior start/appenddone_log = StartupLogs(content="Process complete", status="done")session_view.add_operation(done_log)@@ -1053,17 +1031,17 @@ def test_session_view_startup_logs_standalone_done() -> None:assert session_view.startup_logs.status == "done"-def test_session_view_package_logs_initialization() -> None:+def test_session_view_package_logs_initialization(+ session_view: SessionView,+) -> None:"""Test that SessionView initializes package_logs correctly."""- session_view = SessionView()assert hasattr(session_view, "package_logs")assert isinstance(session_view.package_logs, dict)assert len(session_view.package_logs) == 0-def test_session_view_package_logs_start() -> None:+def test_session_view_package_logs_start(session_view: SessionView) -> None:"""Test SessionView handles package logs start status."""- session_view = SessionView()alert = InstallingPackageAlert(packages={"numpy": "installing"},@@ -1077,9 +1055,8 @@ def test_session_view_package_logs_start() -> None:assert session_view.package_logs["numpy"] == "Installing numpy...\n"-def test_session_view_package_logs_append() -> None:+def test_session_view_package_logs_append(session_view: SessionView) -> None:"""Test SessionView handles package logs append status."""- session_view = SessionView()# Start with initial logstart_alert = InstallingPackageAlert(@@ -1103,9 +1080,8 @@ def test_session_view_package_logs_append() -> None:assert session_view.package_logs["pandas"] == expected_content-def test_session_view_package_logs_done() -> None:+def test_session_view_package_logs_done(session_view: SessionView) -> None:"""Test SessionView handles package logs done status."""- session_view = SessionView()# Start installationstart_alert = InstallingPackageAlert(@@ -1139,9 +1115,10 @@ def test_session_view_package_logs_done() -> None:assert session_view.package_logs["scipy"] == expected_content-def test_session_view_package_logs_multiple_packages() -> None:+def test_session_view_package_logs_multiple_packages(+ session_view: SessionView,+) -> None:"""Test SessionView handles logs for multiple packages simultaneously."""- session_view = SessionView()# Start installing multiple packagesmulti_alert = InstallingPackageAlert(@@ -1182,9 +1159,10 @@ def test_session_view_package_logs_multiple_packages() -> None:)-def test_session_view_package_logs_without_logs() -> None:+def test_session_view_package_logs_without_logs(+ session_view: SessionView,+) -> None:"""Test SessionView handles InstallingPackageAlert without logs (backward compatibility)."""- session_view = SessionView()# Old-style alert without logsalert = InstallingPackageAlert(packages={"requests": "installing"})@@ -1194,9 +1172,10 @@ def test_session_view_package_logs_without_logs() -> None:assert len(session_view.package_logs) == 0-def test_session_view_package_logs_partial_logs() -> None:+def test_session_view_package_logs_partial_logs(+ session_view: SessionView,+) -> None:"""Test SessionView handles alerts with logs but no log_status."""- session_view = SessionView()# Alert with logs but no log_statusalert = InstallingPackageAlert(@@ -1210,9 +1189,10 @@ def test_session_view_package_logs_partial_logs() -> None:assert len(session_view.package_logs) == 0-def test_session_view_package_logs_start_without_existing() -> None:+def test_session_view_package_logs_start_without_existing(+ session_view: SessionView,+) -> None:"""Test package logs start status on package that doesn't exist yet."""- session_view = SessionView()alert = InstallingPackageAlert(packages={"new_package": "installing"},@@ -1227,9 +1207,10 @@ def test_session_view_package_logs_start_without_existing() -> None:)-def test_session_view_package_logs_append_without_existing() -> None:+def test_session_view_package_logs_append_without_existing(+ session_view: SessionView,+) -> None:"""Test package logs append status on package that doesn't exist yet."""- session_view = SessionView()# Append to non-existing package should start with empty stringalert = InstallingPackageAlert(@@ -1245,9 +1226,10 @@ def test_session_view_package_logs_append_without_existing() -> None:)-def test_session_view_package_logs_empty_content() -> None:+def test_session_view_package_logs_empty_content(+ session_view: SessionView,+) -> None:"""Test SessionView handles empty log content."""- session_view = SessionView()alert = InstallingPackageAlert(packages={"empty_logs": "installing"},diff --git a/tests/conftest.py b/tests/conftest.pyindex 4653bfff76..4fdcdc25ca 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -74,6 +74,8 @@ class _MockStream(ThreadSafeStream):def write(self, data: KernelMessage) -> None:self.messages.append(data)+ # Attempt to deserialize the message to ensure it is valid+ deserialize_kernel_message(data)@propertydef operations(self) -> list[MessageOperation]:diff --git a/tests/utils.py b/tests/utils.pyindex 6d92e3e378..df222ba040 100644--- a/tests/utils.py+++ b/tests/utils.py@@ -3,9 +3,17 @@ from __future__ import annotationsimport timefrom typing import TYPE_CHECKING+from marimo._messaging.msgspec_encoder import (+ asdict,+ encode_json_bytes,+)+from marimo._utils.parse_dataclass import parse_raw+if TYPE_CHECKING:from typing import Callable+ import msgspec+def try_assert_n_times(n: int, assert_fn: Callable[[], None]) -> None:"""Attempt an assert multiple times.@@ -21,3 +29,10 @@ def try_assert_n_times(n: int, assert_fn: Callable[[], None]) -> None:n_tries += 1time.sleep(0.1)assert_fn()+++def assert_serialize_roundtrip(obj: msgspec.Struct) -> None:+ serialized = encode_json_bytes(obj)+ cls = type(obj)+ parsed = parse_raw(serialized, cls)+ assert asdict(obj) == asdict(parsed)