Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
*test*
*.p
*.jpg
*.pdf
Expand All @@ -24,6 +23,7 @@ OLD
.vscode
dist
build
tests/reports
*.egg-info
.claude
/UNTRACKED
15 changes: 7 additions & 8 deletions RVC3/examples/imu_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

import matplotlib.pyplot as plt

def IMU():
def tumble():
# accelerometer
g0 = unitvec( [0, 0, 9.8] ).T
gbias = 0.02 * np.r_[2, -2, 2].T # bias 2% of norm
Expand All @@ -30,7 +30,7 @@ def IMU():
mbias = 0.02 * np.r_[-1, -1, 2] # bias 2# of norm

# gyro
wbias = 0.05 * np.r_[-1, 2, -1] # bias 10% of max
wbias = 0.05 * np.r_[-1, 2, -1] # bias 5% of max

## simulation

Expand All @@ -53,10 +53,10 @@ def IMU():
# 1 row per timestep
t = np.arange(0, 20, dt)
omega = odeint( lambda w, t: -np.linalg.inv(J) @ np.cross(w, J @ w),
w0, t)
w0, t)

# Solve for simulated sensor readings and true attitude
# 1 row per timestep
# 1 column per timestep
am = np.zeros(omega.shape)
mm = np.zeros(omega.shape)

Expand All @@ -68,12 +68,11 @@ def IMU():
mm[k,:] = iq * m0 + mbias # sensor reading
truth.append(truth[k] * UnitQuaternion.EulerVec(w * dt))
del truth[-1]
# add bias to measured
# add bias to measured
wm = omega + wbias

imu = namedtuple('imu', 't dt gyro accel magno')
true = namedtuple('true', 't dt omega orientation g B')
return true(t, dt, omega, truth, g0, m0), imu(t, dt, wm, am, mm)
data = namedtuple('tumble', 't omega_true attitude_true g B gyro accel magno')
return data(t, omega, truth, g0, m0, wm, am, mm)

if __name__ == "__main__":

Expand Down
30 changes: 30 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Shared pytest configuration.

Notebook and example-script tests are real but slow (image/vision chapters,
animation loops) -- they're marked `slow` and skipped by default so a plain
`pytest tests/` stays a fast smoke test. Run the full suite with `--runall`.
"""

import pytest


def pytest_addoption(parser):
parser.addoption(
"--runall",
action="store_true",
default=False,
help="also run slow tests (notebooks, RVC3/examples scripts)",
)


def pytest_configure(config):
config.addinivalue_line("markers", "slow: slow test, skipped unless --runall is passed")


def pytest_collection_modifyitems(config, items):
if config.getoption("--runall"):
return
skip_slow = pytest.mark.skip(reason="slow test -- pass --runall to run it")
for item in items:
if "slow" in item.keywords:
item.add_marker(skip_slow)
25 changes: 25 additions & 0 deletions tests/examples_skiplist.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Per-script overrides for tests/test_examples.py, applied by tests/run_example.py.
#
# skip: true -- don't run the script at all, report as skipped with `reason`
# patches: [...] -- literal-text substitutions applied to the script's source
# before exec, e.g. to cap a hardcoded animation loop so it
# finishes quickly under test. `match` must appear verbatim
# in the script or the patch is a no-op (with a warning).
#
# Global to every script, applied by run_example.py itself (not listed per-script
# here): MPLBACKEND=Agg, and matplotlib.pyplot.pause() replaced with a no-op, since
# it sleeps in real wall-clock time even under a headless backend.

visodom.py:
skip: true
reason: >-
requires the manually-downloaded .enpeda stereo dataset
(bridge-l.zip / bridge-r.zip), not bundled with this repo

walking.py:
patches:
- match: "for i in range(4000):"
replace: "for i in range(50):"
reason: >-
cap the gait animation loop to keep the smoke test fast;
the full demo walks for 4000 steps
67 changes: 67 additions & 0 deletions tests/run_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#!/usr/bin/env python
"""
Run a single RVC3/examples/*.py script under automated-test conditions.

Applies two kinds of test-only patching before executing the script's source:

- matplotlib.pyplot.pause() is replaced with a no-op. It sleeps in real
wall-clock time even under the headless Agg backend, which several
examples (and the RTB PyPlot backend's own animation step) call in a
loop -- left alone, a single script can take minutes to finish.
- per-script literal source substitutions from examples_skiplist.yaml,
e.g. capping a hardcoded animation loop count.

Never modifies the script on disk -- patches are applied to an in-memory
copy of its source before exec().

Usage:
python tests/run_example.py RVC3/examples/walking.py
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import yaml

SKIPLIST_PATH = Path(__file__).resolve().parent / "examples_skiplist.yaml"


def load_config() -> dict:
if not SKIPLIST_PATH.exists():
return {}
return yaml.safe_load(SKIPLIST_PATH.read_text()) or {}


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("script", type=Path)
args = parser.parse_args()

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.pause = lambda *args, **kwargs: None

config = load_config().get(args.script.name, {})
source = args.script.read_text()
for patch in config.get("patches", []):
if patch["match"] not in source:
print(
f"warning: patch match {patch['match']!r} not found in {args.script.name}, skipping it",
file=sys.stderr,
)
continue
source = source.replace(patch["match"], patch["replace"])

globals_ = {"__name__": "__main__", "__file__": str(args.script)}
exec(compile(source, str(args.script), "exec"), globals_)
return 0


if __name__ == "__main__":
sys.exit(main())
51 changes: 51 additions & 0 deletions tests/test_examples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#!/usr/bin/env python
"""
Slow test: run every script in RVC3/examples/ and check it exits cleanly.

Each script runs in its own subprocess via run_example.py, which patches
away real-time sleeps (matplotlib.pyplot.pause) and applies any per-script
overrides in examples_skiplist.yaml (skip entirely, or cap a hardcoded
loop) before exec'ing the script's source. See run_example.py and
examples_skiplist.yaml for what's patched and why.
"""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

import pytest
import yaml

REPO_ROOT = Path(__file__).resolve().parent.parent
EXAMPLES_DIR = REPO_ROOT / "RVC3" / "examples"
RUNNER = Path(__file__).resolve().parent / "run_example.py"
SKIPLIST_PATH = Path(__file__).resolve().parent / "examples_skiplist.yaml"


def _skiplist() -> dict:
if not SKIPLIST_PATH.exists():
return {}
return yaml.safe_load(SKIPLIST_PATH.read_text()) or {}


def _scripts() -> list[Path]:
return sorted(p for p in EXAMPLES_DIR.glob("*.py") if p.name != "__init__.py")


pytestmark = pytest.mark.slow


@pytest.mark.parametrize("script", _scripts(), ids=lambda p: p.name)
def test_example_runs(script: Path):
skip = _skiplist().get(script.name, {})
if skip.get("skip"):
pytest.skip(skip.get("reason", "skiplisted"))

result = subprocess.run(
[sys.executable, str(RUNNER), str(script)],
capture_output=True,
timeout=120,
)
assert result.returncode == 0, result.stderr.decode()[-3000:]
48 changes: 48 additions & 0 deletions tests/test_notebooks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#!/usr/bin/env python
"""
Slow test: run the book's chapter notebooks via notebook_runner and check
each one for erroring cells.

Wraps notebook_runner.run_notebook() as one pytest case per notebook, so a
failure names the notebook directly instead of just "notebooks failed".
Warnings are tolerated (recorded in the report, not asserted against);
only actual cell errors or a load/kernel-level failure fail the test.
Still writes the same tests/reports/latest.md as running
notebook_runner.py directly.
"""

from __future__ import annotations

from pathlib import Path

import pytest

import notebook_runner as nr

pytestmark = pytest.mark.slow

_results: list[nr.NotebookResult] = []


@pytest.mark.parametrize("notebook_name", nr.DEFAULT_NOTEBOOKS)
def test_notebook(notebook_name: str):
path = nr.NOTEBOOKS_DIR / notebook_name
if not path.exists():
pytest.skip(f"{path} not found")

skiplist = nr.load_skiplist().get(notebook_name, [])
result = nr.run_notebook(path, skiplist, timeout=300)
_results.append(result)

assert result.load_error is None, result.load_error
counts = result.counts()
errors = [c for c in result.cells if c.status == "error"]
detail = "; ".join(f"cell[{c.index}] {c.detail}" for c in errors)
assert counts["error"] == 0, detail


def test_write_report():
"""Defined after test_notebook, so pytest's default source-order
collection runs it last, once every notebook result is in."""
if _results:
nr.write_report(_results, Path(nr.REPORTS_DIR) / "latest.md")