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.

experimental: reactive pytest (#3938)

Dylan Madisettidc891eec2b63
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index a579723927..cfae96844b 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -1092,6 +1092,31 @@ export const UserConfigForm: React.FC = () => {
</div>
)}
/>
+ <FormField
+ control={form.control}
+ name="experimental.reactive_tests"
+ render={({ field }) => (
+ <div className="flex flex-col gap-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel className="font-normal">
+ Autorun Unit Tests
+ </FormLabel>
+ <FormControl>
+ <Checkbox
+ data-testid="reactive-test-checkbox"
+ checked={field.value === true}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ <FormDescription>
+ Enable experimental reactive pytest tests in notebook. When
+ a cell contains only test functions and classes, marimo will
+ automatically run relevant tests.
+ </FormDescription>{" "}
+ </div>
+ )}
+ />
</SettingGroup>
);
}
diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsx
index ff3af7d933..341e7d21ce 100644
--- a/frontend/src/core/config/feature-flag.tsx
+++ b/frontend/src/core/config/feature-flag.tsx
@@ -12,6 +12,7 @@ export interface ExperimentalFeatures {
wasm_layouts: boolean;
scratchpad: boolean;
rtc: boolean;
+ reactive_tests: boolean;
// Add new feature flags here
}
@@ -21,6 +22,7 @@ const defaultValues: ExperimentalFeatures = {
wasm_layouts: false,
scratchpad: true,
rtc: false,
+ reactive_tests: false,
};
export function getFeatureFlag<T extends keyof ExperimentalFeatures>(
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 5769821d6c..9ddfc035e0 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -181,6 +181,8 @@ class CellImpl:
_raw_sqls: ParsedSQLStatements = dataclasses.field(
default_factory=ParsedSQLStatements
)
+ # Whether this cell can be executed as a test cell.
+ _test: bool = False
def configure(self, update: dict[str, Any] | CellConfig) -> CellImpl:
"""Update the cell config.
@@ -417,11 +419,8 @@ class Cell:
# Number of reserved arguments for pytest
_pytest_reserved: set[str] = dataclasses.field(default_factory=set)
- # The property __test__ is picked up by nose and pytest.
- # We have the compiler mark if the cell name starts with test_
- # _or_, is comprised of only tests; allowing for testing suites to
- # collect this cell.
- _test: bool = False
+ # Whether to expose this cell as a test cell.
+ _test_allowed: bool = False
@property
def name(self) -> str:
@@ -491,9 +490,13 @@ class Cell:
"""
)
+ # The property __test__ is picked up by nose and pytest.
+ # We have the compiler mark if the cell name starts with test_
+ # _or_, is comprised of only tests; allowing for testing suites to
+ # collect this cell.
@property
def __test__(self) -> bool:
- return self._test
+ return self._test_allowed
def _register_app(self, app: InternalApp) -> None:
self._app = app
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index 79a25f1421..b97fc00f44 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -72,16 +72,17 @@ def ends_with_semicolon(code: str) -> bool:
def contains_only_tests(tree: ast.Module) -> bool:
"""Returns True if the module contains only test functions."""
- scope = tree.body[0]
- assert isinstance(scope, (ast.FunctionDef, ast.AsyncFunctionDef))
- for node in scope.body:
+ scope = tree.body
+ for node in scope:
+ if isinstance(node, ast.Return):
+ return True
if not isinstance(
node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
):
return False
if not node.name.lower().startswith("test"):
return False
- return True
+ return bool(scope)
def cache(filename: str, code: str) -> None:
@@ -168,6 +169,7 @@ def compile_cell(
cell_id=cell_id,
)
+ is_test = contains_only_tests(module)
is_import_block = all(
isinstance(stmt, (ast.Import, ast.ImportFrom)) for stmt in module.body
)
@@ -208,7 +210,7 @@ def compile_cell(
cache(filename, code)
# pytest assertion rewriting, gives more context for assertion failures.
- if test_rewrite:
+ if is_test or test_rewrite:
# pytest is not required, so fail gracefully if needed
try:
from _pytest.assertion.rewrite import ( # type: ignore
@@ -270,6 +272,7 @@ def compile_cell(
body=body,
last_expr=last_expr,
cell_id=cell_id,
+ _test=is_test,
)
@@ -329,15 +332,17 @@ def toplevel_cell_factory(
lnum + decorator.end_lineno - 1, # Scrub the decorator
0,
)
+
+ cell = compile_cell(
+ cell_code,
+ cell_id=cell_id,
+ source_position=source_position,
+ test_rewrite=test_rewrite,
+ )
return Cell(
_name=f.__name__,
- _cell=compile_cell(
- cell_code,
- cell_id=cell_id,
- source_position=source_position,
- test_rewrite=test_rewrite,
- ),
- _test=f.__name__.startswith("test_"),
+ _cell=cell,
+ _test_allowed=cell._test or f.__name__.startswith("test_"),
)
@@ -462,13 +467,14 @@ def cell_factory(
f, lnum + start_line - 1, col_offset
)
+ cell = compile_cell(
+ cell_code,
+ cell_id=cell_id,
+ source_position=source_position,
+ test_rewrite=test_rewrite,
+ )
return Cell(
_name=f.__name__,
- _cell=compile_cell(
- cell_code,
- cell_id=cell_id,
- source_position=source_position,
- test_rewrite=test_rewrite,
- ),
- _test=f.__name__.startswith("test_") or contains_only_tests(tree),
+ _cell=cell,
+ _test_allowed=cell._test or f.__name__.startswith("test_"),
)
diff --git a/marimo/_ast/pytest.py b/marimo/_ast/pytest.py
index 84b5683717..d82bad1153 100644
--- a/marimo/_ast/pytest.py
+++ b/marimo/_ast/pytest.py
@@ -17,6 +17,8 @@ if TYPE_CHECKING:
Fn = TypeVar("Fn", bound=Callable[..., Any])
+MARIMO_TEST_STUB_NAME = "MarimoTestBlock"
+
block_incrementer = itertools.count()
@@ -152,6 +154,8 @@ def build_test_class(
"""
tests = {}
for node in body:
+ if isinstance(node, ast.Return):
+ continue
assert isinstance(
node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
), (
@@ -251,13 +255,13 @@ def process_for_pytest(func: Fn, cell: Cell) -> None:
return
# Turn off test for the cell itself in this case.
- cell._test = False
+ cell._test_allowed = False
tree = ast.parse(inspect.getsource(func))
run = functools.cache(cell.run)
# Must be a unique name, otherwise won't be injected properly.
- name = f"MarimoTestBlock_{next(block_incrementer)}"
+ name = f"{MARIMO_TEST_STUB_NAME}_{next(block_incrementer)}"
scope = tree.body[0]
assert isinstance(
diff --git a/marimo/_runtime/pytest.py b/marimo/_runtime/pytest.py
new file mode 100644
index 0000000000..c58e53c9e8
--- /dev/null
+++ b/marimo/_runtime/pytest.py
@@ -0,0 +1,267 @@
+# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+import re
+import sys
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Callable, Optional
+
+import marimo
+from marimo._ast.pytest import MARIMO_TEST_STUB_NAME
+from marimo._cli.print import bold, green
+from marimo._runtime.capture import capture_stdout
+from marimo._runtime.context import ContextNotInitializedError, get_context
+
+MARIMO_TEST_BLOCK_REGEX = re.compile(rf"{MARIMO_TEST_STUB_NAME}_\d+[(?::)\.]+")
+
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ import _pytest # type: ignore
+
+
+@dataclass
+class MarimoPytestResult:
+ passed: int = 0
+ failed: int = 0
+ errors: int = 0
+ skipped: int = 0
+ output: Optional[str] = None
+
+ @property
+ def total(self) -> int:
+ return self.skipped + self.passed + self.failed + self.errors
+
+ @property
+ def summary(self) -> str:
+ return (
+ f"Total: {self.total}, Passed: {self.passed}, "
+ f"Failed: {self.failed}, Errors: {self.errors}, "
+ f"Skipped: {self.skipped}"
+ )
+
+
+def _maybe_name() -> str:
+ try:
+ ctx: Any = get_context()
+ if ctx.filename is not None:
+ filename = ctx.filename
+ except ContextNotInitializedError:
+ filename = "notebook.py"
+ assert isinstance(filename, str)
+ return filename
+
+
+def _to_marimo_uri(uri: str) -> str:
+ """Convert a file path URI to a marimo URI if it matches the cell pattern."""
+ # Should be like
+ # /tmp/marimo_1234567/__marimo__cell_1234_.py
+ if "__marimo__cell_" not in uri:
+ return uri
+ cell_id = uri.split("_")[6]
+
+ notebook = os.path.relpath(_maybe_name(), marimo.notebook_location())
+ return f"marimo://{notebook}#cell_id={cell_id}"
+
+
+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, marimo._ast.cell.Cell):
+ return old_item
+
+ import pytest # type: ignore
+
+ if hasattr(old_item, "callspec") and old_item.callspec:
+ params: dict[str, Any] = old_item.callspec.params
+
+ 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() -> Any:
+ return func_JYWB(**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)
+ pyfn = pytest.Function.from_parent(parent, name=old_item.name, callobj=fn)
+ # 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
+
+
+class ReplaceStubPlugin:
+ """Allows pytest to run in the runtime, by replacing the statically
+ collected stubs with the runtime relevant implementations."""
+
+ def __init__(
+ self,
+ defs: Optional[set[str]] = None,
+ lcls: Optional[dict[str, Any]] = None,
+ ) -> None:
+ if lcls is None:
+ lcls = globals()
+ if defs is None:
+ defs = set(lcls.keys())
+
+ self.lcls = lcls
+ self.defs = defs
+ self._result = MarimoPytestResult()
+
+ def pytest_collection_modifyitems(self, items: list[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.
+ """
+ # Not official marimo dependencies
+ # So don't import at the top level.
+ import _pytest # type: ignore
+
+ to_collect = []
+ # Filter tests, and create new "Functions" with the relevant references
+ # where needed.
+ for i, item in enumerate(items):
+ head: Any = item
+ path: list[str] = []
+
+ while isinstance(head.parent.parent, _pytest.python.Class):
+ 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:
+ obj: Any = self.lcls[name]
+ for attr in reversed(path):
+ if isinstance(obj, type):
+ obj = obj()
+ obj = getattr(obj, attr)
+ to_collect.append(_sub_function(items[i], parent, obj))
+ items[:] = to_collect
+
+ def pytest_terminal_summary(self, terminalreporter: Any) -> None:
+ """Provide a clean summary of test results. Gives something like:
+ =========== Overview ===========
+ Passed Tests:
+ ✓ testing.py::test_sanity
+ ✓ testing.py::test_parameterized_collected[3-4]
+ ✓ testing.py::test_parameterized_collected[4-5]
+ ✓ testing.py::TestWhatever::test_class_def
+
+ Summary:
+ Total: 9, Passed: 4, Failed: 4, Errors: 0, Skipped: 1
+ """
+
+ tr: Any = terminalreporter
+ tr.write_sep("=", "Overview")
+ stats: dict[str, Any] = tr.stats
+
+ # Failures and non passes are shown in summary.
+ # Display successes here manually since -v is a little too noisy.
+ if "passed" in stats:
+ tr.write_line("Passed Tests:")
+ for rep in stats["passed"]:
+ tr.write_line(f"{bold(green('✓'))} {rep.nodeid}")
+
+ tr.write_line("\nSummary:")
+ passed: int = len(stats.get("passed", []))
+ failed: int = len(stats.get("failed", []))
+ skipped: int = len(stats.get("skipped", []))
+ errors: int = len(stats.get("error", []))
+ self._result = MarimoPytestResult(
+ passed=passed, failed=failed, errors=errors, skipped=skipped
+ )
+
+ tr.write_line(self._result.summary)
+
+ def pytest_runtest_logreport(
+ self, report: _pytest.reports.TestReport
+ ) -> None:
+ """In place updates the report for some better formatting.
+ In particular:
+ - removes stub class reference for scoped tests
+ - removes extra frame from parameter workaround
+ - fixes test name/ paths to be more consistent with expectation
+ """
+ report.nodeid = MARIMO_TEST_BLOCK_REGEX.sub("", report.nodeid)
+ if report.location is not None:
+ fspath, lineno, domain = report.location
+ report.location = (
+ fspath,
+ lineno,
+ MARIMO_TEST_BLOCK_REGEX.sub("", domain),
+ )
+ if report.longrepr:
+ if isinstance(report.longrepr, tuple):
+ _, lineno, msg = report.longrepr
+ report.longrepr = (report.nodeid, lineno, f"({msg})")
+ elif not isinstance(report.longrepr, str):
+ longrepr = str(report.longrepr)
+ if "func_JYWB" in longrepr:
+ # Strip the first call of traceback
+ report.longrepr.reprtraceback.reprentries = (
+ report.longrepr.reprtraceback.reprentries[1:]
+ )
+ for entry in report.longrepr.reprtraceback.reprentries:
+ entry.reprfileloc.path = _to_marimo_uri(
+ entry.reprfileloc.path
+ )
+
+
+def run_pytest(
+ defs: set[str] | None = None,
+ lcls: dict[str, Any] | None = None,
+ notebook_path: Path | str | None = None,
+) -> MarimoPytestResult:
+ import pytest # type: ignore
+
+ if not notebook_path:
+ # Translate name to python module
+ notebook_path = os.path.relpath(
+ _maybe_name(), marimo.notebook_location()
+ )
+ notebook_path = str(notebook_path)
+ # So path/to/notebook.py -> path.to.notebook
+ # but windows compat
+ notebook = (
+ notebook_path.replace(os.sep, ".").strip(".py").strip(".md")
+ ).strip(".")
+
+ if notebook in sys.modules:
+ del sys.modules[notebook]
+
+ # qq and disable warnings suppress a fair bit of filler noise.
+ # color=yes seems to work nicely, but code-highlight is a bit much.
+ plugin = ReplaceStubPlugin(defs, lcls)
+ with capture_stdout() as stdout:
+ pytest.main(
+ [
+ "-qq",
+ "--disable-warnings",
+ "--color=yes",
+ "--code-highlight=no",
+ notebook_path,
+ ],
+ plugins=[plugin],
+ )
+
+ plugin._result.output = stdout.getvalue()
+ return plugin._result
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index 45773fcb23..c1f592719e 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import sys
from typing import Callable
from marimo import _loggers
@@ -339,6 +340,26 @@ def _broadcast_outputs(
)
+@kernel_tracer.start_as_current_span("run_pytest")
+def _attempt_pytest(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+) -> None:
+ del run_result
+ if cell._test:
+ try:
+ import marimo._runtime.pytest as marimo_pytest
+
+ if runner.execution_context is not None:
+ with runner.execution_context(cell.cell_id):
+ result = marimo_pytest.run_pytest(cell.defs, runner.glbls)
+ if result.output:
+ sys.stdout.write(result.output)
+ except ImportError:
+ pass
+
+
@kernel_tracer.start_as_current_span("reset_matplotlib_context")
def _reset_matplotlib_context(
cell: CellImpl,
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index fab00a03f6..f873aeeeb4 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -474,6 +474,14 @@ class Kernel:
on_finish_hooks if on_finish_hooks is not None else ON_FINISH_HOOKS
)
+ # Adds in a post_execution hook to run pytest immediately
+ if user_config.get("experimental", {}).get("reactive_pytest", False):
+ from marimo._runtime.runner.hooks_post_execution import (
+ _attempt_pytest,
+ )
+
+ self._post_execution_hooks.append(_attempt_pytest)
+
self._globals_lock = threading.RLock()
self._completion_worker_started = False
diff --git a/marimo/_smoke_tests/reactive_pytest.py b/marimo/_smoke_tests/reactive_pytest.py
new file mode 100644
index 0000000000..be26f83f23
--- /dev/null
+++ b/marimo/_smoke_tests/reactive_pytest.py
@@ -0,0 +1,103 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "pytest",
+# "marimo",
+# ]
+# ///
+# Copyright 2025 Marimo. All rights reserved.
+
+import marimo
+
+__generated_with = "0.11.10"
+app = marimo.App()
+
+
+def _():
+ def inc(x):
+ return x + 1
+ return (inc,)
+
+
+def test_answer(inc):
+ assert inc(3) == 5, "This test fails"
+ return
+
+
+def test_sanity(inc):
+ assert inc(3) == 4, "This test passes"
+ return
+
+
+def _(inc, pytest):
+ @pytest.mark.parametrize("x, y", [(3, 4), (4, 5)])
+ def test_parameterized(x, y):
+ assert inc(x) == y, "These tests should pass."
+ return (test_parameterized,)
+
+
+def _():
+ def cross_cell_fail():
+ assert False
+ return (cross_cell_fail,)
+
+
+def _(cross_cell_fail, inc, pytest):
+ @pytest.mark.parametrize("x, y", [(3, 4), (4, 5)])
+ def test_parameterized_collected(x, y):
+ assert inc(x) == y, "These tests should pass."
+
+ @pytest.mark.parametrize("x, y", [(3, 4), (4, 5)])
+ def test_parameterized_collected2(x, y):
+ assert inc(x) == y, "These tests should pass."
+
+ @pytest.mark.skip(reason="Skip for fun")
+ def test_normal_regular():
+ assert True
+
+ def test_transitive_uri():
+ cross_cell_fail()
+
+
+ class TestParent():
+ def test_parent_inner(self):
+ assert True
+ class TestChild():
+ def test_inner(self):
+ assert True
+ return (
+ TestParent,
+ test_normal_regular,
+ test_parameterized_collected,
+ test_parameterized_collected2,
+ test_transitive_uri,
+ )
+
+
+def _():
+ def test_sanity():
+ assert True
+
+ def test_orwell():
+ a = 2
+ b = 5
+ assert a + a == b
+ return test_orwell, test_sanity
+
+
+def imports():
+ import pytest
+ import marimo as mo
+ return mo, pytest
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_runtime/script_data/contains_tests.py b/tests/_runtime/script_data/contains_tests.py
new file mode 100644
index 0000000000..899a9ab96f
--- /dev/null
+++ b/tests/_runtime/script_data/contains_tests.py
@@ -0,0 +1,82 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "pytest",
+# "marimo",
+# ]
+# ///
+# Copyright 2025 Marimo. All rights reserved.
+
+import marimo
+
+__generated_with = "0.11.10"
+app = marimo.App()
+
+
+# None of these should fail
+
+
+def _():
+ def inc(x):
+ return x + 1
+
+ return (inc,)
+
+
+def _(inc, pytest):
+ @pytest.mark.parametrize("x, y", [(3, 4), (4, 5), (0, 1)])
+ def test_parameterized(x, y):
+ assert inc(x) == y, "These tests should pass."
+
+ return (test_parameterized,)
+
+
+def _(inc, pytest):
+ @pytest.mark.parametrize("x, y", [(3, 4), (4, 5)])
+ def test_parameterized_collected(x, y):
+ assert inc(x) == y, "These tests should pass."
+
+ @pytest.mark.parametrize("x, y", [(3, 4), (4, 5)])
+ def test_parameterized_collected2(x, y):
+ assert inc(x) == y, "These tests should pass."
+
+ @pytest.mark.skip(reason="Skip for fun")
+ def test_normal_regular():
+ assert True
+
+ class TestParent:
+ def test_parent_inner(self):
+ assert True
+
+ class TestChild:
+ def test_inner(self):
+ assert True
+
+ return (
+ TestParent,
+ test_normal_regular,
+ test_parameterized_collected,
+ test_parameterized_collected2,
+ )
+
+
+def _():
+ def test_sanity():
+ assert True
+
+
+def imports():
+ import pytest
+
+ import marimo as mo
+
+ return mo, pytest
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_runtime/test_pytest_runtime.py b/tests/_runtime/test_pytest_runtime.py
new file mode 100644
index 0000000000..62afca102d
--- /dev/null
+++ b/tests/_runtime/test_pytest_runtime.py
@@ -0,0 +1,46 @@
+import os
+from pathlib import Path
+
+from marimo._runtime.pytest import run_pytest
+
+pytest_plugins = ["pytester"]
+
+
+def test_smoke_test():
+ from tests._runtime.script_data.contains_tests import app
+
+ _, lcls = app.run()
+ lcls = dict(lcls)
+
+ def_count = {
+ "test_parameterized": 3,
+ "test_parameterized_collected": 2,
+ "test_parameterized_collected2": 2,
+ "test_normal_regular": 1,
+ "TestParent": 2,
+ "test_sanity": 1,
+ }
+
+ path = Path(__file__).parent / "script_data/contains_tests.py"
+
+ # Turn off for recursion guard
+ previous = os.environ.get("PYTEST_CURRENT_TEST", "")
+ os.environ["PYTEST_CURRENT_TEST"] = ""
+ del os.environ["PYTEST_CURRENT_TEST"]
+
+ # sanity check for run
+ total = 0
+ for cell in app._cell_manager.cells():
+ if cell.__test__:
+ response = run_pytest(
+ defs=cell.defs, lcls=lcls, notebook_path=path
+ )
+ assert response.total == sum([def_count[d] for d in cell.defs]), (
+ response.output
+ )
+ total += response.total
+
+ os.environ["PYTEST_CURRENT_TEST"] = previous
+ # put it back on
+
+ assert total == sum(def_count.values()) == 11
diff --git a/tests/conftest.py b/tests/conftest.py
index 35cc7720d7..b6834c6d4c 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -634,7 +634,7 @@ def pytest_make_collect_report(collector):
# Defined within the file does not seem to hook correctly, as such filter
# for the test_pytest specific file here.
- if "test_pytest" in str(collector.path):
+ if "test_pytest" in str(collector.path) and "_ast" in str(collector.path):
# Classes may also be registered, but they will be hidden behind a cell.
# As such, let's just collect functions.
collected = {