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
feat: koaning/motest parity (pytest in blocks) (#3892)
Dylan Madisettiec1feb884801
diff --git a/docs/guides/testing/pytest.md b/docs/guides/testing/pytest.mdindex 51d20da7c2..ced76e5a42 100644--- a/docs/guides/testing/pytest.md+++ b/docs/guides/testing/pytest.md@@ -12,7 +12,8 @@ For example,pytest test_notebook.py```-runs and tests all notebook cells whose names start with `test_`.+runs and tests all notebook cells whose names start with `test_`, or cells that+contain only `test_` functions and `Test` classes.!!! tip "Naming cells"@@ -42,37 +43,52 @@ app = marimo.App()def _():def inc(x):return x + 1- return inc+ return (inc,)@app.cell-def test_answer(inc):+def test_fails(inc):assert inc(3) == 5, "This test fails"@app.celldef test_sanity(inc):assert inc(3) == 4, "This test passes"++def collection_of_tests(inc, pytest):+ @pytest.mark.parametrize("input, expected", [(3, 4), (4, 5)])+ def test_answer(x, y):+ assert inc(x) == y, "These tests should pass."++def imports():+ import pytest+ return pytest```prints```pytest============================= test session starts ==============================-platform linux -- Python 3.11.10, pytest-8.3.3, pluggy-1.5.0+platform linux -- Python 3.11.10, pytest-8.3.4, pluggy-1.5.0rootdir: /notebooksconfigfile: pyproject.toml-collected 2 items+collected 4 items-test_notebook.py F. [100%]+test_notebook.py::test_fails FAILED [ 25%]+test_notebook.py::test_sanity PASSED [ 50%]+test_notebook.py::MarimoTestBlock_0::test_parameterized[3-4] PASSED [ 75%]+test_notebook.py::MarimoTestBlock_0::test_parameterized[4-5] PASSED [100%]=================================== FAILURES ===================================__________________________________ test_fails __________________________________+ # content of test_notebook.pyimport marimo__generated_with = "0.10.6"- app = marimo.App(width="medium")+ app = marimo.App()@app.cell@@ -83,12 +99,16 @@ __________________________________ test_fails __________________________________@app.cell- def test_answser(inc):+ def test_fails(inc):> assert inc(3) == 5, "This test fails"E AssertionError: This test fails+E assert 4 == 5+E + where 4 = <function inc>(3)-test_notebook.py:16: AssertionError+test_notebook.py:17: AssertionError=========================== short test summary info ============================FAILED test_notebook.py::test_fails - AssertionError: This test fails-========================= 1 failed, 1 passed in 0.20s ===========================+assert 4 == 5+ + where 4 = <function inc>(3)+========================= 1 failed, 3 passed in 0.65s ==========================```diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex a97ba2977f..266b4cf8c4 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -414,6 +414,12 @@ 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+@propertydef name(self) -> str:return self._name@@ -482,6 +488,10 @@ class Cell:""")+ @property+ def __test__(self) -> bool:+ return self._test+def _register_app(self, app: InternalApp) -> None:self._app = app@@ -601,7 +611,7 @@ class Cell:raise e.__cause__ from None # type: ignoredef __call__(self, *args: Any, **kwargs: Any) -> Any:- # TODO: Expand for top level modules when/ if the time comes.+ # TODO: Expand for toplevel modules when the time comes.arg_names = sorted(self._cell.refs - set(globals()["__builtins__"].keys()))diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.pyindex ad0edbb5d0..b0d5bc58ce 100644--- a/marimo/_ast/cell_manager.py+++ b/marimo/_ast/cell_manager.py@@ -1,7 +1,6 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import functoolsimport osimport randomimport string@@ -23,7 +22,7 @@ from marimo._ast.cell import Cell, CellConfigfrom marimo._ast.compiler import cell_factory, toplevel_cell_factoryfrom marimo._ast.models import CellDatafrom marimo._ast.names import DEFAULT_CELL_NAME-from marimo._ast.pytest import wrap_fn_for_pytest+from marimo._ast.pytest import process_for_pytestfrom marimo._types.ids import CellId_tif TYPE_CHECKING:@@ -120,7 +119,7 @@ class CellManager:# Manually set the signature for pytest.if is_top_level_pytest:# NB. in place metadata update.- functools.wraps(wrap_fn_for_pytest(func, cell))(cell)+ process_for_pytest(func, cell)return cellif func is None:diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex 8fe6ee996c..0e77cc7e5d 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -70,6 +70,20 @@ def ends_with_semicolon(code: str) -> bool:return False+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:+ if not isinstance(+ node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)+ ):+ return False+ if not node.name.lower().startswith("test"):+ return False+ return True++def cache(filename: str, code: str) -> None:# Generate a cache entry in Python's linecachelinecache.cache[filename] = (@@ -317,6 +331,7 @@ def toplevel_cell_factory(source_position=source_position,test_rewrite=test_rewrite,),+ _test=f.__name__.startswith("test_"),)@@ -449,4 +464,5 @@ def cell_factory(source_position=source_position,test_rewrite=test_rewrite,),+ _test=f.__name__.startswith("test_") or contains_only_tests(tree),)diff --git a/marimo/_ast/pytest.py b/marimo/_ast/pytest.pyindex 2aee4f47a5..4d3c65c5c2 100644--- a/marimo/_ast/pytest.py+++ b/marimo/_ast/pytest.py@@ -1,20 +1,39 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import astimport copy+import functoolsimport inspect-from typing import Any, Callable, TypeVar, cast+import itertools+from pathlib import Path+from typing import Any, Awaitable, Callable, Mapping, NoReturn, TypeVar, castfrom marimo._ast.cell import CellFn = TypeVar("Fn", bound=Callable[..., Any])+block_incrementer = itertools.count()+++class MarimoTest:+ """Base class for Marimo tests."""++ __test__ = True++# Python definition used as the ast bones for constructing a pytest function.def _pytest_scaffold(stub: Any) -> Any:return stub(stub=stub)-def wrap_fn_for_pytest(func: Fn, cell: Cell) -> Callable[..., Any]:+def build_stub_fn(+ func_body: ast.FunctionDef | ast.AsyncFunctionDef,+ file: str = "",+ basis: None | Callable[..., Any] = None,+ allowed: None | list[str] = None,+) -> Callable[..., Any]:# Avoid declaring the function in the global scope, since it may cause# issues with meta-analysis tools like cxfreeze (see #3828).PYTEST_BASE = ast.parse(inspect.getsource(_pytest_scaffold))@@ -22,14 +41,10 @@ def wrap_fn_for_pytest(func: Fn, cell: Cell) -> Callable[..., Any]:# We modify the signature of the cell function such that pytest# does not attempt to use the arguments as fixtures.- func_ast = ast.parse(inspect.getsource(func))- func_body = func_ast.body[0]- assert isinstance(func_body, (ast.FunctionDef, ast.AsyncFunctionDef))-args = {arg.arg: arg for arg in func_body.args.args}- fixtures = [arg for arg in args.keys() if arg.endswith("_fixture")]- reserved = set(args.keys()) - set(fixtures)- name = func.__name__+ if allowed is None:+ allowed = [arg for arg in args.keys() if arg != "self"]+ name = func_body.name# Typing checks for mypyfn = copy.deepcopy(PYTEST_BASE)@@ -51,7 +66,7 @@ def wrap_fn_for_pytest(func: Fn, cell: Cell) -> Callable[..., Any]:# Which is sufficient to fool pytest.body.args.args[:] = [ast.arg(arg, lineno=args[arg].lineno, col_offset=args[arg].col_offset)- for arg in fixtures+ for arg in allowed](_call_stub,) = call.keywordscall.keywords = [@@ -66,16 +81,202 @@ def wrap_fn_for_pytest(func: Fn, cell: Cell) -> Callable[..., Any]:lineno=args[arg].lineno,col_offset=args[arg].col_offset,)- for arg in fixtures+ for arg in allowed]body.name = name- local = {"stub": cell.__call__, "Any": Any}- eval(compile(fn, inspect.getfile(func), "exec"), local)+ local = {"stub": basis, "Any": Any}+ eval(compile(fn, file, "exec"), local)++ response = cast(Callable[..., Any], local[name])+ assert callable(response)+ return response+++def wrap_fn_for_pytest(func: Fn, cell: Cell) -> Callable[..., Any]:+ func_ast = ast.parse(inspect.getsource(func))+ func_body = func_ast.body[0]+ assert isinstance(func_body, (ast.FunctionDef, ast.AsyncFunctionDef))+ args = {arg.arg: arg for arg in func_body.args.args}+ fixtures = [arg for arg in args.keys() if arg.endswith("_fixture")]+ reserved = set(args.keys()) - set(fixtures)# The remaining expected attributes are needed to ensure attribute count# matches.cell._pytest_reserved = reserved- response = cast(Callable[..., Any], local[name])- assert callable(response)- return response+ return build_stub_fn(+ func_body, inspect.getfile(func), cell.__call__, fixtures+ )+++def build_test_class(+ body: list[ast.stmt],+ run: Callable[+ [],+ tuple[Any, Mapping[str, Any]]+ | Awaitable[tuple[Any, Mapping[str, Any]]],+ ],+ file: str,+ name: str,+ defs: set[str],+ inner: bool = False,+) -> type[MarimoTest]:+ """+ Build a test class from the body of a cell.++ @app.cell+ def _(many, potential, deps):+ def test_one_of_many_tests_in_a_given_cell():+ assert True++ class TestSubclass:+ def test_subclass_method_works(self):+ assert True++ ->++ class MarimoTestBlock_idx(MarimoTest):+ @staticmethod+ def test_one_of_many_tests_in_a_given_cell():+ ...+ class TestSubclass(MarimoTest):+ def test_subclass_method_works(self):+ assert True++ Note that each test is resolved symbolically such that breaking test+ definitions do not change the suite definition/ stop the entire suite from+ running. Relatively marginal overhead.+ """+ tests = {}+ for node in body:+ assert isinstance(+ node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)+ ), (+ "Invalid test compilation. "+ " Please report to marimo-team/marimo/issues."+ )+ tests[node.name] = node++ def hook(var: str) -> Callable[..., Any] | type[MarimoTest]:+ def _hook(*args: Any, **kwargs: Any) -> Any:+ _, defs = run() # type: ignore+ return defs[var](*args, **kwargs)++ test = tests.get(var, None)+ if test is None:++ def fails(*args: Any, **kwargs: Any) -> NoReturn:+ del args, kwargs+ raise ValueError(+ (+ f"Could not find test {var}, please report to"+ "marimo-team/marimo/issues."+ )+ )++ return fails++ if isinstance(test, (ast.FunctionDef, ast.AsyncFunctionDef)):+ stub_fn = build_stub_fn(test, file)+ functools.wraps(stub_fn)(_hook)+ # Evaluate and run decorators.+ local = {}+ try:+ import pytest # type: ignore++ # TODO: Remove import pytest with top level functions+ # Just a hack for now.+ local = {"pytest": pytest}+ except ImportError:+ pass++ try:+ for decorator in test.decorator_list[::-1]:+ expr = ast.Expression(decorator)+ _hook = eval(compile(expr, file, "eval"), local)(_hook)+ if not inner:+ _hook = staticmethod(_hook)+ except Exception as _e:+ # Python restricts scope of exceptions artificially.+ e = copy.copy(_e)++ def fails(*args: Any, **kwargs: Any) -> NoReturn:+ del args, kwargs+ raise ValueError(+ (+ f"Failed to evaluate decorator for {var}."+ "Consider adjusting the test to enable "+ "static analysis."+ )+ ) from e++ functools.wraps(stub_fn)(fails)+ return fails++ return _hook+ elif isinstance(test, ast.ClassDef):+ defs = {+ node.name+ for node in test.body+ if isinstance(+ node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)+ )+ and node.name.lower().startswith("test")+ }++ def _run() -> tuple[Any, Any]:+ old_output, old_defs = run() # type: ignore+ old_defs = dict(old_defs)+ for d in defs:+ old_defs[d] = getattr(old_defs[var], d)+ return old_output, old_defs++ return build_test_class(test.body, _run, file, var, defs, True)+ raise ValueError(+ (+ "Improperly compiled as a test. Please report to"+ "marimo-team/marimo/issues."+ )+ )++ return type(name, (MarimoTest,), {var: hook(var) for var in defs})+++def process_for_pytest(func: Fn, cell: Cell) -> None:+ # Check if it is considered a __test__ cell.+ if not cell.__test__:+ return++ # If this is declared as a test on the top level, leave it alone.+ if cell.name.startswith("test_"):+ # Set the correct signature for the function.+ functools.wraps(wrap_fn_for_pytest(func, cell))(cell)+ return++ # Turn off test for the cell itself in this case.+ cell._test = 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)}"++ scope = tree.body[0]+ assert isinstance(+ scope, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)+ )+ cls = build_test_class(+ scope.body, run, inspect.getfile(func), name, cell.defs+ )+ # Get first frame not in library to insert the class.+ # May be multiple levels if called from pytest or something.+ frames = inspect.stack()++ # ensure marimo/_ not in frame path, using this file as a reference.+ library = Path(__file__).parent.parent+ for frame in frames:+ if library not in Path(frame.filename).parents:+ # Insert the class into the frame.+ frame.frame.f_locals[cls.__name__] = cls+ breakdiff --git a/tests/_ast/test_pytest.py b/tests/_ast/test_pytest.pyindex 68499401ec..89d3c7a84b 100644--- a/tests/_ast/test_pytest.py+++ b/tests/_ast/test_pytest.py@@ -7,6 +7,48 @@ import marimoapp = marimo.App()+async def _(pytest, x, y, Z):+ @pytest.mark.xfail(+ reason=("To ensure this doesn't just eval."),+ raises=AssertionError,+ strict=True,+ )+ def test_independence():+ assert x + y == 0++ def test_another_dependent_cell():+ assert x + y == Z++ class TestClass:+ @pytest.mark.xfail(+ reason=("To ensure this doesn't just eval."),+ raises=AssertionError,+ strict=True,+ )+ def test_method(self):+ assert x + y == 0++ @staticmethod+ @pytest.mark.xfail(+ reason=("To ensure this doesn't just eval."),+ raises=AssertionError,+ strict=True,+ )+ def test_static_method() -> None:+ assert x + y == 0++ def test_normal(self):+ assert x + y == Z++ @staticmethod+ def test_static() -> None:+ assert x + y == Z++ async def test_async_cell():+ assert True++@app.celldef imports():import marimo as mo@@ -14,7 +56,9 @@ def imports():# Suffixed with _fixture should have corresponding definitions in conftest.pymo_fixture = None- return mo, mo_fixture+ import pytest++ return mo, mo_fixture, pytest@app.cell@@ -99,9 +143,7 @@ def test_cell_args_resolved_by_name(mo): # noqa: ARG001@app.cell-def test_cell_assert_rewritten():- import pytest-+def test_cell_assert_rewritten(pytest):a = 1b = 2@@ -111,3 +153,11 @@ def test_cell_assert_rewritten():# Check expansion works. Without rewrite, this just produces# "AssertionError", without showing the expanded expression.assert "assert (1 + 2) == (1 * 2)" in str(exc_info.value)+++def cell_with_multiple_deps():+ x = 1+ y = 2+ Z = 3+ return x, y, Zdiff --git a/tests/conftest.py b/tests/conftest.pyindex c293d4c38f..c6f7d9f1df 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -627,10 +627,25 @@ def app() -> Generator[App, None, None]:@pytest.hookimpldef pytest_make_collect_report(collector):report = runner.pytest_make_collect_report(collector)+ # If it's not a module, we can return early.+ if not isinstance(collector, pytest.Module):+ return report+# 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):- collected = {fn.originalname for fn in collector.collect()}+ # Classes may also be registered, but they will be hidden behind a cell.+ # As such, let's just collect functions.+ collected = {+ fn.originalname+ for fn in collector.collect()+ if isinstance(fn, pytest.Function)+ }+ classes = {+ cls.name+ for cls in collector.collect()+ if isinstance(cls, pytest.Class)+ }from tests._ast.test_pytest import app as app_pytestfrom tests._ast.test_pytest_toplevel import app as app_toplevel@@ -639,6 +654,21 @@ def pytest_make_collect_report(collector):"test_pytest_toplevel": app_toplevel,}[collector.path.stem]+ # Just a quick check to make sure the class is actually exported.+ if app == app_pytest:+ if len(classes) == 0:+ report.outcome = "failed"+ report.longrepr = (+ f"Expected class in {collector.path}, found none."+ )+ return report+ for cls in classes:+ if not cls.startswith("MarimoTestBlock"):+ report.outcome = "failed"+ report.longrepr = f"Unknown class '{cls}' in {collector.path}"+ return report++ # Check the functions match cells in the app.invalid = []for name in app._cell_manager.names():if name.startswith("test_") and name not in collected: