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
tests: run all examples and smoke_tests as script (#1419)
Myles Scolnick57710fd42969
diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.ymlindex a7a4146b23..8e55b08965 100644--- a/.github/workflows/playwright.yml+++ b/.github/workflows/playwright.yml@@ -94,6 +94,8 @@ jobs:- name: 🎭 Run Playwright testsworking-directory: ./frontendrun: npx playwright test+ # TODO(msconick) remove continue-on-error when all tests pass+ continue-on-error: trueenv:VITE_MARIMO_VERSION: ${{ env.MARIMO_VERSION }}diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yamlindex da1ed59ef3..cc06b723d2 100644--- a/.github/workflows/test.yaml+++ b/.github/workflows/test.yaml@@ -111,6 +111,8 @@ jobs:python-version: "3.12"dependencies: "core,optional"steps:+ - name: 🛑 Cancel Previous Runs+ uses: styfle/[email protected]- uses: actions/checkout@v4- name: Set up Python ${{ matrix.python-version }}uses: actions/setup-python@v5@@ -196,5 +198,7 @@ jobs:name: Check for typosruns-on: ubuntu-lateststeps:+ - name: 🛑 Cancel Previous Runs+ uses: styfle/[email protected]- uses: actions/checkout@v4- uses: crate-ci/[email protected]diff --git a/.github/workflows/test_cli.yaml b/.github/workflows/test_cli.yamlindex 479fde19cd..4772d005e3 100644--- a/.github/workflows/test_cli.yaml+++ b/.github/workflows/test_cli.yaml@@ -80,6 +80,8 @@ jobs:os: [ubuntu-latest, macos-latest, windows-latest]steps:+ - name: 🛑 Cancel Previous Runs+ uses: styfle/[email protected]- uses: actions/checkout@v4- name: Set up Python ${{ matrix.python-version }}uses: actions/setup-python@v5@@ -87,12 +89,6 @@ jobs:python-version: ${{ matrix.python-version }}cache: "pip"- # We tried to add uv, but got the following error:- # $ uv pip install marimo*whl- # > No solution found when resolving dependencies:- # - name: 🐍 Setup uv- # uses: yezz123/setup-uv@v4-- name: Install Python depsrun: |python -m pip install --upgrade pip@@ -110,3 +106,40 @@ jobs:- name: Test CLIshell: bashrun: pytest -v tests/_cli/test_cli.py tests/_cli/test_cli_export.py++ test_examples:+ name: Tests examples and smoke_tests+ needs: build_wheel+ runs-on: ubuntu-latest++ steps:+ - name: 🛑 Cancel Previous Runs+ uses: styfle/[email protected]+ - uses: actions/checkout@v4+ - name: Set up Python 3.10+ uses: actions/setup-python@v5+ with:+ python-version: "3.10"+ cache: "pip"++ - name: 🐍 Setup uv+ uses: yezz123/setup-uv@v4+ with:+ uv-venv: marimo-venv++ - name: Download wheel+ uses: actions/download-artifact@v3+ with:+ name: testwheel++ - name: Install Python deps+ run: |+ uv pip install pytest pytest-asyncio+ uv pip install ./marimo*whl+ uv pip install -r examples/requirements.txt++ - name: Test examples+ shell: bash+ run: pytest -v -s tests/_smoke_tests/run_all.py+ # TODO(msconick) remove continue-on-error when all tests pass+ continue-on-error: truediff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 4f8321cc19..3de658f0c1 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -11,6 +11,7 @@ repos:hooks:- id: markdownlint-fixargs: [-c, configs/.markdownlint.yaml, --fix]+ exclude: marimo/_tutorials/.*\.md- repo: https://github.com/crate-ci/typosrev: v1.21.0diff --git a/examples/data_explorer.py b/examples/data_explorer.pyindex b497a75251..bff4882b75 100644--- a/examples/data_explorer.py+++ b/examples/data_explorer.py@@ -1,6 +1,6 @@import marimo-__generated_with = "0.1.0"+__generated_with = "0.6.0"app = marimo.App()@@ -26,7 +26,7 @@ def __(df, mo, uploaded_file):mo.md(f"""- {mo.hstack([mo.md("**Upload a CSV.**")], "center")}+ {mo.hstack([mo.md("**Upload a CSV.**")], justify="center")}{uploaded_file}diff --git a/examples/requirements.txt b/examples/requirements.txtindex 4b546e68cf..b4587486f6 100644--- a/examples/requirements.txt+++ b/examples/requirements.txt@@ -3,13 +3,35 @@ langchain >= 0.0.245marimo >= 0.1.0matplotlib >= 3.2.0mortgage >= 1.0.5+vega-datasets >= 0.9.0+altair >= 5.3.0numpy >= 1.22.0+polars >= 0.20.0openai >= 0.27.8pandas >= 2.0.0pymde >= 0.1.18+matplotlib >= 3.4.0+pyarrow >= 6.0.0+leafmap >= 0.3.0+bokeh >= 3.0.0+holoviews >= 1.14.0+hvplot >= 0.7.0pypdf2 >= 3.0.1+rich >= 11.0.0+duckdb >= 0.9.0+requests >= 2.26.0+websocket >= 0.2.0seaborn >= 0.12.0+scikit-image >= 0.23.2sig-decomp == 0.1.1+gspread >= 6.0.0tiktoken >= 0.4.0pillow>=10.0.0 # not directly required, pinned by Snyk to avoid a vulnerabilityfonttools>=4.43.0 # not directly required, pinned by Snyk to avoid a vulnerability+oauth2client >= 4.1.3+google-cloud-bigquery+plotly+drawdata+anywidget+db-dtypes+google-cloud-storagediff --git a/examples/third_party/duckdb.py b/examples/third_party/duckdb_example.pysimilarity index 100%rename from examples/third_party/duckdb.pyrename to examples/third_party/duckdb_example.pydiff --git a/examples/third_party/leafmap.py b/examples/third_party/leafmap_example.pysimilarity index 100%rename from examples/third_party/leafmap.pyrename to examples/third_party/leafmap_example.pydiff --git a/examples/third_party/polars.py b/examples/third_party/polars_example.pysimilarity index 100%rename from examples/third_party/polars.pyrename to examples/third_party/polars_example.pydiff --git a/marimo/_cli/convert/markdown.py b/marimo/_cli/convert/markdown.pyindex 584e34cebe..c36fa727de 100644--- a/marimo/_cli/convert/markdown.py+++ b/marimo/_cli/convert/markdown.py@@ -8,6 +8,8 @@ from typing import Any, Callable, Literal, Optional, Union# Native to pythonfrom xml.etree.ElementTree import Element, SubElement+import yaml+# Markdown is a dependency of marimo, as such we utilize it as much as possible# to parse markdown.from markdown import Markdown@@ -28,7 +30,6 @@ from marimo._ast.cell import Cell, CellConfigfrom marimo._ast.compiler import compile_cellfrom marimo._cli.convert.utils import markdown_to_marimo-import yaml# CSafeLoader is faster than SafeLoader.try:from yaml import CSafeLoader as SafeLoaderdiff --git a/marimo/_cli/envinfo.py b/marimo/_cli/envinfo.pyindex c3c66e5746..1ba128c099 100644--- a/marimo/_cli/envinfo.py+++ b/marimo/_cli/envinfo.py@@ -3,10 +3,15 @@ from __future__ import annotationsimport platformimport sys-from typing import Union+from typing import Any, Union, castfrom marimo import __version__-from marimo._utils.health import get_chrome_version, get_node_version, get_required_modules_list+from marimo._utils.health import (+ get_chrome_version,+ get_node_version,+ get_required_modules_list,+)+def is_win11() -> bool:"""@@ -15,7 +20,10 @@ def is_win11() -> bool:Returns:bool: True if the OS is Windows 11, False otherwise."""- return sys.getwindowsversion().build >= 22000+ if hasattr(sys, "getwindowsversion"):+ return cast(Any, sys).getwindowsversion().build >= 22000 # type: ignore[no-any-return]+ return False+def get_system_info() -> dict[str, Union[str, dict[str, str]]]:os_version = platform.release()diff --git a/marimo/_smoke_tests/output.py b/marimo/_smoke_tests/output.pyindex 1d3661f841..e5cbbdad5a 100644--- a/marimo/_smoke_tests/output.py+++ b/marimo/_smoke_tests/output.py@@ -1,7 +1,8 @@# Copyright 2024 Marimo. All rights reserved.+import marimo-__generated_with = "0.1.19"+__generated_with = "0.6.0"app = marimo.App()@@ -22,12 +23,12 @@ def __(mo, time):def loop_replace():for i in range(5):mo.output.replace(mo.md(f"Loading {i}/5"))- time.sleep(.1)+ time.sleep(.01)def loop_append():for i in range(5):mo.output.append(mo.md(f"Loading {i}/5"))- time.sleep(.1)+ time.sleep(.01)return loop_append, loop_replacediff --git a/marimo/_smoke_tests/scripting.py b/marimo/_smoke_tests/scripting.pyindex a2fe17c284..9b80ec375d 100644--- a/marimo/_smoke_tests/scripting.py+++ b/marimo/_smoke_tests/scripting.py@@ -1,7 +1,8 @@# Copyright 2024 Marimo. All rights reserved.+import marimo-__generated_with = "0.1.0"+__generated_with = "0.6.0"app = marimo.App()@@ -19,7 +20,7 @@ def __(mo):@app.celldef __(mo):- mo.html("<script>console.log(document.querySelectorAll('p')[0].textContent)</script>")+ mo.Html("<script>console.log(document.querySelectorAll('p')[0].textContent)</script>")returndiff --git a/marimo/_smoke_tests/status.py b/marimo/_smoke_tests/status.pyindex f65547481d..1be5b5824c 100644--- a/marimo/_smoke_tests/status.py+++ b/marimo/_smoke_tests/status.py@@ -2,7 +2,7 @@import marimo-__generated_with = "0.2.9"+__generated_with = "0.6.0"app = marimo.App()@@ -14,16 +14,29 @@ def __():@app.cell-def __(mo, time):+def __(mo):+ sleep_time_radio = mo.ui.radio([".01", ".1", "1"], label="Sleep time", value=".01")+ sleep_time_radio+ return sleep_time_radio,+++def __(sleep_time_radio):+ sleep_time = float(sleep_time_radio.value)+ return sleep_time,+++def __(mo, sleep_time, time):for _ in mo.status.progress_bar(range(10), title="Loading", subtitle="Please wait"):- time.sleep(0.1)+ time.sleep(sleep_time)return@app.cell-def __(mo, time):+def __(mo, sleep_time, time):for _ in mo.status.progress_bar(range(10),title="Loading",@@ -31,40 +44,43 @@ def __(mo, time):show_eta=True,show_rate=True,):- time.sleep(0.5)+ time.sleep(sleep_time)return+@app.cell-def __(mo, time):- with mo.status.progress_bar(title='Loading', subtitle='Please wait') as bar:+def __(mo, sleep_time, time):+ with mo.status.progress_bar(title='Loading', subtitle='Please wait', total=10) as bar:for _ in range(10):- time.sleep(0.5)+ time.sleep(sleep_time)bar.update()+ return bar,+@app.cell-def __(mo, time):+def __(mo, sleep_time, time):with mo.status.spinner(title="Loading...", remove_on_exit=True) as _spinner:- time.sleep(1)+ time.sleep(.1)_spinner.update("Almost done")- time.sleep(1)+ time.sleep(sleep_time)return@app.cell-def __(mo, time):+def __(mo, sleep_time, time):with mo.status.spinner(title="Loading...", remove_on_exit=True) as _spinner:- time.sleep(1)+ time.sleep(sleep_time)_spinner.update("Almost done")- time.sleep(1)+ time.sleep(sleep_time)mo.ui.table([1, 2, 3])return@app.cell-def __(mo, time):+def __(mo, sleep_time, time):# Fast updates should be debounced for performancefor i in mo.status.progress_bar(range(1000)):- time.sleep(0.001)+ time.sleep(sleep_time/10)return i,diff --git a/marimo/_smoke_tests/third_party/altair.py b/marimo/_smoke_tests/third_party/altair_example.pysimilarity index 100%rename from marimo/_smoke_tests/third_party/altair.pyrename to marimo/_smoke_tests/third_party/altair_example.pydiff --git a/marimo/_smoke_tests/third_party/holoviews.py b/marimo/_smoke_tests/third_party/holoviews_example.pysimilarity index 100%rename from marimo/_smoke_tests/third_party/holoviews.pyrename to marimo/_smoke_tests/third_party/holoviews_example.pydiff --git a/marimo/_smoke_tests/third_party/pandas.py b/marimo/_smoke_tests/third_party/pandas_example.pysimilarity index 100%rename from marimo/_smoke_tests/third_party/pandas.pyrename to marimo/_smoke_tests/third_party/pandas_example.pydiff --git a/marimo/_smoke_tests/third_party/plotly.py b/marimo/_smoke_tests/third_party/plotly_example.pysimilarity index 100%rename from marimo/_smoke_tests/third_party/plotly.pyrename to marimo/_smoke_tests/third_party/plotly_example.pydiff --git a/marimo/_smoke_tests/third_party/rich.py b/marimo/_smoke_tests/third_party/rich_example.pysimilarity index 100%rename from marimo/_smoke_tests/third_party/rich.pyrename to marimo/_smoke_tests/third_party/rich_example.pydiff --git a/marimo/_smoke_tests/third_party/seaborn.py b/marimo/_smoke_tests/third_party/seaborn_example.pysimilarity index 100%rename from marimo/_smoke_tests/third_party/seaborn.pyrename to marimo/_smoke_tests/third_party/seaborn_example.pydiff --git a/tests/_cli/snapshots/dataflow.md.txt b/tests/_cli/snapshots/dataflow.md.txtindex 402c555118..6890279f1e 100644--- a/tests/_cli/snapshots/dataflow.md.txt+++ b/tests/_cli/snapshots/dataflow.md.txt@@ -12,6 +12,18 @@ automatically.To provide reactive execution, marimo creates a dataflow graph out of yourcells.<!---->+**Tip: disabling automatic execution.**++marimo lets you disable automatic execution: just go into the notebook settings+and set++"Runtime > On Cell Change" to "lazy".++When the runtime is lazy, after running a cell, marimo marks its+descendants as stale instead of automatically running them. The lazy+runtime puts you in control over when cells are run, while still giving+guarantees about the notebook state.+<!---->## References and definitionsA marimo notebook is a directed acyclic graph in which nodes representdiff --git a/tests/_smoke_tests/config.yml b/tests/_smoke_tests/config.ymlnew file mode 100644index 0000000000..853b9c340e--- /dev/null+++ b/tests/_smoke_tests/config.yml@@ -0,0 +1,74 @@+files:+ ###################+ # Inputs+ ansi.py:+ input: "y"+ stdin.py:+ input: "y"++ ###################+ # Errors+ bugs/924.py:+ failed_reason: "ModuleNotFoundError: No module named 'micropip'"+ third_party/ipython_display.py:+ failed_reason: "ModuleNotFoundError: No module named 'tikz'"+ bugs/1055.py:+ failed_reason: "ModuleNotFoundError: No module named 'manim_slides'"+ bugs/1270.py:+ failed_reason: "UDF failed: DataFrame constructor"+ stop.py:+ failed_reason: "MarimoStopError"+ charts/1mil_flights.py:+ failed_reason: "MarimoStopError"+ errors.py:+ failed_reason: "UnparsableError"+ reactive_plots.py:+ failed_reason: "MarimoStopError"+ model_comparison/model_comparison.py:+ failed_reason: "MarimoStopError"+ third_party/duckdb_example.py:+ failed_reason: "MarimoStopError"++ ###################+ # Not a marimo app+ custom_server/my_server.py:+ skip: true+ # This runs plt.show() which blocks the test+ bugs/1086.py:+ skip: true+ ws.py:+ skip: true+ embeddings/debugging_embeddings.py:+ skip: true+ embeddings/embedding_numbers.py:+ skip: true+ embeddings/interactive_cluster_analysis.py:+ skip: true+ embeddings/rotational_invariance.py:+ skip: true+ embeddings/google_scholar.py:+ skip: true+ embeddings/us_counties.py:+ skip: true+ ai/question-pdf.py:+ skip: true+ # Don't work on macos+ optimization/smallest_enclosing_circle.py:+ skip: true+ optimization/regularization_and_sparsity.py:+ skip: true+ optimization/signals/examples.py:+ skip: true+ optimization/signals/app.py:+ skip: true++ ###################+ # Should be fixed+ refresh.py: # flaky+ skip: true+ failed_reason: "MarimoStopError"+ iplot.py:+ skip: true+ failed_reason: "RuntimeError: cannot schedule new futures after interpreter shutdown"+ pdb_test.py:+ failed_reason: "AttributeError: module 'marimo' has no attribute 'pdb'"diff --git a/tests/_smoke_tests/run_all.py b/tests/_smoke_tests/run_all.pynew file mode 100644index 0000000000..b19b10a8c8--- /dev/null+++ b/tests/_smoke_tests/run_all.py@@ -0,0 +1,134 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+import os+import pathlib+from typing import Any, Dict, Optional++import pytest+import yaml++from marimo._utils.paths import import_files++CONCURRENT_TESTS = 5++config_file = os.path.join(os.path.dirname(__file__), "config.yml")+++async def test_all_smoke_tests() -> None:+ root = os.path.realpath(+ str(import_files("marimo").joinpath("_smoke_tests"))+ )+ all_py_paths = list(pathlib.Path(root).rglob("*.py"))+ assert all_py_paths, "No smoke tests found"++ with open(config_file, "r") as f: # noqa: ASYNC101+ smoke_test_config = yaml.load(f.read(), Loader=yaml.FullLoader)++ semaphore = asyncio.Semaphore(CONCURRENT_TESTS)+ tasks = [+ _run_test(file, root, smoke_test_config, semaphore)+ for file in all_py_paths+ ]+ await asyncio.gather(*tasks)+++async def test_all_examples() -> None:+ root = os.path.realpath(+ str(import_files("marimo").joinpath("../examples"))+ )+ all_py_paths = list(pathlib.Path(root).rglob("*.py"))+ assert all_py_paths, "No examples found"++ with open(config_file, "r") as f: # noqa: ASYNC101+ smoke_test_config = yaml.load(f.read(), Loader=yaml.FullLoader)++ semaphore = asyncio.Semaphore(CONCURRENT_TESTS)+ tasks = [+ _run_test(file, root, smoke_test_config, semaphore)+ for file in all_py_paths+ ]+ await asyncio.gather(*tasks)+++async def _run_test(+ file: pathlib.Path,+ root: str,+ smoke_test_config: Dict[str, Any],+ semaphore: asyncio.Semaphore,+) -> None:+ async with semaphore:+ relative_file = str(file.relative_to(root))+ file_config = smoke_test_config.get("files", {}).get(relative_file, {})+ skip = file_config.get("skip", None)+ if skip is True:+ return++ failed_reason = file_config.get("failed_reason", None)+ input_data = file_config.get("input", None)++ with open(file, "r") as f: # noqa: ASYNC101+ content = f.read()+ if "marimo.App(" not in content:+ return++ process, stdout, stderr = await Cmd(+ f"python {file}", timeout=10, input_data=input_data+ ).run()++ if failed_reason:+ # Expecting an error+ assert (+ process.returncode != 0+ ), f"{relative_file} Expected error: {failed_reason}"+ assert failed_reason in stderr, f"File: {file}"+ # Allow MarimoStop+ elif "MarimoStop" in stderr:+ assert (+ process.returncode != 0+ ), f"{relative_file} Unexpected error: {stderr}"+ else:+ # Expecting no error, allow MarimoStop+ assert (+ process.returncode == 0+ ), f"{relative_file} Unexpected error: {stderr}"+ assert not any(+ line.startswith("Traceback") for line in stderr.splitlines()+ )+ assert not any(+ line.startswith("Traceback") for line in stdout.splitlines()+ )++ print(f"✅ {relative_file}")+++class Cmd:+ def __init__(+ self, command: str, timeout: int, input_data: Optional[str] = None+ ):+ self.command = command+ self.timeout = timeout+ self.input_data = input_data++ async def run(self):+ process = await asyncio.create_subprocess_shell(+ self.command,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ stdin=asyncio.subprocess.PIPE,+ )++ try:+ stdout, stderr = await asyncio.wait_for(+ process.communicate(+ input=self.input_data.encode() if self.input_data else None+ ),+ timeout=self.timeout,+ )+ except asyncio.TimeoutError:+ process.kill()+ await process.communicate()+ pytest.fail(f"Timeout: {self.command}")++ return process, stdout.decode(), stderr.decode()