diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 34f1ed8a9..e5d237192 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -111,6 +111,41 @@ jobs: - name: Test run: pytest tests/ --ignore=tests/test_blocks.py -m "not slow" --timeout=50 --timeout_method=thread -q + # Advisory while we establish a history of green runs in real Pyodide. + # Kept out of all-tests-passed; make it required once it has run green for a while. + test-pyodide: + runs-on: ubuntu-latest + continue-on-error: true + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-python@v7 + with: + python-version: "3.12" + cache: pip + + - name: Build pure-Python wheel for Pyodide + # Use the same wheel as JupyterLite, with the Python fallbacks for the + # compiled extensions. The tests must import this wheel inside WASM. + run: | + pip install build + RTB_PURE_WHEEL=1 python -m build --wheel + + # Node 26, not the 22 used by docs.yml: the notebook-bootstrap tests call + # asyncio.run() inside Pyodide, which needs WebAssembly stack switching + # (JSPI), and Node 22 does not have it. + - uses: actions/setup-node@v7 + with: + node-version: "26" + cache: npm + cache-dependency-path: docs/lite/wasm_check/package-lock.json + + - name: Test inside real Pyodide + run: | + npm --prefix docs/lite/wasm_check ci + node docs/lite/wasm_check/run_pytest.mjs dist/*.whl + all-tests-passed: name: All tests passed needs: [test-core, test] diff --git a/docs/lite/wasm_check/README.md b/docs/lite/wasm_check/README.md index bfe5ee9e2..41d2c844b 100644 --- a/docs/lite/wasm_check/README.md +++ b/docs/lite/wasm_check/README.md @@ -51,6 +51,33 @@ dependency of RTB that cannot be installed in Pyodide, needing a workaround in `_rtb_nb_bootstrap.py`) and how to fix it, followed by the real traceback. +## Test suite in Pyodide + +`run_pytest.mjs` runs the non-slow test suite inside real Pyodide under Node, +against a pure-Python wheel installed through the same notebook bootstrap. The +advisory `test-pyodide` job in `ci.yml` runs it on every PR, in parallel with the +desktop tests. Run it locally from the repository root: + +```bash +RTB_PURE_WHEEL=1 python -m build --wheel +npm --prefix docs/lite/wasm_check ci +node docs/lite/wasm_check/run_pytest.mjs dist/*.whl +``` + +The runner copies tests and the source, example and notebook files they inspect +into Pyodide's filesystem. Matplotlib uses Agg; pytest uses system capture and +disables its timeout plugin because subprocesses, file-descriptor capture and +signal timers are unavailable there. A failing pytest run exits non-zero. + +To skip a test that needs a feature unavailable in the browser, add its node ID +to the relevant reason group in `_PYODIDE_SKIPS` in `tests/conftest.py`, or add a +group with a specific reason. IDs can name a module, class, test or individual +parameter case; skips remain visible in pytest's report. Modules that import +`bdsim` at module scope are skipped by the collection hook before those imports. +These rules apply only when `sys.platform == "emscripten"`. Known bugs belong in +`_PYODIDE_XFAILS` instead: non-strict xfails keep them visible until separate fixes +land, without changing any desktop expectations. + ## Known flakiness Each run installs ~35 packages fresh from a CDN (jsdelivr). An occasional network diff --git a/docs/lite/wasm_check/run_pytest.mjs b/docs/lite/wasm_check/run_pytest.mjs new file mode 100644 index 000000000..e9cf43e98 --- /dev/null +++ b/docs/lite/wasm_check/run_pytest.mjs @@ -0,0 +1,86 @@ +#!/usr/bin/env node +/** + * Run the test suite inside real Pyodide under Node, using the notebook install + * path. This checks WASM behaviour; browser widget presentation is covered by + * ../browser_check/ instead. + * + * Usage: node docs/lite/wasm_check/run_pytest.mjs + */ + +import { loadPyodide } from "pyodide"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const wheelPath = process.argv[2]; +if (!wheelPath) { + console.error("Usage: node docs/lite/wasm_check/run_pytest.mjs "); + process.exit(2); +} + +const root = fileURLToPath(new URL("../../../", import.meta.url)); +const wheelName = path.basename(wheelPath); +const pyodide = await loadPyodide(); +await pyodide.loadPackage("micropip"); + +function copyTree(source, target) { + pyodide.FS.mkdirTree(target); + for (const entry of fs.readdirSync(source, { withFileTypes: true })) { + if (["__pycache__", ".ipynb_checkpoints", ".env"].includes(entry.name) + || entry.name.startsWith(".env.")) continue; + const src = path.join(source, entry.name); + const dst = target + "/" + entry.name; + if (entry.isDirectory()) copyTree(src, dst); + else if (entry.isFile() && !entry.name.endsWith(".pyc")) { + pyodide.FS.writeFile(dst, fs.readFileSync(src)); + } + } +} + +// Some tests inspect source, compile examples or read notebook resources. Keep +// their repository layout, but import the toolbox from the installed wheel. +for (const directory of ["tests", "src/roboticstoolbox", "examples", "docs/notebooks"]) { + copyTree(path.join(root, directory), "/repo/" + directory); +} +pyodide.FS.writeFile("/repo/pyproject.toml", fs.readFileSync(path.join(root, "pyproject.toml"))); +// The JupyterLite capability-banner tests read these alongside the notebooks. +pyodide.FS.mkdirTree("/repo/docs/lite"); +for (const name of ["inject_jspi_check.py", "jspi-check.js"]) { + pyodide.FS.writeFile("/repo/docs/lite/" + name, fs.readFileSync(path.join(root, "docs/lite", name))); +} +pyodide.FS.writeFile("/" + wheelName, fs.readFileSync(wheelPath)); +pyodide.globals.set("_wheel_url", "emfs:/" + wheelName); + +const exitCode = await pyodide.runPythonAsync(` +import os +import sys +import types + +os.environ["MPLBACKEND"] = "Agg" +sys.path.insert(0, "/repo/docs/notebooks") +import micropip +import _rtb_nb_bootstrap as bootstrap + +# As in check_pyodide_install.mjs, only replace piplite's wheel lookup. The real +# bootstrap still owns the install steps and resolves all other dependencies. +piplite = types.ModuleType("piplite") +async def install(requirements, deps=True, **kwargs): + if requirements == "roboticstoolbox-python": + requirements = _wheel_url + return await micropip.install(requirements, deps=deps, **kwargs) +piplite.install = install +sys.modules["piplite"] = piplite +await bootstrap.ensure_installed(extras=["ik"]) +await micropip.install("pytest") + +os.chdir("/repo") +sys.path.insert(0, "/repo") +import pytest +print(f"Pyodide: {sys.version}; {sys.platform}") +# fd capture and pytest-timeout rely on OS facilities unavailable in Pyodide. +int(pytest.main([ + "tests", "-m", "not slow", "--ignore=tests/test_blocks.py", "-q", + "-p", "no:cacheprovider", "-p", "no:timeout", "--capture=sys", "-rfEX", +])) +`); +process.exitCode = exitCode; diff --git a/tests/conftest.py b/tests/conftest.py index 8f4d354ef..c0ef3f8f5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,14 +6,19 @@ - Registers the skip_no_collision_checking/skip_no_qp marks (defined in tests/__init__.py, imported as `from tests import ...`) so pytest recognizes them instead of warning PytestUnknownMarkWarning. +- Records browser limitations and known failures when running in real Pyodide. """ +import sys +from pathlib import Path + import matplotlib +import pytest matplotlib.use("Agg") # must be set before any pyplot import -def pytest_configure(config): +def pytest_configure(config: pytest.Config) -> None: config.addinivalue_line( "markers", "skip_no_collision_checking: skip test if coal/trimesh are not installed", @@ -22,3 +27,147 @@ def pytest_configure(config): "markers", "skip_no_qp: skip test if qpsolvers/quadprog are not installed", ) + + +# Keep these rules together so a browser-only limitation has one stated reason, +# and desktop runs collect and execute exactly the same tests as before. +_BDSIM_REASON = "bdsim is not installed by the notebook bootstrap" +_PYODIDE_SKIPS = [ + ( + "Pyodide cannot start subprocesses", + ( + "tests/test_bin.py", + "tests/test_demo.py", + "tests/test_Robot.py::TestRobot::test_showgraph", + ), + ), + ( + "robot_descriptions URDF assets need git, unavailable in Pyodide", + ( + "tests/test_BaseRobot.py::TestBaseRobot::test_ets_gripper2", + "tests/test_BaseRobot.py::TestBaseRobot::test_init", + "tests/test_BaseRobot.py::TestBaseRobot::test_init9", + "tests/test_BaseRobot.py::TestBaseRobot::test_limits", + "tests/test_BaseRobot.py::TestBaseRobot::test_segments2", + "tests/test_BaseRobot.py::TestBaseRobot::test_str", + "tests/test_BaseRobot.py::TestBaseRobot::test_yumi_gripper_parents", + "tests/test_CustomXacro.py::TestCustomXacro::test_custom", + "tests/test_IK.py::TestIK::test_IK_GN3", + "tests/test_IK.py::TestIK::test_ik_lm_failure_returns_compact_q", + "tests/test_Robot.py::TestRobot::test_fkine_all2", + "tests/test_Robot.py::TestRobot::test_fkine_compact_q_branched_robot", + "tests/test_URDFRobot.py::TestURDFRobotGripperLinkName", + "tests/test_fknm_fallback.py::TestRobotLinkTReference::test_gripper_without_joints", + "tests/test_models.py::TestModels::test_Jaco", + "tests/test_models.py::TestModels::test_PandaURDF_robot_descriptions", + "tests/test_models.py::TestModels::test_UR10", + "tests/test_models.py::TestModels::test_UR3", + "tests/test_models.py::TestModels::test_UR5", + "tests/test_models.py::TestModels::test_pr2", + "tests/test_models.py::TestModelSmoke::test_all_models_construct", + "tests/test_urdf_model.py::TestURDF::test_urdf_load", + ), + ), + ( + "the teach panel refuses to run under Jupyter/Pyodide", + ( + "tests/test_BaseRobot.py::TestBaseRobot::test_teach", + "tests/test_DHRobot.py::TestDHRobot::test_teach", + "tests/test_DHRobot.py::TestDHRobot::test_teach_basic", + "tests/test_DHRobot.py::TestDHRobot::test_teach_withq", + "tests/test_ETS.py::TestETS::test_teach", + "tests/test_plot_view.py::TestTeach", + ), + ), + ( + _BDSIM_REASON, + ("tests/test_quintic_conditioning.py::test_bdsim_quintic_block_long_duration",), + ), + ( + "window-mode expectation: Pyodide uses notebook-inline rendering", + ( + "tests/test_plot_env.py::TestSharedScene::test_the_second_plot_is_added_to_the_scene", + "tests/test_plot_env.py::TestAxes::test_plot_on_given_axes", + "tests/test_render_mode.py::test_other_environments_update_one_inline_display", + "tests/test_step_dt.py::test_3d_step_needs_a_positive_dt[0]", + "tests/test_step_dt.py::test_3d_step_needs_a_positive_dt[0.0]", + "tests/test_step_dt.py::test_2d_step_needs_a_positive_dt[0]", + "tests/test_step_dt.py::test_2d_step_needs_a_positive_dt[0.0]", + "tests/test_step_dt.py::test_plot_with_a_zero_dt_raises_and_does_not_hang", + ), + ), + ( + "collision checking is disabled in Pyodide before checking for coal", + ( + "tests/test_collision.py::TestEnvironmentGuards::test_missing_coal_raises_import_error", + ), + ), +] + +# These are real findings, not unsupported features. Keep running them so a +# separate fix shows up as XPASS without making this advisory job fail. +_PYODIDE_XFAILS = [ + ( + "movie getframe draws the wrong canvas before reading its renderer", + ("tests/test_PyPlot.py::TestPyPlot::test_plot_movie",), + ), + ( + "path byte hashes assume int64 but Pyodide paths use int32", + ( + "tests/test_planner_cleanup.py::TestDistanceTransformQuery::test_book_paths_are_unchanged", + ), + ), + ( + "notebook-inline step accepts a negative dt without validation", + ( + "tests/test_step_dt.py::test_3d_step_needs_a_positive_dt[-0.05]", + "tests/test_step_dt.py::test_2d_step_needs_a_positive_dt[-0.05]", + ), + ), + ( + "emscripten backend selection overrides the configured default backend", + ( + "tests/test_default_backend.py::test_a_default_given_in_upper_case_selects_the_backend", + "tests/test_default_backend.py::test_a_registered_backend_can_be_the_default", + ), + ), +] + + +class _PyodideBdsimModule(pytest.Module): + def collect(self) -> list[pytest.Item | pytest.Collector]: + # These modules import bdsim at module scope, before item marks can help. + # Skipping the collector reports a skip, rather than hiding the module. + pytest.skip(_BDSIM_REASON) + + +def pytest_pycollect_makemodule( + module_path: Path, parent: pytest.Collector +) -> pytest.Module | None: + if sys.platform == "emscripten" and module_path.name in ( + "test_block_parameters.py", + "test_trapezoidal_profile.py", + ): + return _PyodideBdsimModule.from_parent(parent, path=module_path) + return None + + +def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: + if sys.platform != "emscripten": + return + + for rules, mark in ( + (_PYODIDE_SKIPS, pytest.mark.skip), + (_PYODIDE_XFAILS, pytest.mark.xfail(strict=False)), + ): + for reason, prefixes in rules: + for item in items: + # Match a module, class, test or parameter case without also + # matching similarly named tests (test_init versus test_init2). + if any( + item.nodeid == prefix + or item.nodeid.startswith(prefix + "::") + or item.nodeid.startswith(prefix + "[") + for prefix in prefixes + ): + item.add_marker(mark(reason=reason))