from pathlib import Path from chemenu.evals.loader import load_eval_set from chemenu.evals.model import ResponseError from chemenu.evals.runner import format_report, run_eval_set EVAL_YAML = """\ name: "demo" threshold: 0.8 output_model: "chemenu.evals.example:ExampleOutput" """ CASE_YAML = """\ input: text: "Hallo" expect: - grader: "equals" path: "/language" value: "de" - grader: "contains" path: "/entities" items: ["a"] """ GOOD = '{"language": "de", "entities": ["a"]}' HALF = '{"language": "en", "entities": ["a"]}' def make_set(root: Path, cases: list[str]) -> Path: (root / "cases").mkdir(parents=True) (root / "eval.yaml").write_text(EVAL_YAML, encoding="utf-8") for stem in cases: (root / "cases" / f"{stem}.yaml").write_text(CASE_YAML, encoding="utf-8") return root class FakeResponses: def __init__(self, data: dict[str, str]) -> None: self._data = data def response_for(self, case_id: str) -> str | None: return self._data.get(case_id) def test_scores_every_case(tmp_path: Path) -> None: eval_set = load_eval_set(make_set(tmp_path, ["b", "a"])) result = run_eval_set(eval_set, FakeResponses({"a": GOOD, "b": HALF})) assert result.name == "demo" assert result.threshold == 0.8 assert [c.case_id for c in result.cases] == ["a", "b"] assert [c.score for c in result.cases] == [1.0, 0.5] assert not result.passed def test_report_lists_cases_and_total(tmp_path: Path) -> None: eval_set = load_eval_set(make_set(tmp_path, ["a", "b", "c"])) result = run_eval_set(eval_set, FakeResponses({"a": GOOD, "b": HALF, "c": "{bad"})) lines = format_report(result).splitlines() assert lines[0] == "PASS a 1.00" assert lines[1].startswith("FAIL b 0.50 equals /language: ") assert lines[2].startswith("FAIL c 0.00 invalid response: ") assert not result.passed assert lines[-1] == "demo: 1/3 passed, mean 0.50, threshold 0.8" assert len(lines) == 4 assert all(line == line.rstrip() for line in lines) class _Unreadable: def response_for(self, case_id: str) -> str | None: raise ResponseError(f"{case_id}.json: boom") def test_unreadable_response_fails_case(tmp_path: Path) -> None: eval_set = load_eval_set(make_set(tmp_path, ["a"])) result = run_eval_set(eval_set, _Unreadable()) assert not result.passed assert result.cases[0].error == "cannot read response: a.json: boom" assert result.cases[0].score == 0.0