Files
chemenu-ng/tests/evals/test_loader.py
T
torbenandClaude Sonnet 5.5 9a7dc6ceb3 Add reference grader with set comparison and text normalisation
Compares answer lists against a reference as sets with precision and recall minimums; text is casefolded, NFC and whitespace normalised.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-04 23:02:45 +01:00

183 lines
6.2 KiB
Python

from pathlib import Path
import pytest
from chemenu.evals.example import ExampleOutput
from chemenu.evals.loader import EvalSetError, RecordedResponses, load_eval_set
from chemenu.evals.model import ContainsCheck, EqualsCheck, ResponseError
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"]
"""
def make_set(root: Path, eval_yaml: str = EVAL_YAML, cases: dict[str, str] | None = None) -> Path:
root.mkdir(parents=True, exist_ok=True)
(root / "eval.yaml").write_text(eval_yaml, encoding="utf-8")
(root / "cases").mkdir(exist_ok=True)
selected = cases if cases is not None else {"b": CASE_YAML, "a": CASE_YAML}
for stem, text in selected.items():
(root / "cases" / f"{stem}.yaml").write_text(text, encoding="utf-8")
return root
def test_loads_cases_sorted_by_file_stem(tmp_path: Path) -> None:
root = make_set(tmp_path, cases={"b": CASE_YAML, "a": CASE_YAML, "c": CASE_YAML})
eval_set = load_eval_set(root)
assert eval_set.name == "demo"
assert eval_set.threshold == 0.8
assert eval_set.output_model is ExampleOutput
assert [case.id for case in eval_set.cases] == ["a", "b", "c"]
assert isinstance(eval_set.cases, tuple)
@pytest.mark.parametrize(
"output_model",
[
"nocolon",
"no.such.module:X",
"chemenu.evals.example:Missing",
"pathlib:Path",
],
)
def test_unknown_output_model_raises(tmp_path: Path, output_model: str) -> None:
eval_yaml = EVAL_YAML.replace("chemenu.evals.example:ExampleOutput", output_model)
with pytest.raises(EvalSetError, match="output_model"):
load_eval_set(make_set(tmp_path, eval_yaml))
def test_empty_set_raises(tmp_path: Path) -> None:
with pytest.raises(EvalSetError, match="cases"):
load_eval_set(make_set(tmp_path, cases={}))
def test_missing_cases_dir_raises(tmp_path: Path) -> None:
(tmp_path / "eval.yaml").write_text(EVAL_YAML, encoding="utf-8")
with pytest.raises(EvalSetError, match="cases"):
load_eval_set(tmp_path)
def test_missing_eval_yaml_raises(tmp_path: Path) -> None:
with pytest.raises(EvalSetError, match=r"eval\.yaml"):
load_eval_set(tmp_path)
@pytest.mark.parametrize(
"bad",
[
"input: [",
"- just\n- a list\n",
'input: {}\nexpect: []\nid: "x"\n',
'input: {}\nexpect: [{grader: "nope"}]\n',
],
)
def test_invalid_case_raises(tmp_path: Path, bad: str) -> None:
root = make_set(tmp_path, cases={"bad": bad})
with pytest.raises(EvalSetError, match=r"bad\.yaml") as info:
load_eval_set(root)
assert "\n" not in str(info.value).strip()
assert "errors.pydantic.dev" not in str(info.value)
def test_invalid_eval_yaml_raises(tmp_path: Path) -> None:
with pytest.raises(EvalSetError, match=r"eval\.yaml"):
load_eval_set(make_set(tmp_path / "one", 'name: "x"\n'))
with pytest.raises(EvalSetError, match=r"eval\.yaml"):
load_eval_set(make_set(tmp_path / "two", "a: ["))
def test_recorded_response_is_raw_text(tmp_path: Path) -> None:
raw = ' {"language": "de",\n "entities": ["ä"]} \n'
(tmp_path / "a.json").write_text(raw, encoding="utf-8")
assert RecordedResponses(tmp_path).response_for("a") == raw
def test_missing_recorded_response_is_none(tmp_path: Path) -> None:
assert RecordedResponses(tmp_path).response_for("a") is None
def test_recorded_response_strips_bom(tmp_path: Path) -> None:
(tmp_path / "a.json").write_bytes(b"\xef\xbb\xbf" + b'{"language": "de"}')
assert RecordedResponses(tmp_path).response_for("a") == '{"language": "de"}'
def test_unreadable_recorded_response_raises(tmp_path: Path) -> None:
(tmp_path / "a.json").write_bytes(b"\xff\xfe\x00{")
(tmp_path / "b.json").mkdir()
for case_id in ("a", "b"):
with pytest.raises(ResponseError, match=case_id):
RecordedResponses(tmp_path).response_for(case_id)
def test_non_yaml_file_in_cases_raises(tmp_path: Path) -> None:
root = make_set(tmp_path)
(root / "cases" / "x.yml").write_text(CASE_YAML, encoding="utf-8")
with pytest.raises(EvalSetError, match=r"x\.yml.*must end in \.yaml"):
load_eval_set(root)
def test_unquoted_no_stays_string(tmp_path: Path) -> None:
case = CASE_YAML.replace('value: "de"', "value: no").replace('items: ["a"]', "items: [yes, on]")
eval_set = load_eval_set(make_set(tmp_path, cases={"a": case}))
first, second = eval_set.cases[0].expect
assert isinstance(first, EqualsCheck)
assert first.value == "no"
assert isinstance(second, ContainsCheck)
assert second.items == ["yes", "on"]
case = CASE_YAML.replace('value: "de"', "value: true")
eval_set = load_eval_set(make_set(tmp_path / "t", cases={"a": case}))
first = eval_set.cases[0].expect[0]
assert isinstance(first, EqualsCheck)
assert first.value is True
_REF_HEAD = (
'input: {}\nexpect:\n - grader: "reference"\n path: "/e"\n'
" min_precision: 0.5\n min_recall: 0.5\n"
)
@pytest.mark.parametrize(
"body",
[
' items: ["a", {n: "b"}]\n',
' items: [{a: "x"}, {b: "y"}]\n',
' items: ["a", " A"]\n',
' items: [{a: "x"}, {a: "X "}]\n',
" items: [{}]\n",
' items: [["a"]]\n',
' items: [{a: ["x"]}]\n',
' where: {kind: "e"}\n items: ["a"]\n',
" items: [.nan]\n",
' where: {n: .inf}\n items: [{a: "x"}]\n',
"min_recall",
"min_precision",
],
)
def test_invalid_reference_raises(tmp_path: Path, body: str) -> None:
if body.startswith("min_"): # minimum missing
text = _REF_HEAD.replace(f" {body}: 0.5\n", "") + ' items: ["a"]\n'
else:
text = _REF_HEAD + body
with pytest.raises(EvalSetError, match=r"bad\.yaml"):
load_eval_set(make_set(tmp_path, cases={"bad": text}))
def test_valid_reference_loads(tmp_path: Path) -> None:
text = _REF_HEAD + ' where: {kind: "e"}\n items: [{a: "x"}, {a: "y"}]\n'
assert load_eval_set(make_set(tmp_path, cases={"ok": text})).cases[0].expect