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: pytest bugs from user feedback (#4206)

Dylan Madisetti65da5a9b231a
diff --git a/marimo/_ast/pytest.py b/marimo/_ast/pytest.py
index d82bad1153..000b094a5b 100644
--- a/marimo/_ast/pytest.py
+++ b/marimo/_ast/pytest.py
@@ -10,6 +10,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, NoReturn, TypeVar, cast
from marimo._ast.cell import Cell
+from marimo._runtime.context import ContextNotInitializedError, get_context
if TYPE_CHECKING:
from collections.abc import Awaitable, Mapping
@@ -186,15 +187,28 @@ def build_test_class(
functools.wraps(stub_fn)(_hook)
# Evaluate and run decorators.
local = {}
+ # Always expose pytest. Low hanging fruit, that should mitigate some
+ # user issues.
try:
import pytest # type: ignore
- # TODO: Remove import pytest with top level functions
- # Just a hack for now.
- local = {"pytest": pytest}
+ local["pytest"] = pytest
except ImportError:
pass
+ # If called from the runtime, we can populate the locals
+ try:
+ local.update(get_context().globals)
+ except ContextNotInitializedError:
+ # If not in runtime, we are running directly as a script. As
+ # such, we need the values from the module frame.
+ # Traverse frame upwards until we match the file.
+ frames = inspect.stack()
+ for frame in frames:
+ if Path(frame.filename).resolve() == Path(file).resolve():
+ local.update(frame.frame.f_locals)
+ break
+
try:
for decorator in test.decorator_list[::-1]:
expr = ast.Expression(decorator)
@@ -208,12 +222,12 @@ def build_test_class(
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."
+ f"Failed to evaluate signature/decorator for {var} "
+ "during test collection. Consider exposing relevant "
+ "variables in the setup block, or rewriting your "
+ "tests to avoid runtime dependencies."
) from e
- functools.wraps(stub_fn)(fails)
return fails
return _hook
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 7a73e8e9aa..825cdd1e47 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -191,6 +191,7 @@ class DependencyManager:
panel = Dependency("panel")
sqlalchemy = Dependency("sqlalchemy")
pylsp = Dependency("pylsp")
+ pytest = Dependency("pytest")
vegafusion = Dependency("vegafusion")
vl_convert_python = Dependency("vl_convert")
diff --git a/marimo/_runtime/pytest.py b/marimo/_runtime/pytest.py
index c58e53c9e8..0d1bdf852e 100644
--- a/marimo/_runtime/pytest.py
+++ b/marimo/_runtime/pytest.py
@@ -10,6 +10,7 @@ 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._dependencies.dependencies import DependencyManager
from marimo._runtime.capture import capture_stdout
from marimo._runtime.context import ContextNotInitializedError, get_context
@@ -19,7 +20,7 @@ MARIMO_TEST_BLOCK_REGEX = re.compile(rf"{MARIMO_TEST_STUB_NAME}_\d+[(?::)\.]+")
if TYPE_CHECKING:
from pathlib import Path
- import _pytest # type: ignore
+ import _pytest.Item # type: ignore
@dataclass
@@ -209,21 +210,24 @@ class ReplaceStubPlugin:
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
- )
+ # Signature from pytest for longrepr is:
+ # None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr
+ if not report.longrepr or isinstance(report.longrepr, str):
+ return
+
+ if isinstance(report.longrepr, tuple):
+ _, lineno, msg = report.longrepr
+ report.longrepr = (report.nodeid, lineno, f"({msg})")
+ # Not all TerminalRepr seem to have a reprtraceback
+ elif hasattr(report.longrepr, "reprtraceback"):
+ 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(
@@ -231,37 +235,57 @@ def run_pytest(
lcls: dict[str, Any] | None = None,
notebook_path: Path | 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.
+ 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
if not notebook_path:
# Translate name to python module
- notebook_path = os.path.relpath(
- _maybe_name(), marimo.notebook_location()
- )
+ notebook_path = _maybe_name()
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]
+ # Hold on to modules since we want to refresh them in order to enable
+ # repeated calls.
+ module_snapshot = dict(sys.modules)
+ # Paths may be altered by pytest. To prevent accumulation- we refresh the
+ # path to the original state.
+ # NB. refer to pytester the most native solution (not used here, since it
+ # seems reasonable to just hook in this way).
+ path_snapshot = sys.path.copy()
# qq and disable warnings suppress a fair bit of filler noise.
# color=yes seems to work nicely, but code-highlight is a bit much.
+ # 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)
- with capture_stdout() as stdout:
- pytest.main(
- [
- "-qq",
- "--disable-warnings",
- "--color=yes",
- "--code-highlight=no",
- notebook_path,
- ],
- plugins=[plugin],
- )
+ try:
+ with capture_stdout() as stdout:
+ pytest.main(
+ [
+ "-qq",
+ "--disable-warnings",
+ "--color=yes",
+ "--code-highlight=no",
+ notebook_path,
+ ],
+ plugins=[plugin],
+ )
+ finally:
+ # Note, in pytester, there are also exceptions for zope and readline.
+ # However, those deps should already be in module_snapshot, since
+ # dependencies are required before the given cell runs.
+ sys.modules.clear()
+ sys.modules.update(module_snapshot)
+ sys.path[:] = path_snapshot
plugin._result.output = stdout.getvalue()
return plugin._result
diff --git a/tests/_ast/test_pytest_scoped.py b/tests/_ast/test_pytest_scoped.py
new file mode 100644
index 0000000000..687188764b
--- /dev/null
+++ b/tests/_ast/test_pytest_scoped.py
@@ -0,0 +1,23 @@
+import marimo
+
+__generated_with = "0.11.25"
+app = marimo.App(width="medium")
+
+
+with app.setup:
+ import pytest
+
+ test_cases = [(1, 2), (1, 3), (1, 5)]
+
+
+def _(test_cases):
+ @pytest.mark.parametrize(("a", "b"), test_cases)
+ def test_function(a, b):
+ assert a < b
+
+ return (test_function,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_runtime/script_data/contains_tests.py b/tests/_runtime/script_data/contains_tests.py
index 899a9ab96f..ea89941252 100644
--- a/tests/_runtime/script_data/contains_tests.py
+++ b/tests/_runtime/script_data/contains_tests.py
@@ -13,40 +13,29 @@ __generated_with = "0.11.10"
app = marimo.App()
-# None of these should fail
-
+with app.setup:
+ import pytest
-def _():
- def inc(x):
- return x + 1
+ test_cases = [(1, 2), (1, 3), (1, 5)]
- return (inc,)
+def inc(x):
+ return x + 1
-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,)
[email protected](("x", "y"), [(3, 4), (4, 5), (0, 1)])
+def test_parameterized(x, y):
+ assert inc(x) == y, "These tests should pass."
@app.cell
-def _(inc, pytest):
- @pytest.mark.parametrize("x, y", [(3, 4), (4, 5)])
+def _(inc):
+ @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
@@ -57,9 +46,7 @@ def _(inc, pytest):
return (
TestParent,
- test_normal_regular,
test_parameterized_collected,
- test_parameterized_collected2,
)
@@ -68,14 +55,25 @@ def _():
def test_sanity():
assert True
+ def test_failure():
+ pytest.fail("Ensure a failure is captured.")
+
+ @pytest.mark.skip(reason="Ensure a skip is captured.")
+ def test_skip():
+ assert True
+
@app.cell
-def imports():
- import pytest
+def _():
+ @pytest.mark.parametrize(("a", "b"), test_cases)
+ def test_using_var_in_scope(a, b):
+ assert a < b
- import marimo as mo
- return mo, pytest
[email protected](("a", "b"), test_cases)
+def test_using_var_in_toplevel(a, b):
+ assert a < b
if __name__ == "__main__":
diff --git a/tests/_runtime/test_pytest_runtime.py b/tests/_runtime/test_pytest_runtime.py
index 62afca102d..eddeba2108 100644
--- a/tests/_runtime/test_pytest_runtime.py
+++ b/tests/_runtime/test_pytest_runtime.py
@@ -13,12 +13,14 @@ def test_smoke_test():
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,
+ "TestParent": (2, 0, 0),
+ "test_failure": (0, 0, 1),
+ "test_parameterized": (3, 0, 0),
+ "test_parameterized_collected": (2, 0, 0),
+ "test_sanity": (1, 0, 0),
+ "test_skip": (0, 1, 0),
+ "test_using_var_in_scope": (3, 0, 0),
+ "test_using_var_in_toplevel": (3, 0, 0),
}
path = Path(__file__).parent / "script_data/contains_tests.py"
@@ -35,7 +37,11 @@ def test_smoke_test():
response = run_pytest(
defs=cell.defs, lcls=lcls, notebook_path=path
)
- assert response.total == sum([def_count[d] for d in cell.defs]), (
+ assert (
+ response.passed,
+ response.skipped,
+ response.failed,
+ ) == tuple(map(sum, zip(*[def_count[d] for d in cell.defs]))), (
response.output
)
total += response.total
@@ -43,4 +49,5 @@ def test_smoke_test():
os.environ["PYTEST_CURRENT_TEST"] = previous
# put it back on
- assert total == sum(def_count.values()) == 11
+ # Assert all cases captured, and nothing missed.
+ assert total == sum(map(sum, def_count.values())) == 16
diff --git a/tests/conftest.py b/tests/conftest.py
index 57dcc2ca20..42ccd62f51 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -652,11 +652,13 @@ def pytest_make_collect_report(collector):
if isinstance(cls, pytest.Class)
}
from tests._ast.test_pytest import app as app_pytest
+ from tests._ast.test_pytest_scoped import app as app_scoped
from tests._ast.test_pytest_toplevel import app as app_toplevel
app = {
"test_pytest": app_pytest,
"test_pytest_toplevel": app_toplevel,
+ "test_pytest_scoped": app_scoped,
}[collector.path.stem]
# Just a quick check to make sure the class is actually exported.