Download testing/agent_evaluation/tests/test_cli_adapters.py from yuhanqin/ut-evaluation: direct link, hf CLI and curl.
- Browser
- Download file 8.46 kB
-
https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/agent_evaluation/tests/test_cli_adapters.py
- Command line
-
hf download hf://datasets/yuhanqin/ut-evaluation/testing/agent_evaluation/tests/test_cli_adapters.py
-
curl -L -o test_cli_adapters.py https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/agent_evaluation/tests/test_cli_adapters.py
8.46 kB
| import json | |
| import urllib.parse | |
| from pathlib import Path | |
| import pytest | |
| from agent_evaluation import cli | |
| from agent_evaluation.integrations.opencode import ( | |
| InteractiveOpenCodeAdapter, | |
| OpenCodeExportAdapter, | |
| project_opencode_export, | |
| ) | |
| from agent_evaluation.models import SkillBundle | |
| from agent_evaluation.datasets.models import EvaluationCase | |
| from agent_evaluation.config import SkillEvaluationConfig | |
| from .support import profile_text, write_canonical_dataset | |
| def _skill(tmp_path: Path) -> Path: | |
| root = tmp_path / "skill" | |
| root.mkdir() | |
| (root / "SKILL.md").write_text("---\nname: demo\n---\nDo the task.\n", encoding="utf-8") | |
| (root / "skill.yaml").write_text( | |
| profile_text(" execution: []\n trace:\n - id: trace_shape\n params: {}\n"), | |
| encoding="utf-8", | |
| ) | |
| return root | |
| def _dataset(tmp_path: Path) -> Path: | |
| return write_canonical_dataset(tmp_path / "dataset", [{ | |
| "case_id": "case-1", "input": "do it", | |
| "metadata": {"schema_version": "case-spec/v1"}, | |
| }]) | |
| def _export(path: Path, session_id: str = "ses-1") -> None: | |
| path.write_text(json.dumps({ | |
| "info": {"id": session_id, "directory": "/old/project"}, | |
| "messages": [ | |
| {"info": {"role": "assistant", "tokens": { | |
| "input": 3, "output": 5, "reasoning": 1, "total": 8, | |
| }, "finish": "stop"}, "parts": [{"type": "text", "text": "done"}]}, | |
| {"info": {"role": "assistant"}, "parts": [{"type": "tool", "tool": "bash", | |
| "state": {"status": "completed", "input": {"command": "echo hi"}, | |
| "output": "hi"}}]}, | |
| ], | |
| }), encoding="utf-8") | |
| def test_export_projection_is_explicit_and_keeps_tool_payload(tmp_path: Path): | |
| export = tmp_path / "export.json" | |
| _export(export) | |
| case = EvaluationCase("case-1", "do it", {}) | |
| artifact = project_opencode_export(export, case, trace_project="subject-test") | |
| assert artifact.status == "completed" | |
| assert artifact.trace_ref.to_dict() == {"project": "subject-test", "session_id": "ses-1"} | |
| assert artifact.output["final_output"] == "done" | |
| assert artifact.output["tool_calls"][0]["input"] == {"command": "echo hi"} | |
| assert artifact.metadata["task_workspace"] is None | |
| assert artifact.metadata["export_directory"] == "/old/project" | |
| def test_export_projection_rejects_bad_shape_and_session_mismatch(tmp_path: Path): | |
| path = tmp_path / "export.json" | |
| path.write_text("{}", encoding="utf-8") | |
| with pytest.raises(ValueError, match="info object"): | |
| project_opencode_export(path, EvaluationCase("case-1", "x", {}), trace_project="p") | |
| _export(path) | |
| with pytest.raises(ValueError, match="does not match"): | |
| project_opencode_export(path, EvaluationCase("case-1", "x", {}), trace_project="p", | |
| expected_session_id="ses-other") | |
| def test_export_adapter_does_not_use_export_directory_as_workspace(tmp_path: Path): | |
| export = tmp_path / "export.json" | |
| _export(export) | |
| adapter = OpenCodeExportAdapter(export, "subject-test") | |
| artifact = adapter.run(EvaluationCase("case-1", "x", {}), SkillBundle.load(_skill(tmp_path)), | |
| object()) | |
| assert artifact.execution.task_workspace is None | |
| assert artifact.trace_ref.project == "subject-test" | |
| def test_interactive_session_requests_bind_workspace(monkeypatch, tmp_path: Path): | |
| requests = [] | |
| class Response: | |
| status = 201 | |
| def __enter__(self): | |
| return self | |
| def __exit__(self, *_): | |
| return False | |
| def read(self): | |
| return b'{"id":"ses-created"}' | |
| def fake_urlopen(request, timeout): | |
| requests.append((request.full_url, request.get_method(), json.loads(request.data))) | |
| return Response() | |
| monkeypatch.setattr( | |
| "agent_evaluation.integrations.opencode.agent_adapter.urllib.request.urlopen", | |
| fake_urlopen, | |
| ) | |
| adapter = InteractiveOpenCodeAdapter(["opencode", "run"], server_url="http://127.0.0.1:4099") | |
| directory = tmp_path / "workspace" | |
| assert adapter._create_session(directory, "title") == "ses-created" | |
| adapter._send_prompt("ses-created", "hello", directory) | |
| assert requests[0][0].startswith("http://127.0.0.1:4099/session?") | |
| assert "directory=" in requests[0][0] | |
| assert requests[1][0].endswith("/prompt_async?directory=" + urllib.parse.quote(directory.as_posix(), safe="")) | |
| assert requests[1][2]["parts"][0]["text"] == "hello" | |
| # Model selection is sent through PromptRequest; attach itself does not | |
| # expose a --model flag in the installed OpenCode CLI. | |
| model_adapter = InteractiveOpenCodeAdapter( | |
| ["opencode", "run"], server_url="http://127.0.0.1:4099", model="provider/model-id" | |
| ) | |
| model_adapter._send_prompt("ses-created", "hello", directory) | |
| assert requests[2][2]["model"] == {"providerID": "provider", "modelID": "model-id"} | |
| def test_interactive_run_uses_attach_and_expected_export_session(monkeypatch, tmp_path: Path): | |
| skill_root = _skill(tmp_path) | |
| skill = SkillBundle.load(skill_root) | |
| case = EvaluationCase("case-1", "do it", {}) | |
| commands = [] | |
| export = {"info": {"id": "ses-created"}, "messages": [ | |
| {"info": {"role": "assistant", "finish": "stop"}, | |
| "parts": [{"type": "text", "text": "done"}]}, | |
| ]} | |
| adapter = InteractiveOpenCodeAdapter( | |
| ["/bin/opencode", "run"], run_root=tmp_path / "runs", | |
| server_url="http://127.0.0.1:4099", interactive_timeout=None, | |
| flush_wait_seconds=0, | |
| ) | |
| adapter.start = lambda: None | |
| adapter._create_session = lambda directory, title: "ses-created" | |
| adapter._send_prompt = lambda session_id, prompt, directory: None | |
| def fake_tui(command, **kwargs): | |
| commands.append(command) | |
| return type("Completed", (), {"returncode": 0})() | |
| def fake_export(session_id, target, process_env, cwd): | |
| assert session_id == "ses-created" | |
| target.write_text(json.dumps(export), encoding="utf-8") | |
| return target | |
| monkeypatch.setattr("agent_evaluation.integrations.opencode.agent_adapter.subprocess.run", fake_tui) | |
| adapter._export_session = fake_export | |
| artifact = adapter.run(case, skill, SkillEvaluationConfig.resolve(skill_root)) | |
| assert artifact.status == "completed" | |
| assert artifact.trace_ref.session_id == "ses-created" | |
| assert commands and commands[0][1] == "attach" | |
| assert "--session" in commands[0] and "ses-created" in commands[0] | |
| assert "--dir" in commands[0] and str(tmp_path / "runs" / "case-1" / artifact.run_id) in commands[0] | |
| assert "--model" not in commands[0] | |
| def test_cli_dispatches_evaluate_export_before_legacy_parser(monkeypatch, tmp_path: Path): | |
| skill = _skill(tmp_path) | |
| dataset = _dataset(tmp_path) | |
| export = tmp_path / "export.json" | |
| _export(export) | |
| captured = {} | |
| def fake_run(args, parser, adapter): | |
| captured["adapter"] = adapter | |
| return 0 | |
| monkeypatch.setattr(cli, "_run_loop", fake_run) | |
| result = cli.main(["evaluate-export", "--skill", str(skill), "--dataset", str(dataset), | |
| "--artifacts", str(tmp_path / "artifacts"), "--case-id", "case-1", | |
| "--export-json", str(export), "--trace-project", "subject-test"]) | |
| assert result == 0 | |
| assert isinstance(captured["adapter"], OpenCodeExportAdapter) | |
| def test_interactive_export_streams_to_file_and_validates_session(monkeypatch, tmp_path): | |
| adapter = InteractiveOpenCodeAdapter(["opencode", "run"]) | |
| document = {"info": {"id": "ses-large"}, "messages": [ | |
| {"info": {"role": "assistant", "finish": "stop"}, | |
| "parts": [{"type": "text", "text": "x" * 100000}]}]} | |
| encoded = json.dumps(document) | |
| def export(command, **kwargs): | |
| assert "capture_output" not in kwargs, "pipe stdout can truncate large OpenCode exports" | |
| assert kwargs["stdout"].fileno() >= 0 | |
| kwargs["stdout"].write(encoded) | |
| return type("Result", (), {"returncode": 0, "stderr": ""})() | |
| monkeypatch.setattr("agent_evaluation.integrations.opencode.agent_adapter.subprocess.run", export) | |
| target = tmp_path / "export.json" | |
| adapter._export_session("ses-large", target, {}, tmp_path) | |
| assert json.loads(target.read_text()) == document | |
| with pytest.raises(ValueError, match="does not match"): | |
| adapter._export_session("ses-other", target, {}, tmp_path) | |