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
Apply save-and-restore main decorator across all tests (#9286)
Akshay Agrawal0349628bb15b
diff --git a/tests/_islands/test_island_generator.py b/tests/_islands/test_island_generator.pyindex 7ad8bb1c87..1a31193bca 100644--- a/tests/_islands/test_island_generator.py+++ b/tests/_islands/test_island_generator.py@@ -10,7 +10,6 @@ from marimo._islands._island_generator import (MarimoIslandGenerator,)from tests.mocks import snapshotter-from tests.utils import save_and_restore_mainif TYPE_CHECKING:from pathlib import Path@@ -26,7 +25,6 @@ def test_add_code():assert len(list(generator._app.cell_manager.cells())) == 1-@save_and_restore_mainasync def test_build():generator = MarimoIslandGenerator()generator.add_code("print('Hello, World!')")@@ -41,7 +39,6 @@ async def test_build():await generator.build()-@save_and_restore_mainasync def test_render():generator = MarimoIslandGenerator()block1 = generator.add_code("import marimo as mo")@@ -80,7 +77,6 @@ async def test_render():)-@save_and_restore_mainasync def test_render_multiline_markdown():generator = MarimoIslandGenerator()stub = generator.add_code(@@ -109,7 +105,6 @@ async def test_render_multiline_markdown():snapshot("markdown.txt", stub.render())-@save_and_restore_mainasync def test_from_file(tmp_path: Path):# Create a temporary marimo filemarimo_file = tmp_path / "temp_marimo_file.py"diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex 1b84d1744e..1d89057efe 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -53,7 +53,6 @@ from marimo._session.session import (from marimo._session.state.session_view import SessionViewfrom marimo._types.ids import ConsumerId, SessionIdfrom marimo._utils.marimo_path import MarimoPath-from tests.utils import save_and_restore_maininitialize_asyncio()@@ -90,7 +89,6 @@ class MockSessionConsumer(SessionConsumer):session_id = SessionId("test")-@save_and_restore_maindef test_queue_manager() -> None:# Test with multiprocessing queuesqueue_manager_mp = QueueManagerImpl(use_multiprocessing=True)@@ -105,7 +103,6 @@ def test_queue_manager() -> None:assert isinstance(queue_manager_thread.input_queue, queue.Queue)-@save_and_restore_maindef test_kernel_manager_run_mode() -> None:# Mock objects and data for testingqueue_manager = QueueManagerImpl(use_multiprocessing=False)@@ -139,7 +136,6 @@ def test_kernel_manager_run_mode() -> None:assert queue_manager.control_queue.empty()-@save_and_restore_maindef test_kernel_manager_edit_mode() -> None:# Mock objects and data for testingqueue_manager = QueueManagerImpl(use_multiprocessing=True)@@ -173,7 +169,6 @@ def test_kernel_manager_edit_mode() -> None:queue_manager.control_queue.join_thread() # type: ignore-@save_and_restore_maindef test_kernel_manager_interrupt(tmp_path: Path) -> None:queue_manager = QueueManagerImpl(use_multiprocessing=True)mode = SessionMode.EDIT@@ -279,7 +274,6 @@ def test_kernel_manager_interrupt(tmp_path: Path) -> None:session_id = SessionId("test_session_id")-@save_and_restore_mainasync def test_session() -> None:session_consumer: Any = MagicMock()session_consumer.connection_state.return_value = ConnectionState.OPEN@@ -325,7 +319,6 @@ async def test_session() -> None:assert session.connection_state() == ConnectionState.CLOSED-@save_and_restore_maindef test_session_disconnect_reconnect() -> None:session_consumer: Any = MagicMock()session_consumer.connection_state.return_value = ConnectionState.OPEN@@ -383,7 +376,6 @@ def test_session_disconnect_reconnect() -> None:assert session.connection_state() == ConnectionState.CLOSED-@save_and_restore_maindef test_session_with_kiosk_consumers() -> None:session_consumer: Any = MagicMock()session_consumer.connection_state.return_value = ConnectionState.OPEN@@ -448,7 +440,6 @@ def test_session_with_kiosk_consumers() -> None:@pytest.mark.flaky(reruns=3)-@save_and_restore_mainasync def test_session_manager_file_watching(tmp_path: Path) -> None:# Create a temporary filetmp_file = tmp_path / "test.py"@@ -604,7 +595,6 @@ def __():session_manager.shutdown()-@save_and_restore_maindef test_watch_mode_does_not_override_config(tmp_path: Path) -> None:"""Test that watch mode does not override config settings."""# Create a temporary file@@ -659,7 +649,6 @@ def test_watch_mode_does_not_override_config(tmp_path: Path) -> None:@pytest.mark.flaky(reruns=3)-@save_and_restore_mainasync def test_watch_mode_with_watcher_on_save_autorun(tmp_path: Path) -> None:"""Test that watch mode with autorun config auto-executes changed cells."""tmp_file = tmp_path / "test.py"@@ -769,7 +758,6 @@ async def test_watch_mode_with_watcher_on_save_autorun(tmp_path: Path) -> None:session_manager.shutdown()-@save_and_restore_mainasync def test_watch_mode_with_watcher_on_save_lazy(tmp_path: Path) -> None:"""Test that watch mode with lazy config marks cells as stale without executing."""tmp_file = tmp_path / "test.py"@@ -868,7 +856,6 @@ async def test_watch_mode_with_watcher_on_save_lazy(tmp_path: Path) -> None:session_manager.shutdown()-@save_and_restore_mainasync def test_session_manager_file_rename() -> None:"""Test that file renaming works correctly with file watching."""# Create two temporary files@@ -986,7 +973,6 @@ def __():os.remove(tmp_path1)-@save_and_restore_maindef test_session_with_script_config_overrides(tmp_path: Path,) -> None:@@ -1038,7 +1024,6 @@ def test_session_with_script_config_overrides(session.close()-@save_and_restore_mainasync def test_caching_extension_respects_mode_and_config() -> None:"""Test caching enablement and mode across edit/run sessions."""from marimo._session.extensions.extensions import (diff --git a/tests/conftest.py b/tests/conftest.pyindex 39b33b9524..f9ba93114c 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -126,6 +126,26 @@ def _ensure_main_has_file() -> Generator[None, None, None]:del current_main.__file__[email protected](autouse=True)+def _save_and_restore_main(+ _ensure_main_has_file: None,+) -> Generator[None, None, None]:+ """Restore sys.modules["__main__"] after each test.++ marimo's kernel swaps out the main module via patch_main_module;+ without this fixture, that swap leaks into subsequent tests.+ """+ main = sys.modules.get("__main__")+ if main is None:+ yield+ return++ try:+ yield+ finally:+ sys.modules["__main__"] = main++@pytest.fixture(autouse=True)def patch_random_seed(monkeypatch: pytest.MonkeyPatch) -> None:"""Patch UIElement._random_seed to use a fixed seed for testing"""diff --git a/tests/utils.py b/tests/utils.pyindex ad59b7a6bb..5d2e3bf0b2 100644--- a/tests/utils.py+++ b/tests/utils.py@@ -1,11 +1,8 @@from __future__ import annotations-import asyncio-import functoolsimport inspect-import sysimport time-from typing import TYPE_CHECKING, Any, TypeVar+from typing import TYPE_CHECKING, Anyfrom marimo._messaging.msgspec_encoder import (asdict,@@ -18,25 +15,6 @@ if TYPE_CHECKING:import msgspec-F = TypeVar("F", bound="Callable[..., Any]")---# TODO(akshayka): automatically do this for every test in our test suite-def save_and_restore_main(f: F) -> F:- """Kernels swap out the main module; restore it after running tests."""-- @functools.wraps(f)- def wrapper(*args: Any, **kwargs: Any) -> None:- main = sys.modules["__main__"]- try:- res = f(*args, **kwargs)- if asyncio.iscoroutine(res):- asyncio.run(res)- finally:- sys.modules["__main__"] = main-- return wrapper # type: ignore-def try_assert_n_times(n: int, assert_fn: Callable[[], None]) -> None:"""Attempt an assert multiple times.