ut-evaluation / testing /agent_evaluation /tests /test_structure_migration.py
Codex
Replace the dataset with the current testing tree and the three UT docs.
d26f22a
Raw History Blame Contribute Delete
9.64 kB
"""Regression checks for the flattened native runtime; no real agents run here."""
import html
import json
import os
from pathlib import Path
import subprocess
import pty
from urllib.parse import unquote
import re
import pytest
from agent_evaluation import cli
from agent_evaluation.backend.config import DEFAULT_DATABASE
from agent_evaluation.models import TaskArtifact, ScoreRecord, score_statistics
from agent_evaluation.reporting.models import ReportData
from agent_evaluation.backend.views import report_data_from_experiment
from agent_evaluation.reporting.render import render_evaluation_document
from .test_render import renderer_example_result
ROOT = Path(__file__).parents[1]
def test_default_database_is_project_local():
assert DEFAULT_DATABASE == ROOT / "workspace/native/evaluation.sqlite"
@pytest.mark.parametrize("mode", ["headless", "interactive", "evaluate-export"])
def test_cli_modes_share_assembly_and_normalize_cases(mode, tmp_path, monkeypatch):
captured = []
monkeypatch.setattr(cli, "DEFAULT_ENV_FILE", tmp_path / "absent.env")
monkeypatch.delenv("SKILL_EVAL_ENV_FILE", raising=False)
monkeypatch.setattr(cli, "_profile_requires_trace", lambda args: False)
monkeypatch.setattr(cli, "OpenCodeExportAdapter", lambda *args, **kwargs: object())
monkeypatch.setattr(cli, "_make_opencode_adapter", lambda *args, **kwargs: object())
monkeypatch.setattr(cli, "_run_loop", lambda args, parser, adapter: captured.append(args) or 0)
args = ["--skill", "skill", "--dataset", "dataset", "--artifacts", "artifacts", "--case-id", "one"]
if mode == "headless":
args += ["--case-id", "two", "--limit", "1"]
else:
args = [mode, *args, "--case-id", "overridden"]
if mode == "evaluate-export":
args += ["--export-json", "export.json"]
assert cli.main(args) == 0
assert captured[0].case_ids == (["one", "two"] if mode == "headless" else ["overridden"])
assert getattr(captured[0], "limit", None) == (1 if mode == "headless" else None)
@pytest.mark.parametrize("mode,option", [("interactive", "--limit"), ("evaluate-export", "--limit"),
("interactive", "--opencode-auto-approve")])
def test_cli_rejects_mode_inapplicable_options(mode, option, monkeypatch, tmp_path):
monkeypatch.setattr(cli, "DEFAULT_ENV_FILE", tmp_path / "absent")
monkeypatch.delenv("SKILL_EVAL_ENV_FILE", raising=False)
args = [mode, "--skill", "s", "--dataset", "d", "--artifacts", "a", "--case-id", "c", option]
if option == "--limit":
args.append("1")
if mode == "evaluate-export":
args += ["--export-json", "e"]
with pytest.raises(SystemExit) as exc:
cli.main(args)
assert exc.value.code == 2
def test_shell_credentials_do_not_require_dotenv_but_explicit_file_does(tmp_path, monkeypatch):
missing = tmp_path / "absent.env"
monkeypatch.setattr(cli, "DEFAULT_ENV_FILE", missing)
monkeypatch.delenv("SKILL_EVAL_ENV_FILE", raising=False)
monkeypatch.setenv("SKILL_EVAL_LLM_MODEL", "shell-model")
assert cli._load_environment([]) == missing
assert os.environ["SKILL_EVAL_LLM_MODEL"] == "shell-model"
monkeypatch.setenv("SKILL_EVAL_ENV_FILE", str(missing))
with pytest.raises(SystemExit):
cli._load_environment([])
@pytest.mark.parametrize("script", sorted((ROOT / "scripts").iterdir()), ids=lambda p: p.name)
def test_scripts_cannot_replace_a_sourcing_shell(script):
result = subprocess.run(["bash", "--noprofile", "--norc", "-c",
'source "$1"; status=$?; echo "survived:$status"', "check", str(script)],
text=True, capture_output=True)
assert result.returncode == 0
assert "survived:2" in result.stdout
assert "do not source" in result.stderr
def test_example_scripts_forward_overrides_without_worktree_env_fallback():
for script in (ROOT / "scripts").glob("run-*-example"):
source = script.read_text()
assert '"$@"' in source
assert "git-common-dir" not in source
assert 'if [[ ! -f "$ENV_FILE" ]]' not in source
assert "export NO_PROXY=" not in source
@pytest.mark.parametrize("name", ["run-interactive-example", "run-export-example"])
def test_example_forwarding_reaches_cli_process(name, tmp_path):
capture = tmp_path / "argv"
executable = tmp_path / "python"
executable.write_text('#!/bin/bash\nprintf "%s\\n" "$@" > "$CAPTURE"\n')
executable.chmod(0o700)
curl = tmp_path / "curl"
curl.write_text('#!/bin/bash\nprintf "%s\\n" "$@" > "$CURL_CAPTURE"\n')
curl.chmod(0o700)
env = {**os.environ, "SKILL_EVAL_PYTHON": str(executable), "EXPORT_JSON": "unused-export",
"PATH": f"{tmp_path}:{os.environ.get('PATH', '')}", "CAPTURE": str(capture),
"CURL_CAPTURE": str(tmp_path / "curl-argv"), "SKILL": "/missing/default-skill"}
env.pop("ENV_FILE", None)
env.pop("SKILL_EVAL_ENV_FILE", None)
master, slave = pty.openpty()
try:
completed = subprocess.run([str(ROOT / "scripts" / name), "--skill", str(tmp_path),
"--backend-endpoint=http://127.0.0.1:9999", "--llm-timeout", "17"],
stdin=slave, stdout=slave, stderr=subprocess.PIPE, env=env, timeout=10)
assert completed.returncode == 0, completed.stderr.decode()
finally:
os.close(slave)
os.close(master)
args = capture.read_text().splitlines()
assert args[:3] == ["-m", "agent_evaluation.cli", "interactive" if "interactive" in name else "evaluate-export"]
assert args[-5:] == ["--skill", str(tmp_path), "--backend-endpoint=http://127.0.0.1:9999", "--llm-timeout", "17"]
assert "--env-file" not in args
if "interactive" in name:
curl_args = (tmp_path / "curl-argv").read_text().splitlines()
assert curl_args[:2] == ["--noproxy", "*"]
assert curl_args[-1] == "http://127.0.0.1:9999/api/health"
def test_typed_params_and_no_foreign_evaluator_facade_exports():
from agent_evaluation import evaluators
from agent_evaluation.evaluators import ExpectedFilesParams
params = ExpectedFilesParams(("result.md",))
assert params.expected_files == ("result.md",)
assert params.to_dict() == {"expected_files": ["result.md"]}
assert not hasattr(params, "get")
with pytest.raises(TypeError):
params["expected_files"]
assert not hasattr(evaluators, "TraceStore")
assert not hasattr(evaluators, "SkillEvaluationConfig")
def test_report_memory_and_persisted_score_parity():
example = renderer_example_result()
run = TaskArtifact("run", "synthetic-case", "completed", {"final_output": "<text>"})
memory = ReportData(example.experiment_id, (run,), example.scores, example.inputs,
{"name": "native", "experiment_id": example.experiment_id,
"metadata": example.backend["metadata"]})
persisted = report_data_from_experiment(json.loads(json.dumps({
"id": example.experiment_id, "runs": [run.to_dict()],
"scores": [s.to_dict() for s in example.scores], "inputs": {},
"backend_metadata": dict(example.backend["metadata"]),
})))
assert score_statistics(memory.scores) == score_statistics(persisted.scores)
assert [s.to_dict() for s in memory.scores] == [s.to_dict() for s in persisted.scores]
assert memory.backend["metadata"] == persisted.backend["metadata"]
assert render_evaluation_document(memory) == render_evaluation_document(persisted)
document = render_evaluation_document(persisted)
assert "task-artifact.json" not in document
assert "synthetic-case" in document and "completed" in document
assert "Synthetic publication warning" in html.unescape(document)
@pytest.mark.parametrize("score", renderer_example_result().scores)
def test_score_record_owns_flat_audit_roundtrip(score):
document = json.loads(json.dumps(score.to_dict()))
assert ScoreRecord.from_dict(document).to_dict() == document
def test_renderer_only_accepts_report_data_and_has_no_writing_interface():
from agent_evaluation.reporting import render
assert not hasattr(render, "render_evaluation_report")
assert not hasattr(ReportData, "from_result")
assert not hasattr(ReportData, "from_experiment")
with pytest.raises(TypeError, match="ReportData"):
render_evaluation_document({"id": "not-a-report"})
@pytest.mark.parametrize("url", ["javascript:alert(1)", "//host/path", "file:///etc/passwd", "/etc/passwd", "x\nfoo", "https://host", "\\\\host"])
def test_report_rejects_unsafe_task_links(url):
example = renderer_example_result()
report = ReportData(example.experiment_id, (TaskArtifact("run", "<case>", "completed", {}),),
example.scores, example.inputs, example.backend)
document = render_evaluation_document(report, task_links={"run": url})
assert "task-artifact.json</a>" not in document
assert "&lt;case&gt;" in document
def test_static_task_links_resolve_to_written_artifacts(tmp_path):
from .test_loop import _fixture, _loop
from agent_evaluation.integrations.simulator import SimulatorAdapter
skill, dataset = _fixture(tmp_path)
result = _loop(SimulatorAdapter()).run(skill, dataset, tmp_path / "artifacts", evolve=False)
index = tmp_path / "artifacts" / result.experiment_id / "report/index.html"
links = re.findall(r'href="([^"]+task-artifact.json)"', index.read_text())
assert len(links) == len(result.runs)
assert all((index.parent / unquote(html.unescape(link))).is_file() for link in links)