Files
VibemakerSandbox/hardware/unoq/python/tests/test_deploy.py
T

198 lines
8.2 KiB
Python

import io
import json
import shutil
import sys
import threading
import urllib.error
import urllib.request
import zipfile
from pathlib import Path
import pytest
PYTHON_ROOT = Path(__file__).resolve().parents[1]
UNOQ_ROOT = PYTHON_ROOT.parent
if str(PYTHON_ROOT) not in sys.path:
sys.path.insert(0, str(PYTHON_ROOT))
from core.config import load_hardware_profile, load_robot_manifest # noqa: E402
from core.controller import MicroduckController # noqa: E402
from core.deploy_service import DeployService # noqa: E402
from core.policy_runner import PolicySet # noqa: E402
from hal.mock_hal import MockHal # noqa: E402
from web.fallback_server import FallbackWebServer # noqa: E402
def _make_runtime_dir(tmp_path: Path) -> tuple[Path, MicroduckController]:
base = tmp_path / "unoq"
(base / "config").mkdir(parents=True)
(base / "policies").mkdir(parents=True)
shutil.copy2(UNOQ_ROOT / "config" / "robot_manifest.json", base / "config" / "robot_manifest.json")
shutil.copy2(UNOQ_ROOT / "config" / "hardware_profile.json", base / "config" / "hardware_profile.json")
manifest = load_robot_manifest(base / "config" / "robot_manifest.json")
profile = load_hardware_profile(base / "config" / "hardware_profile.json")
profile["joints"]["left_hip_yaw"]["zero_offset_ticks"] = 77
from core.config import save_hardware_profile
save_hardware_profile(base / "config" / "hardware_profile.json", profile, manifest["joint_names"])
for skill in manifest["skills"].values():
(base / skill["path"]).write_bytes(b"MOCK_ONNX_V1")
hal = MockHal()
policies = PolicySet.load_from_manifest(base, manifest, backend="dummy")
ctrl = MicroduckController(base_dir=base, manifest=manifest, profile=profile, hal=hal, policies=policies)
ctrl.connect()
return base, ctrl
def _build_zip_bytes(
manifest: dict,
files: dict[str, bytes] | None = None,
profile: dict | None = None,
custom_script: dict | None = None,
prefix: str = "",
) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
zf.writestr(f"{prefix}config/robot_manifest.json", json.dumps(manifest))
if profile is not None:
zf.writestr(f"{prefix}config/hardware_profile.json", json.dumps(profile))
if custom_script is not None:
zf.writestr(f"{prefix}config/custom_move_script.json", json.dumps(custom_script))
if files is not None:
for rel, data in files.items():
zf.writestr(f"{prefix}{rel}", data)
else:
for skill in manifest.get("skills", {}).values():
zf.writestr(f"{prefix}{skill['path']}", b"MOCK_ONNX_V2")
return buf.getvalue()
def test_deploy_service_applies_valid_zip_and_preserves_profile_by_default(tmp_path: Path):
base, ctrl = _make_runtime_dir(tmp_path)
deploy = DeployService(base_dir=base, controller=ctrl, policy_backend="dummy")
manifest = load_robot_manifest(base / "config" / "robot_manifest.json")
manifest["variants"]["rollers"]["enabled"] = True
manifest["skills"]["drive"] = {
"path": "policies/drive.onnx",
"kind": "perpetual",
"slot": "drive",
"action_scale": 1.0,
}
incoming_profile = load_hardware_profile(base / "config" / "hardware_profile.json")
incoming_profile["joints"]["left_hip_yaw"]["zero_offset_ticks"] = 0
custom_script = {
"name": "wave",
"durationS": 1.0,
"loop": True,
"keyframes": [{"t": 0.0, "cmd": [0.1] + [0.0] * 12}],
}
manifest["custom_move"] = {"name": "wave", "slot": "script", "type": "script"}
zip_bytes = _build_zip_bytes(manifest, profile=incoming_profile, custom_script=custom_script, prefix="microduck_unoq/")
result = deploy.apply_zip_bytes(zip_bytes, overwrite_profile=False)
assert result["ok"] is True
assert "drive" in result["loaded_skills"]
# On-robot calibration must be preserved unless overwrite_profile=True
assert ctrl.profile["joints"]["left_hip_yaw"]["zero_offset_ticks"] == 77
assert ctrl.state_machine.rollers_enabled is True
assert ctrl.state_machine.custom_script["name"] == "wave"
assert (base / "policies" / "drive.onnx").read_bytes() == b"MOCK_ONNX_V2"
# Now deploy with overwrite_profile=True
result2 = deploy.apply_zip_bytes(zip_bytes, overwrite_profile=True)
assert result2["ok"] is True
assert ctrl.profile["joints"]["left_hip_yaw"]["zero_offset_ticks"] == 0
def test_deploy_service_rejects_traversal_and_invalid_manifest(tmp_path: Path):
base, ctrl = _make_runtime_dir(tmp_path)
deploy = DeployService(base_dir=base, controller=ctrl, policy_backend="dummy")
manifest = load_robot_manifest(base / "config" / "robot_manifest.json")
# 1) Path traversal inside zip must be rejected without touching files
bad_buf = io.BytesIO()
with zipfile.ZipFile(bad_buf, "w") as zf:
zf.writestr("../evil.txt", b"pwn")
zf.writestr("config/robot_manifest.json", json.dumps(manifest))
with pytest.raises(ValueError):
deploy.apply_zip_bytes(bad_buf.getvalue())
assert not (base.parent / "evil.txt").exists()
# 2) Wrong obs_size must be rejected
bad_manifest = dict(manifest)
bad_manifest["obs_size"] = 99
with pytest.raises(ValueError):
deploy.apply_zip_bytes(_build_zip_bytes(bad_manifest))
# 3) Missing skill onnx file referenced in manifest must be rejected
partial_files = {"policies/stand.onnx": b"MOCK_ONNX"} # walk.onnx missing
with pytest.raises(ValueError):
deploy.apply_zip_bytes(_build_zip_bytes(manifest, files=partial_files))
def test_fallback_http_server_status_deploy_control_and_mobile_ui(tmp_path: Path):
base, ctrl = _make_runtime_dir(tmp_path)
deploy = DeployService(base_dir=base, controller=ctrl, policy_backend="dummy")
server = FallbackWebServer(host="127.0.0.1", port=0, controller=ctrl, deploy_service=deploy)
port = server.port
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
# 1) Mobile index page
with urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=3) as resp:
html = resp.read().decode("utf-8")
assert resp.status == 200
assert "Microduck" in html
assert "E-STOP" in html
# 2) Initial status
with urllib.request.urlopen(f"http://127.0.0.1:{port}/api/status", timeout=3) as resp:
status = json.loads(resp.read().decode("utf-8"))
assert status["lifecycle"] == "IDLE"
assert "walk" in status["loaded_skills"]
# 3) HTTP push hot deploy (raw application/zip)
manifest = load_robot_manifest(base / "config" / "robot_manifest.json")
manifest["variants"]["rollers"]["enabled"] = True
manifest["skills"]["drive"] = {
"path": "policies/drive.onnx",
"kind": "perpetual",
"slot": "drive",
"action_scale": 1.0,
}
zip_bytes = _build_zip_bytes(manifest)
req = urllib.request.Request(
f"http://127.0.0.1:{port}/api/deploy?overwrite_profile=0",
data=zip_bytes,
method="POST",
headers={"Content-Type": "application/zip"},
)
with urllib.request.urlopen(req, timeout=5) as resp:
deployed = json.loads(resp.read().decode("utf-8"))
assert resp.status == 200
assert deployed["ok"] is True
assert "drive" in deployed["loaded_skills"]
# 4) Stand + step + E-STOP over HTTP
req_stand = urllib.request.Request(f"http://127.0.0.1:{port}/api/stand", data=b"{}", method="POST")
with urllib.request.urlopen(req_stand, timeout=3) as resp:
st = json.loads(resp.read().decode("utf-8"))
assert st["lifecycle"] == "SOFT_START"
ctrl.step_once(dt=0.02)
req_estop = urllib.request.Request(f"http://127.0.0.1:{port}/api/estop", data=b"{}", method="POST")
with urllib.request.urlopen(req_estop, timeout=3) as resp:
st2 = json.loads(resp.read().decode("utf-8"))
assert st2["lifecycle"] == "IDLE"
assert ctrl.profile["joints"]["left_hip_yaw"]["zero_offset_ticks"] == 77
finally:
server.shutdown()
server.server_close()