Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: resolve pytest race condition during edit (#10139)

Dylan Madisetti784810a75fce
diff --git a/examples/testing/test_with_pytest.py b/examples/testing/test_with_pytest.py
index 78b7fff421..3e816ec83c 100644
--- a/examples/testing/test_with_pytest.py
+++ b/examples/testing/test_with_pytest.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.15.5"
+__generated_with = "0.23.9"
app = marimo.App()
diff --git a/marimo/_ast/pytest.py b/marimo/_ast/pytest.py
index 48d201d31d..cfbe0a9d93 100644
--- a/marimo/_ast/pytest.py
+++ b/marimo/_ast/pytest.py
@@ -457,17 +457,27 @@ def process_for_pytest(func: Fn, cell: Cell) -> None:
f"Expected function or class definition, got {type(scope).__name__}"
)
# Get first frame not in library to insert the class.
- # May be multiple levels if called from pytest or something.
+ # May be multiple levels if called from pytest or somewhere else.
frames = fast_stack()
+ notebook_file = inspect.getfile(func)
cls = build_test_class(
- scope.body, run, inspect.getfile(func), name, cell.defs, frames
+ scope.body, run, notebook_file, name, cell.defs, frames
)
- # ensure marimo/_ not in frame path, using this file as a reference.
- library = Path(__file__).parent.parent
+ # Inject the stub class into the notebook module's own frame so pytest's
+ # module-level collection finds it.
+ target = Path(notebook_file).resolve()
for frame in frames:
- if library not in Path(frame.filename).parents:
- # Insert the class into the frame.
+ if Path(frame.filename).resolve() == target:
+ # At module level f_locals is the module dict, so this persists.
frame.frame.f_locals[cls.__name__] = cls
break
+ else:
+ # If no frame matches the notebook source, use the first frame outside
+ # the marimo package.
+ library = Path(__file__).parent.parent
+ for frame in frames:
+ if library not in Path(frame.filename).parents:
+ frame.frame.f_locals[cls.__name__] = cls
+ break
diff --git a/marimo/_runtime/pytest.py b/marimo/_runtime/pytest.py
index e9535d9ca6..78470f9576 100644
--- a/marimo/_runtime/pytest.py
+++ b/marimo/_runtime/pytest.py
@@ -1,13 +1,14 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import functools
import os
import re
import sys
+import types
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, cast
-from marimo._ast.cell import Cell
from marimo._ast.pytest import MARIMO_TEST_STUB_NAME
from marimo._ast.variables import demangle_locals_in_text
from marimo._cli.print import bold, green
@@ -20,10 +21,13 @@ MARIMO_TEST_BLOCK_REGEX = re.compile(rf"{MARIMO_TEST_STUB_NAME}_\d+[(?::)\.]+")
if TYPE_CHECKING:
- from collections.abc import Callable
from pathlib import Path
- import _pytest.Item # type: ignore
+ import pytest
+ from _pytest.nodes import Collector, Item, Node
+
+ class _LiveModule(pytest.Module):
+ def _set_globals(self, _marimo_globals: dict[str, Any]) -> None: ...
@dataclass
@@ -107,70 +111,66 @@ def _rewrite_longrepr(longrepr: Any) -> None:
reprcrash.message = demangle_locals_in_text(reprcrash.message)
-def _sub_function(
- old_item: _pytest.Item, parent: Any, fn: Callable[..., Any]
-) -> _pytest.Item:
- # Directly execute the cell, since this means it's a toplevel function with no deps.
- # Or a cell where which we already wrapped in skip.
- if isinstance(old_item.obj, Cell):
- return old_item
-
- import pytest # type: ignore
- from _pytest.fixtures import FuncFixtureInfo # type: ignore
-
- fixtureinfo = old_item._fixtureinfo
- param_names: set[str] = set()
-
- if hasattr(old_item, "callspec") and old_item.callspec:
- params: dict[str, Any] = old_item.callspec.params
- param_names = set(params.keys())
-
- def make_test_func(
- func_JYWB: Callable[..., Any], param_dict: dict[str, Any]
- ) -> Callable[[], Any]:
- # note _JYWB is a suffix to easily detect in stack trace for
- # removal.
- # Also no functools.wraps(func) because we need the empty
- # call signature
- def test_wrapper(*args: Any, **kwargs: Any) -> Any:
- return func_JYWB(*args, **kwargs, **param_dict)
-
- # but copy attributes from the original function
- test_wrapper.__name__ = func_JYWB.__name__
- test_wrapper.__module__ = func_JYWB.__module__
- return test_wrapper
-
- fn = make_test_func(fn, params)
-
- # Filter out parametrized args from fixtureinfo since they're baked in
- fixtureinfo = FuncFixtureInfo(
- argnames=tuple(
- a for a in fixtureinfo.argnames if a not in param_names
- ),
- initialnames=tuple(
- a for a in fixtureinfo.initialnames if a not in param_names
- ),
- names_closure=[
- a for a in fixtureinfo.names_closure if a not in param_names
- ],
- name2fixturedefs={
- k: v
- for k, v in fixtureinfo.name2fixturedefs.items()
- if k not in param_names
- },
- )
+def _is_fixture(obj: Any) -> bool:
+ """Whether `obj` is a pytest fixture.
- pyfn = pytest.Function.from_parent(
- parent,
- name=old_item.name,
- callobj=fn,
- fixtureinfo=fixtureinfo, # Preserve fixture metadata (minus params)
+ pytest <9 tags the function with `_pytestfixturefunction`; pytest >=9 wraps
+ it in a `FixtureFunctionDefinition`. Duck-typed on the class name to avoid a
+ private import that doesn't exist across both.
+ """
+ return hasattr(obj, "_pytestfixturefunction") or (
+ type(obj).__name__ == "FixtureFunctionDefinition"
)
- # Attributes that need to be carried over.
- for attr in ["keywords", "own_markers"]:
- if hasattr(old_item, attr):
- setattr(pyfn, attr, getattr(old_item, attr))
- return pyfn
+
+
+def _global_scope_defs() -> set[str]:
+ """Names visible to every cell: the setup cell and top-level
+ (`@app.function` / `@app.class_definition`) definitions.
+
+ Used to determine notebook-global fixtures for live collection.
+ Returns an empty set when no kernel context is available.
+ """
+ from marimo._ast.names import SETUP_CELL_NAME
+
+ ctx = safe_get_context()
+ if ctx is None:
+ return set()
+ graph = ctx.graph
+ hint = graph.cells_serving_serialization_hint
+ out: set[str] = set()
+ for cid, cell in graph.cells.items():
+ if str(cid) == SETUP_CELL_NAME or cid in hint:
+ out |= cell.defs
+ return out
+
+
+def _live_module_cls() -> type[_LiveModule]:
+ """`pytest.Module` that collects from the kernel's live globals.
+
+ The kernel has already executed the notebook's cells, so the live test
+ objects — carrying the user's current (possibly unsaved) definitions and
+ `@parametrize` markers — are sitting in the run namespace.
+
+ Defined lazily because pytest is an optional dependency.
+ """
+ import pytest
+
+ class _LiveModuleImpl(pytest.Module):
+ _marimo_globals: dict[str, Any]
+
+ def _set_globals(self, _marimo_globals: dict[str, Any]) -> None:
+ self._marimo_globals = _marimo_globals
+
+ def _getobj(self) -> types.ModuleType:
+ module = types.ModuleType(self.path.stem)
+ module.__file__ = str(self.path)
+ # Copy in: pytest mutates the module dict during collection, so we
+ # must not alias (and pollute) the live kernel namespace.
+ module.__dict__.update(self._marimo_globals)
+ return module
+
+ return cast("type[_LiveModule]", _LiveModuleImpl)
class ReplaceStubPlugin:
@@ -181,6 +181,7 @@ class ReplaceStubPlugin:
self,
defs: set[str] | None = None,
lcls: dict[str, Any] | None = None,
+ global_defs: set[str] | None = None,
) -> None:
if lcls is None:
lcls = globals()
@@ -189,87 +190,62 @@ class ReplaceStubPlugin:
self.lcls = lcls
self.defs = defs
+ # Notebook-global names (setup + top-level defs). Together with `defs`
+ # they bound which fixtures stay visible during live collection; any
+ # fixture outside this scope belongs to a sibling cell and is hidden to
+ # preserve cell isolation.
+ self.global_defs = global_defs or set()
self._result = MarimoPytestResult()
- def pytest_collection_modifyitems(
- self, items: list[Any], session: Any
- ) -> None:
- """Provided pytest has statically collected all the relevant tests:
- - Filter based on the expected defs of the cell context.
- - Sub in the function references in scope opposed to the pytest
- determined stubs.
+ def _live_module_globals(self) -> dict[str, Any]:
+ """The kernel globals, minus fixtures owned by sibling cells.
+
+ Non-fixture names are kept wholesale so cross-cell variable refs and
+ decorator values resolve. Fixtures are kept only when in scope (this
+ run's `defs` or a notebook-global def); a sibling cell's fixture is
+ dropped so a test referencing it errors with "fixture not found",
+ preserving cell isolation.
+ """
+ scope = self.defs | self.global_defs
+ return {
+ name: value
+ for name, value in self.lcls.items()
+ if name in scope or not _is_fixture(value)
+ }
+
+ def pytest_pycollect_makemodule(
+ self, module_path: Path, parent: Collector
+ ) -> _LiveModule:
+ """Collect from the kernel's live globals rather than disk."""
+ module = _live_module_cls().from_parent(parent, path=module_path)
+ module._set_globals(self._live_module_globals())
+ return module
+
+ def _live_owner(self, item: Item) -> str | None:
+ """Name of the module-level object (function/class) owning `item`."""
+ import pytest
+
+ node: Node = item
+ while node.parent is not None and not isinstance(
+ node.parent, pytest.Module
+ ):
+ node = node.parent
+ if node.parent is None:
+ return None
+ name = getattr(node, "originalname", node.name)
+ return name if isinstance(name, str) else None
+
+ def pytest_collection_modifyitems(self, items: list[pytest.Item]) -> None:
+ """Filter to just the items owned by this cell's defs.
+
+ Items were collected from the live kernel globals, so they are
+ already the runtime implementations with current markers, and the
+ in-scope fixtures are present in the synthetic module (see
+ `_live_module_globals`).
"""
- # Not official marimo dependencies
- # So don't import at the top level.
- import _pytest # type: ignore
-
- def is_fixture(obj: Any) -> bool:
- """Check if object is a pytest fixture."""
- return callable(obj) and hasattr(obj, "_pytestfixturefunction")
-
- # Register cell-scoped fixtures before processing items
- # Use names_closure (transitive deps) instead of just argnames
- # to handle fixture dependency chains
- fm = session._fixturemanager
- registered_fixtures: set[str] = set()
- for item in items:
- if hasattr(item, "_fixtureinfo"):
- for argname in item._fixtureinfo.names_closure:
- if (
- argname not in registered_fixtures
- and argname in self.lcls
- and is_fixture(self.lcls[argname])
- ):
- obj = self.lcls[argname]
- marker = obj._pytestfixturefunction
- fm._register_fixture(
- name=argname,
- func=obj,
- nodeid="", # Global visibility
- scope=marker.scope,
- params=marker.params,
- ids=marker.ids,
- autouse=marker.autouse,
- )
- registered_fixtures.add(argname)
-
- to_collect = []
- # Filter tests, and create new "Functions" with the relevant references
- # where needed.
- for item in items:
- head: Any = item
- path: list[str] = []
-
- while isinstance(head.parent.parent, _pytest.python.Class):
- path.append(head.name)
- head = head.parent
-
- # Handle @app.class_definition classes (not wrapped in stub class)
- # Check if head is a Function directly inside a Class whose name is in defs
- if isinstance(head, _pytest.python.Function) and isinstance(
- head.parent, _pytest.python.Class
- ):
- parent_name = getattr(
- head.parent, "originalname", head.parent.name
- )
- if parent_name in self.defs:
- path.append(head.name)
- head = head.parent
-
- # For test name, helps keep names relative to the root.
- parent: Any = item.parent
- if not path:
- parent = parent.parent
-
- name: str = getattr(head, "originalname", head.name)
- if name in self.defs:
- value: Any = self.lcls[name]
- for attr in reversed(path):
- if isinstance(value, type):
- value = value()
- value = getattr(value, attr)
- to_collect.append(_sub_function(item, parent, value))
- items[:] = to_collect
+ items[:] = [
+ item for item in items if self._live_owner(item) in self.defs
+ ]
def pytest_terminal_summary(self, terminalreporter: Any) -> None:
"""Provide a clean summary of test results. Gives something like:
@@ -313,9 +289,7 @@ class ReplaceStubPlugin:
tr.write_line(self._result.summary)
- def pytest_runtest_logreport(
- self, report: _pytest.reports.TestReport
- ) -> None:
+ def pytest_runtest_logreport(self, report: pytest.TestReport) -> None:
"""In place updates the report for some better formatting.
In particular:
- removes stub class reference for scoped tests
@@ -347,24 +321,29 @@ def run_pytest(
defs: set[str] | None = None,
lcls: dict[str, Any] | None = None,
notebook_path: Path | str | None = None,
+ global_defs: set[str] | None = None,
) -> MarimoPytestResult:
- # Note, there does seem to be a bit of a race condition if the file hasn't
- # saved yet...
- # But I think this may only be noticeable with rapidly adding, renaming, and
- # running tests.
+ # Collection reads the kernel's live globals (see
+ # ReplaceStubPlugin.pytest_pycollect_makemodule).
DependencyManager.pytest.require(
"pytest is required for reactive "
"testing. Please report to github if you would like a different testing "
"suite supported."
)
- import pytest # type: ignore
+ import pytest
if not notebook_path:
# Translate name to python module
notebook_path = _get_name()
notebook_path = str(notebook_path)
+ if global_defs is None:
+ # In the kernel this resolves setup + top-level defs from the live
+ # graph; with no context (e.g. direct `app.run()`) it is empty and the
+ # caller may pass an explicit set.
+ global_defs = _global_scope_defs()
+
# Hold on to modules since we want to refresh them in order to enable
# repeated calls.
module_snapshot = dict(sys.modules)
@@ -379,7 +358,7 @@ def run_pytest(
# Ideally, --import-mode=importlib would be a great flag- however the
# method is too brittle to handle absolute paths. As such, we default to
# the normal behavior (in which pytest alters the system path).
- plugin = ReplaceStubPlugin(defs, lcls)
+ plugin = ReplaceStubPlugin(defs, lcls, global_defs=global_defs)
try:
# pytest in wasm doesn't seem to set environment variables correctly.
# This work around is to prevent collision with non-wasm testing.
diff --git a/marimo/_smoke_tests/reactive_pytest.py b/marimo/_smoke_tests/reactive_pytest.py
index bd21bd4177..e8c3d01add 100644
--- a/marimo/_smoke_tests/reactive_pytest.py
+++ b/marimo/_smoke_tests/reactive_pytest.py
@@ -9,9 +9,13 @@
import marimo
-__generated_with = "0.15.5"
+__generated_with = "0.23.14"
app = marimo.App()
+with app.setup:
+ import pytest
+ import marimo as mo
+
@app.function
def inc(x):
@@ -30,12 +34,10 @@ def test_sanity():
return
-def _(pytest):
- @pytest.mark.parametrize("x, y", [(3, 4), (4, 5)])
- def test_parameterized(x, y):
- assert inc(x) == y, "These tests should pass."
- return
[email protected]("x, y", [(3, 4), (4, 5)])
+def test_parameterized(x, y):
+ assert inc(x) == y, "These tests should pass."
@app.function
@@ -44,7 +46,7 @@ def cross_cell_fail():
@app.cell
-def _(pytest):
+def _():
@pytest.mark.parametrize("x, y", [(3, 4), (4, 5)])
def test_parameterized_collected(x, y):
assert inc(x) == y, "These tests should pass."
@@ -60,13 +62,14 @@ def _(pytest):
def test_transitive_uri():
cross_cell_fail()
-
- class TestParent():
+ class TestParent:
def test_parent_inner(self):
assert True
- class TestChild():
+
+ class TestChild:
def test_inner(self):
assert True
+
return
@@ -79,14 +82,20 @@ def _():
a = 2
b = 5
assert a + a == b
+
return
@app.cell
-def imports():
- import pytest
- import marimo as mo
- return (pytest,)
+def _():
+ @pytest.fixture
+ def foo():
+ return 7
+
+ def test_fixture(foo):
+ assert foo == 8
+
+ return
if __name__ == "__main__":
diff --git a/pyproject.toml b/pyproject.toml
index 7ea8101899..5f13c8d892 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -238,6 +238,7 @@ typecheck = [
"leafmap~=0.39.2",
"panel>=1.5.3",
"polars>=1.9.0",
+ "pytest>=9.0.2",
"duckdb>=1.0.0",
"narwhals>=2.0.0",
"matplotlib>=3.8.0",
diff --git a/tests/_runtime/snapshots/offline_collection_inside_marimo_package.txt b/tests/_runtime/snapshots/offline_collection_inside_marimo_package.txt
new file mode 100644
index 0000000000..a70265a0e2
--- /dev/null
+++ b/tests/_runtime/snapshots/offline_collection_inside_marimo_package.txt
@@ -0,0 +1,5 @@
+marimo/_smoke_tests/_offline_collect_probe.py::MarimoTestBlock_0::test_param[1]
+marimo/_smoke_tests/_offline_collect_probe.py::MarimoTestBlock_0::test_param[2]
+marimo/_smoke_tests/_offline_collect_probe.py::MarimoTestBlock_0::test_uses_fixture
+
+3 tests collected in Ns
diff --git a/tests/_runtime/test_pytest_runtime.py b/tests/_runtime/test_pytest_runtime.py
index a7b1d9c0ea..f1dce7353b 100644
--- a/tests/_runtime/test_pytest_runtime.py
+++ b/tests/_runtime/test_pytest_runtime.py
@@ -2,16 +2,21 @@ from __future__ import annotations
import asyncio
import os
+import re
import sys
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
+from tests.mocks import snapshotter
+
if TYPE_CHECKING:
from marimo._runtime.pytest import run_pytest as _run_pytest_type
from tests._runtime.script_data.contains_tests import app as _app_type
+snapshot = snapshotter(__file__)
+
# Format: (passed, skipped, failed, errors)
_DEF_COUNT = {
# fixtures, not tests
@@ -49,8 +54,9 @@ _ISOLATION_DEFS = {"test_cross_cell_fixture_fails", "test_missing_fixture"}
@pytest.fixture(scope="module")
def notebook_env() -> tuple[
- type[_app_type], dict[str, object], Path, type[_run_pytest_type]
+ type[_app_type], dict[str, object], Path, type[_run_pytest_type], set[str]
]:
+ from marimo._ast.names import SETUP_CELL_NAME, TOPLEVEL_CELL_PREFIX
from marimo._runtime.pytest import run_pytest
from tests._runtime.script_data.contains_tests import app
@@ -58,6 +64,16 @@ def notebook_env() -> tuple[
lcls = dict(lcls)
path = Path(__file__).parent / "script_data/contains_tests.py"
+ # Notebook-global defs (setup + top-level), normally resolved from the live
+ # kernel graph; the script-mode `app.run()` above has no kernel context, so
+ # compute them here and thread them through to `run_pytest`.
+ global_defs: set[str] = set()
+ for cid, cell in app._cell_manager.valid_cells():
+ if str(cid) == SETUP_CELL_NAME or cell._name.startswith(
+ TOPLEVEL_CELL_PREFIX
+ ):
+ global_defs |= cell._cell.defs
+
# Turn off for recursion guard
previous = os.environ.get("PYTEST_CURRENT_TEST", "")
os.environ["PYTEST_CURRENT_TEST"] = ""
@@ -65,7 +81,7 @@ def notebook_env() -> tuple[
# Give time for env changes to sync (helps with race conditions on Windows)
asyncio.run(asyncio.sleep(0.1))
- yield app, lcls, path, run_pytest
+ yield app, lcls, path, run_pytest, global_defs
if previous:
os.environ["PYTEST_CURRENT_TEST"] = previous
@@ -76,7 +92,7 @@ def notebook_env() -> tuple[
@pytest.mark.skipif(sys.platform == "win32", reason="Fails on Windows CI")
def test_batched_cells(notebook_env):
"""Batch all non-isolation cells into a single run_pytest call."""
- app, lcls, path, run_pytest = notebook_env
+ app, lcls, path, run_pytest, global_defs = notebook_env
batch_defs: set[str] = set()
batch_expected = [0, 0, 0, 0] # passed, skipped, failed, errors
@@ -87,7 +103,12 @@ def test_batched_cells(notebook_env):
for i, v in enumerate(_DEF_COUNT[d]):
batch_expected[i] += v
- response = run_pytest(defs=batch_defs, lcls=lcls, notebook_path=path)
+ response = run_pytest(
+ defs=batch_defs,
+ lcls=lcls,
+ notebook_path=path,
+ global_defs=global_defs,
+ )
assert (
response.passed,
response.skipped,
@@ -100,13 +121,16 @@ def test_batched_cells(notebook_env):
@pytest.mark.skipif(sys.platform == "win32", reason="Fails on Windows CI")
def test_isolation_cells(notebook_env):
"""Isolation tests run separately to verify fixture scoping errors."""
- app, lcls, path, run_pytest = notebook_env
+ app, lcls, path, run_pytest, global_defs = notebook_env
total = 0
for cell in app._cell_manager.cells():
if cell and cell.__test__ and (cell.defs & _ISOLATION_DEFS):
response = run_pytest(
- defs=cell.defs, lcls=lcls, notebook_path=path
+ defs=cell.defs,
+ lcls=lcls,
+ notebook_path=path,
+ global_defs=global_defs,
)
expected = tuple(
map(
@@ -123,6 +147,158 @@ def test_isolation_cells(notebook_env):
assert total == 2
[email protected](sys.platform == "win32", reason="Fails on Windows CI")
+def test_live_collection_ignores_stale_disk(tmp_path) -> None:
+ """Reactive collection reads the kernel's live globals, not the on-disk
+ notebook, so unsaved edits are picked up without racing the save (#4797):
+ new parametrize values, added tests, and renamed tests all take effect
+ while the file on disk is deliberately stale.
+ """
+ import marimo
+ from marimo._runtime.pytest import run_pytest
+
+ app = marimo.App()
+
+ @app.cell
+ def _():
+ import pytest
+
+ return (pytest,)
+
+ @app.cell
+ def _(pytest):
+ # Live: 3 param rows (edited/added a row), an added test, a renamed one.
+ @pytest.mark.parametrize(("a", "b"), [(1, 2), (3, 4), (9, 9)])
+ def test_values(a, b):
+ assert a <= b
+
+ def test_added():
+ assert True
+
+ def test_renamed_target():
+ assert True
+
+ return
+
+ _, lcls = app.run()
+ lcls = dict(lcls)
+ defs = {"test_values", "test_added", "test_renamed_target"}
+
+ # On-disk file is stale: one param row, the pre-rename name, no added test.
+ stale = tmp_path / "notebook.py"
+ stale.write_text(
+ "import marimo\n"
+ "app = marimo.App()\n\n"
+ "@app.cell\n"
+ "def _():\n"
+ " import pytest\n"
+ " return (pytest,)\n\n"
+ "@app.cell\n"
+ "def _(pytest):\n"
+ " @pytest.mark.parametrize(('a', 'b'), [(1, 2)])\n"
+ " def test_values(a, b):\n"
+ " assert a <= b\n"
+ " def test_old_name():\n"
+ " assert True\n"
+ " return\n"
+ )
+
+ # Recursion guard: we are invoking pytest from within pytest.
+ previous = os.environ.get("PYTEST_CURRENT_TEST", "")
+ os.environ.pop("PYTEST_CURRENT_TEST", None)
+ asyncio.run(asyncio.sleep(0.1))
+ try:
+ result = run_pytest(defs=defs, lcls=lcls, notebook_path=stale)
+ finally:
+ if previous:
+ os.environ["PYTEST_CURRENT_TEST"] = previous
+
+ # 3 live param rows + test_added + test_renamed_target = 5, all passing.
+ # The stale disk file (one row, test_old_name) is never read.
+ assert (result.passed, result.failed, result.errors) == (5, 0, 0), (
+ result.output
+ )
+ assert "test_renamed_target" in result.output
+ assert "test_old_name" not in result.output
+
+
[email protected](sys.platform == "win32", reason="Fails on Windows CI")
+def test_offline_collection_inside_marimo_package() -> None:
+ """Plain `pytest notebook.py` must collect multi-def cells, classes, and
+ fixture-using tests even when the notebook lives inside the marimo package.
+
+ `process_for_pytest` injects the generated MarimoTestBlock stub into the
+ notebook's own module frame; an earlier "first frame not under marimo/"
+ heuristic skipped that frame for notebooks inside the package (e.g.
+ marimo/_smoke_tests/*), silently dropping every test in such cells.
+ """
+ import subprocess
+
+ import marimo
+
+ notebook = """
+import marimo
+app = marimo.App()
+
+with app.setup:
+ import pytest
+
+
+def _():
+ @pytest.fixture
+ def my_fixture():
+ return 7
+
+ def test_uses_fixture(my_fixture):
+ assert my_fixture == 7
+
+ @pytest.mark.parametrize("x", [1, 2])
+ def test_param(x):
+ assert x > 0
+ return
+
+
+if __name__ == "__main__":
+ app.run()
+"""
+ # The bug only triggers when the notebook path is inside the marimo package.
+ pkg_dir = Path(marimo.__file__).parent / "_smoke_tests"
+ nb = pkg_dir / f"_offline_collect_probe_{os.getpid()}.py"
+ nb.write_text(notebook)
+ # Mimic a standalone CLI run: the inherited PYTEST_CURRENT_TEST (set by the
+ # outer pytest) would otherwise disable marimo's pytest test-rewrite in the
+ # child during collection.
+ env = {k: v for k, v in os.environ.items() if k != "PYTEST_CURRENT_TEST"}
+ try:
+ proc = subprocess.run(
+ [
+ sys.executable,
+ "-m",
+ "pytest",
+ str(nb),
+ "--collect-only",
+ "-q",
+ "-p",
+ "no:cacheprovider",
+ "-p",
+ "no:inline_snapshot",
+ ],
+ capture_output=True,
+ text=True,
+ cwd=Path(marimo.__file__).parent.parent,
+ env=env,
+ )
+ finally:
+ nb.unlink(missing_ok=True)
+
+ out = proc.stdout + proc.stderr
+ # Sanitize the pid-suffixed filename and timing, which vary per run.
+ out = re.sub(r"_offline_collect_probe_\d+", "_offline_collect_probe", out)
+ out = re.sub(r"in [\d.]+s", "in Ns", out)
+ snapshot("offline_collection_inside_marimo_package.txt", out)
+
+
def test_pytest_result_summary_includes_xfail() -> None:
from marimo._runtime.pytest import MarimoPytestResult