Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
"""Tests for the benchmark runner functions.
This module tests run_benchmark, run_single_task, and run_interactive
which use the gym interface (make, reset, step, evaluate) directly.
"""
from pathlib import Path
import pytest
from cua_bench import (
BenchmarkResult,
DoneAction,
Task,
TaskResult,
run_benchmark,
run_interactive,
run_single_task,
)
# Simple HTML for test tasks
SIMPLE_BUTTON_HTML = """
<div class="flex flex-col items-center justify-center h-full w-full bg-gray-100 p-4">
<h1 class="text-xl mb-4">Test Task</h1>
<button
id="test-btn"
class="btn bg-blue-500 text-white px-4 py-2 rounded"
onclick="window.__clicked = true; window.__score = 1.0;"
>
Click Me
</button>
</div>
<script>
window.__clicked = false;
window.__score = 0.0;
</script>
"""
@pytest.fixture(autouse=True)
def _fake_sandboxes(monkeypatch):
"""Tasks run in a (fake, in-memory) sandbox: no container, no network."""
from cua_bench import sandboxes
from .fakes import FakeSDK
sdk = FakeSDK()
monkeypatch.setattr(sandboxes, "_sdk", sdk.pair)
for var in ("CUA_BENCH_ON", "CUA_BENCH_RUNTIME", "CUA_BENCH_IMAGE"):
monkeypatch.delenv(var, raising=False)
return sdk
class TestTaskResult:
"""Tests for TaskResult dataclass."""
def test_task_result_creation(self):
"""Test creating a TaskResult."""
result = TaskResult(
task_path="./task",
variant_id=0,
success=True,
reward=1.0,
steps=5,
)
assert result.task_path == "./task"
assert result.variant_id == 0
assert result.success is True
assert result.reward == 1.0
assert result.steps == 5
assert result.error is None
def test_task_result_with_error(self):
"""Test TaskResult with error."""
result = TaskResult(
task_path="./task",
variant_id=0,
success=False,
reward=0.0,
steps=0,
error="Task failed: timeout",
)
assert result.success is False
assert result.error == "Task failed: timeout"
class TestBenchmarkResult:
"""Tests for BenchmarkResult dataclass."""
def test_benchmark_result_creation(self):
"""Test creating a BenchmarkResult."""
result = BenchmarkResult(
run_id="test-run-123",
task_results=[
{"task_path": "./task1", "success": True, "reward": 1.0},
{"task_path": "./task2", "success": False, "reward": 0.0},
],
total_tasks=2,
success_count=1,
failed_count=1,
avg_reward=0.5,
duration_seconds=120.5,
)
assert result.run_id == "test-run-123"
assert result.total_tasks == 2
assert result.success_count == 1
assert result.failed_count == 1
assert result.avg_reward == 0.5
assert len(result.task_results) == 2
def test_benchmark_result_all_success(self):
"""Test BenchmarkResult with all successful tasks."""
result = BenchmarkResult(
run_id="success-run",
task_results=[{"success": True, "reward": 1.0} for _ in range(5)],
total_tasks=5,
success_count=5,
failed_count=0,
avg_reward=1.0,
duration_seconds=60.0,
)
assert result.success_count == result.total_tasks
assert result.failed_count == 0
def test_benchmark_result_all_failed(self):
"""Test BenchmarkResult with all failed tasks."""
result = BenchmarkResult(
run_id="failed-run",
task_results=[{"success": False, "reward": 0.0} for _ in range(3)],
total_tasks=3,
success_count=0,
failed_count=3,
avg_reward=0.0,
duration_seconds=30.0,
)
assert result.success_count == 0
assert result.failed_count == result.total_tasks
class TestRunSingleTaskE2E:
"""E2E tests for run_single_task function."""
@pytest.mark.asyncio
async def test_run_single_task_oracle(self, tmp_path):
"""Test run_single_task with oracle mode."""
task_dir = tmp_path / "task"
task_dir.mkdir()
(task_dir / "main.py").write_text(f'''
import cua_bench as cb
HTML = """{SIMPLE_BUTTON_HTML}"""
pid = None
@cb.tasks_config(split="train")
def get_tasks():
return [cb.Task(
description="Click the button",
computer={{"provider": "native", "setup_config": {{"os_type": "linux", "width": 800, "height": 600}}}}
)]
@cb.setup_task(split="train")
async def setup(task, session):
global pid
await session.write_file("/tmp/page.html", HTML)
pid = 1
@cb.solve_task(split="train")
async def solve(task, session):
global pid
await session.write_file("/tmp/clicked", "1")
@cb.evaluate_task(split="train")
async def evaluate(task, session):
global pid
clicked = await session.file_exists("/tmp/clicked")
return [1.0 if clicked else 0.0]
''')
result = await run_single_task(task_dir, oracle=True)
assert result.success is True
assert result.reward == 1.0
@pytest.mark.asyncio
async def test_run_single_task_with_agent(self, tmp_path):
"""Test run_single_task with custom agent that immediately finishes."""
task_dir = tmp_path / "task"
task_dir.mkdir()
(task_dir / "main.py").write_text(f'''
import cua_bench as cb
HTML = """{SIMPLE_BUTTON_HTML}"""
pid = None
@cb.tasks_config(split="train")
def get_tasks():
return [cb.Task(
description="Click the button",
computer={{"provider": "native", "setup_config": {{"os_type": "linux", "width": 800, "height": 600}}}}
)]
@cb.setup_task(split="train")
async def setup(task, session):
global pid
await session.write_file("/tmp/page.html", HTML)
pid = 1
@cb.evaluate_task(split="train")
async def evaluate(task, session):
global pid
clicked = await session.file_exists("/tmp/clicked")
return [1.0 if clicked else 0.0]
''')
def done_agent(screenshot: bytes, task: Task):
return DoneAction()
result = await run_single_task(task_dir, agent_fn=done_agent)
# Agent just returns DoneAction, so button won't be clicked
assert result.reward == 0.0
assert result.steps == 1
@pytest.mark.asyncio
async def test_run_single_task_failure(self):
"""Test run_single_task handles errors."""
result = await run_single_task(Path("/nonexistent/task"))
assert result.success is False
assert result.reward == 0.0
assert result.error is not None
class TestRunBenchmark:
"""Tests for run_benchmark function."""
@pytest.mark.asyncio
async def test_run_benchmark_not_found(self):
"""Test run_benchmark with non-existent dataset."""
with pytest.raises(FileNotFoundError, match="Dataset not found"):
await run_benchmark(Path("/nonexistent/dataset"))
@pytest.mark.asyncio
async def test_run_benchmark_empty_dataset(self, tmp_path):
"""Test run_benchmark with empty dataset."""
dataset_path = tmp_path / "empty"
dataset_path.mkdir()
with pytest.raises(ValueError, match="No tasks found"):
await run_benchmark(dataset_path)
@pytest.mark.asyncio
async def test_run_benchmark_task_filter_no_match(self, tmp_path):
"""Test run_benchmark with filter that matches nothing."""
dataset_path = tmp_path / "dataset"
dataset_path.mkdir()
task_dir = dataset_path / "my-task"
task_dir.mkdir()
(task_dir / "main.py").write_text("""
import cua_bench as cb
@cb.tasks_config(split="train")
def get_tasks():
return [cb.Task(description="Test")]
""")
with pytest.raises(ValueError, match="No tasks match filter"):
await run_benchmark(dataset_path, task_filter="nonexistent-*")
class TestRunBenchmarkE2E:
"""E2E tests for run_benchmark function."""
@pytest.mark.asyncio
async def test_run_benchmark_oracle(self, tmp_path):
"""Test run_benchmark with oracle mode."""
dataset_path = tmp_path / "dataset"
dataset_path.mkdir()
task_dir = dataset_path / "click-task"
task_dir.mkdir()
(task_dir / "main.py").write_text(f'''
import cua_bench as cb
HTML = """{SIMPLE_BUTTON_HTML}"""
pid = None
@cb.tasks_config(split="train")
def get_tasks():
return [cb.Task(
description="Click the button",
computer={{"provider": "native", "setup_config": {{"os_type": "linux", "width": 800, "height": 600}}}}
)]
@cb.setup_task(split="train")
async def setup(task, session):
global pid
await session.write_file("/tmp/page.html", HTML)
pid = 1
@cb.solve_task(split="train")
async def solve(task, session):
global pid
await session.write_file("/tmp/clicked", "1")
@cb.evaluate_task(split="train")
async def evaluate(task, session):
global pid
clicked = await session.file_exists("/tmp/clicked")
return [1.0 if clicked else 0.0]
''')
result = await run_benchmark(dataset_path, oracle=True, max_parallel=1)
assert isinstance(result, BenchmarkResult)
assert result.total_tasks == 1
assert result.success_count == 1
assert result.avg_reward == 1.0
@pytest.mark.asyncio
async def test_run_benchmark_task_filter(self, tmp_path):
"""Test run_benchmark with task filter."""
dataset_path = tmp_path / "dataset"
dataset_path.mkdir()
# Create multiple tasks
for name in ["click-task", "type-task", "other-task"]:
task_dir = dataset_path / name
task_dir.mkdir()
(task_dir / "main.py").write_text(f'''
import cua_bench as cb
HTML = """{SIMPLE_BUTTON_HTML}"""
pid = None
@cb.tasks_config(split="train")
def get_tasks():
return [cb.Task(
description="{name}",
computer={{"provider": "native", "setup_config": {{"os_type": "linux", "width": 800, "height": 600}}}}
)]
@cb.setup_task(split="train")
async def setup(task, session):
global pid
await session.write_file("/tmp/page.html", HTML)
pid = 1
@cb.solve_task(split="train")
async def solve(task, session):
global pid
await session.write_file("/tmp/clicked", "1")
@cb.evaluate_task(split="train")
async def evaluate(task, session):
global pid
clicked = await session.file_exists("/tmp/clicked")
return [1.0 if clicked else 0.0]
''')
# Run with filter matching only click-task
result = await run_benchmark(
dataset_path,
oracle=True,
task_filter="click-*",
max_parallel=1,
)
assert result.total_tasks == 1
class TestRunInteractiveE2E:
"""E2E tests for run_interactive function."""
@pytest.mark.asyncio
async def test_run_interactive_returns_env(self, tmp_path):
"""Test run_interactive returns environment."""
task_dir = tmp_path / "task"
task_dir.mkdir()
(task_dir / "main.py").write_text(f'''
import cua_bench as cb
HTML = """{SIMPLE_BUTTON_HTML}"""
pid = None
@cb.tasks_config(split="train")
def get_tasks():
return [cb.Task(
description="Interactive task",
computer={{"provider": "native", "setup_config": {{"os_type": "linux", "width": 800, "height": 600}}}}
)]
@cb.setup_task(split="train")
async def setup(task, session):
global pid
await session.write_file("/tmp/page.html", HTML)
pid = 1
''')
env, screenshot, task_cfg = await run_interactive(task_dir)
try:
assert env is not None
assert isinstance(screenshot, bytes)
assert len(screenshot) > 0
assert task_cfg.description == "Interactive task"
finally:
await env.close()
class TestEvaluatorRewardFailClosed:
@pytest.mark.asyncio
@pytest.mark.parametrize("value", [[1.0, float("nan")], [1.0, "bad"], [1.0, 1.5]])
async def test_invalid_secondary_reward_cannot_claim_success(
self, tmp_path, monkeypatch, value
):
from types import SimpleNamespace
import cua_bench.runners as runners
class FakeEnvironment:
evaluate_task_fn = object()
solve_task_fn = None
async def reset(self, task_id=0):
return b"screen", SimpleNamespace()
async def step(self, action):
return b"screen"
async def evaluate(self):
return value
async def close(self):
pass
monkeypatch.setattr(runners, "make", lambda *args, **kwargs: FakeEnvironment())
result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())
assert result.success is False
assert result.reward == 0.0
assert result.error is not None
@pytest.mark.asyncio
@pytest.mark.parametrize("value", ["1.0", None, float("nan"), float("inf"), -0.1, 1.1])
async def test_invalid_reward_cannot_claim_success(self, tmp_path, monkeypatch, value):
from types import SimpleNamespace
import cua_bench.runners as runners
class FakeEnvironment:
evaluate_task_fn = object()
solve_task_fn = None
async def reset(self, task_id=0):
return b"screen", SimpleNamespace()
async def step(self, action):
return b"screen"
async def evaluate(self):
return value
async def close(self):
pass
monkeypatch.setattr(runners, "make", lambda *args, **kwargs: FakeEnvironment())
result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())
assert result.success is False
assert result.reward == 0.0
assert result.error is not None
@pytest.mark.asyncio
@pytest.mark.parametrize(
"value, reward",
[
(True, 1.0),
(False, 0.0),
([1.0, True], 1.0),
({"reward": True}, 1.0),
(0.75, 0.75),
({"reward": 1.0}, 1.0),
],
)
async def test_valid_reward(self, tmp_path, monkeypatch, value, reward):
from types import SimpleNamespace
import cua_bench.runners as runners
class FakeEnvironment:
evaluate_task_fn = object()
async def reset(self, task_id=0):
return b"screen", SimpleNamespace()
async def step(self, action):
return b"screen"
async def evaluate(self):
return value
async def close(self):
pass
monkeypatch.setattr(runners, "make", lambda *args, **kwargs: FakeEnvironment())
result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())
assert result.success is (reward >= 0.5)
assert result.reward == reward
assert result.error is None
@pytest.mark.asyncio
async def test_missing_evaluator_cannot_claim_success(self, tmp_path, monkeypatch):
from types import SimpleNamespace
import cua_bench.runners as runners
class FakeEnvironment:
evaluate_task_fn = None
solve_task_fn = None
async def reset(self, task_id=0):
return b"screen", SimpleNamespace()
async def step(self, action):
return b"screen"
async def close(self):
pass
monkeypatch.setattr(runners, "make", lambda *args, **kwargs: FakeEnvironment())
result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())
assert result.success is False
assert result.error is not None
@pytest.mark.asyncio
async def test_setup_only_cannot_claim_success_even_if_evaluator_would_pass(
self, tmp_path, monkeypatch
):
from types import SimpleNamespace
import cua_bench.runners as runners
calls = {"evaluated": False, "closed": False}
class AlreadySatisfied:
evaluate_task_fn = object()
solve_task_fn = None
async def reset(self, task_id=0):
return b"screen", SimpleNamespace()
async def evaluate(self):
calls["evaluated"] = True
return 1.0
async def close(self):
calls["closed"] = True
monkeypatch.setattr(runners, "make", lambda *args, **kwargs: AlreadySatisfied())
result = await runners.run_single_task(tmp_path)
assert result.success is False
assert result.reward == 0.0
assert "No agent_fn" in result.error
assert calls["evaluated"] is False
assert calls["closed"] is True
@pytest.mark.asyncio
async def test_cleanup_failure_revokes_success_and_keeps_steps(self, tmp_path, monkeypatch):
from types import SimpleNamespace
import cua_bench.runners as runners
class FailedCleanup:
evaluate_task_fn = object()
solve_task_fn = None
async def reset(self, task_id=0):
return b"screen", SimpleNamespace()
async def step(self, action):
return b"screen"
async def evaluate(self):
return 1.0
async def close(self):
raise RuntimeError("injected close failure")
monkeypatch.setattr(runners, "make", lambda *a, **k: FailedCleanup())
result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())
assert result.success is False
assert result.reward == 0.0
assert result.steps == 1
assert "Environment cleanup failed" in result.error
@pytest.mark.asyncio
async def test_mid_execution_failure_retains_completed_step_count(self, tmp_path, monkeypatch):
from types import SimpleNamespace
import cua_bench.runners as runners
class FailedStep:
solve_task_fn = None
def __init__(self):
self.calls = 0
self.closed = False
async def reset(self, task_id=0):
return b"screen", SimpleNamespace()
async def step(self, action):
self.calls += 1
if self.calls == 3:
raise RuntimeError("injected third step failure")
return b"screen"
async def close(self):
self.closed = True
env = FailedStep()
monkeypatch.setattr(runners, "make", lambda *a, **k: env)
result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: object(), max_steps=4)
assert result.success is False
assert result.steps == 2
assert "third step failure" in result.error
assert env.closed is True
@pytest.mark.asyncio
@pytest.mark.parametrize("budget", [0, -1, False, True, 1.5, "2"])
async def test_invalid_step_budget_cannot_score_initial_state(
self, tmp_path, monkeypatch, budget
):
import cua_bench.runners as runners
def forbidden_make(*args, **kwargs):
raise AssertionError("must reject before creating a task environment")
monkeypatch.setattr(runners, "make", forbidden_make)
with pytest.raises(ValueError, match="max_steps must be a positive integer"):
await runners.run_single_task(
tmp_path, agent_fn=lambda *_: DoneAction(), max_steps=budget
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"value",
[
{"reward": None},
{"reward": "1.0"},
{"reward": float("nan")},
{"reward": float("inf")},
{"reward": -0.1},
{"reward": 1.1},
{"score": 1.0},
],
)
async def test_invalid_mapping_reward_cannot_claim_success(self, tmp_path, monkeypatch, value):
from types import SimpleNamespace
import cua_bench.runners as runners
class FakeEnvironment:
evaluate_task_fn = object()
solve_task_fn = None
async def reset(self, task_id=0):
return b"screen", SimpleNamespace()
async def step(self, action):
return b"screen"
async def evaluate(self):
return value
async def close(self):
pass
monkeypatch.setattr(runners, "make", lambda *a, **k: FakeEnvironment())
result = await runners.run_single_task(tmp_path, agent_fn=lambda *_: DoneAction())
assert result.success is False
assert result.reward == 0.0
assert result.error is not None
class TestBenchmarkDiscoveryFailClosed:
@pytest.mark.asyncio
@pytest.mark.parametrize("parallel", [0, -1, True, 1.5, "2"])
async def test_invalid_parallelism_rejected_before_task_discovery(self, tmp_path, parallel):
import cua_bench.runners as runners
with pytest.raises(ValueError, match="max_parallel must be a positive integer"):
await runners.run_benchmark(tmp_path, max_parallel=parallel)
@pytest.mark.asyncio
@pytest.mark.parametrize("limit", [0, -1, True, 1.5, "2"])
async def test_invalid_variant_limit_rejected(self, tmp_path, limit):
import cua_bench.runners as runners
with pytest.raises(ValueError, match="max_variants must be a positive integer"):
await runners.run_benchmark(tmp_path, max_variants=limit)
@pytest.mark.asyncio
async def test_variant_discovery_failure_is_not_silently_scored(self, tmp_path, monkeypatch):
import cua_bench.runners as runners
task_dir = tmp_path / "task"
task_dir.mkdir()
(task_dir / "main.py").write_text("# fixture\n")
def broken_make(*args, **kwargs):
raise RuntimeError("invalid task fixture")
monkeypatch.setattr(runners, "make", broken_make)
with pytest.raises(RuntimeError, match="Unable to discover variants"):
await runners.run_benchmark(tmp_path, oracle=True)
@pytest.mark.asyncio
async def test_discovery_environment_is_closed_before_execution(self, tmp_path, monkeypatch):
import cua_bench.runners as runners
task_dir = tmp_path / "task"
task_dir.mkdir()
(task_dir / "main.py").write_text("# fixture\n")
calls = {"closed": 0}
class DiscoveryEnvironment:
def tasks_config_fn(self):
return [object()]
async def close(self):
calls["closed"] += 1
def make_for_discovery(*args, **kwargs):
return DiscoveryEnvironment()
async def fake_run(*args, **kwargs):
assert calls["closed"] == 1
return runners.TaskResult(
task_path=str(task_dir),
variant_id=0,
success=False,
reward=0.0,
steps=0,
error="not executed",
)
monkeypatch.setattr(runners, "make", make_for_discovery)
monkeypatch.setattr(runners, "run_single_task", fake_run)
await runners.run_benchmark(tmp_path)
assert calls["closed"] == 1
@pytest.mark.asyncio
async def test_discovery_cleanup_failure_blocks_benchmark(self, tmp_path, monkeypatch):
import cua_bench.runners as runners
task_dir = tmp_path / "task"
task_dir.mkdir()
(task_dir / "main.py").write_text("# fixture\n")
class DiscoveryEnvironment:
def tasks_config_fn(self):
return [object()]
async def close(self):
raise RuntimeError("cleanup failure")
monkeypatch.setattr(runners, "make", lambda *a, **k: DiscoveryEnvironment())
with pytest.raises(RuntimeError, match="Unable to close discovery environment"):
await runners.run_benchmark(tmp_path)