codex-python / tests /test_patterns.py
tailot's picture
Upload folder using huggingface_hub
1600cd6 verified
Raw History Blame
8.64 kB
"""Tests for the pattern catalog: what a card claims, and what a plan reports."""
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
from typing import Dict, List
from lgcodex.casecorpus import read_rows, validate_case_rows
from lgpython.patterns import (
FAMILIES,
PATTERNS,
PATTERN_IDS,
PatternSpec,
pattern_card,
plan_pattern,
render_card,
scan_pattern,
split_target,
TARGET_SEPARATOR,
)
from lgpython.rules import RULE_IDS
ROOT = Path(__file__).resolve().parents[1]
LAB = ROOT / "fixtures" / "pattern_lab"
CASES = ROOT / "patterns" / "pattern_cases.jsonl"
COVERAGE = ROOT / "patterns" / "coverage.json"
POSITIVE = {
"annotate-literal-defaults": "src/tokens.py::count_words",
"bare-assert-to-explicit-raise": "src/guards.py::open_ticket",
"chain-to-registry": "src/registry.py::render",
"mutable-default-to-none": "src/slugify.py::add_tag",
"open-to-context-manager": "src/notes.py::read_note",
}
NEGATIVE = {
"annotate-literal-defaults": "src/tokens.py::count_lines",
"bare-assert-to-explicit-raise": "src/guards.py::close_ticket",
"chain-to-registry": "src/registry.py::render_pair",
"mutable-default-to-none": "src/slugify.py::join_parts",
"open-to-context-manager": "src/notes.py::write_note",
}
def _card(pattern_id: str) -> PatternSpec:
return pattern_card(pattern_id)
def _reason_codes() -> List[str]:
from lgpython import rules
return [name for name in dir(rules) if name.isupper() and "_" in name]
def test_each_card_states_the_shape_it_claims_and_the_lock_it_writes() -> None:
assert sorted(PATTERNS) == list(PATTERN_IDS)
for pattern_id in PATTERN_IDS:
spec = _card(pattern_id)
assert spec.family in FAMILIES
assert spec.rule in RULE_IDS
assert spec.shape and spec.rationale and spec.lock_claims
assert spec.preconditions, "%s claims a shape with no stated precondition" % pattern_id
assert spec.intent_tags and spec.companions
assert spec.min_assurance >= 2
def test_the_refusals_a_card_lists_are_codes_its_rule_can_give() -> None:
known = set(_reason_codes())
for pattern_id in PATTERN_IDS:
spec = _card(pattern_id)
assert spec.refuses_as, "%s states no refusal" % pattern_id
for code in spec.refuses_as:
assert code in known, "%s names %s, which no rule of this bundle gives" % (pattern_id, code)
def test_a_target_label_splits_into_the_file_and_the_function_it_names() -> None:
assert split_target("src/notes.py::read_note") == ("src/notes.py", "read_note")
assert split_target("src\\notes.py::read_note") == ("src/notes.py", "read_note")
for broken in ("src/notes.py", "src/notes.py::", "::read_note"):
try:
split_target(broken)
except ValueError:
continue
raise AssertionError("'%s' is not a target label" % broken)
assert TARGET_SEPARATOR == "::"
def test_a_card_that_is_not_in_the_catalog_is_named_as_missing() -> None:
try:
pattern_card("rename-the-module")
except KeyError as exc:
assert "rename-the-module" in str(exc)
return
raise AssertionError("an unknown card was accepted")
def test_a_plan_that_applies_reports_the_files_it_would_write() -> None:
for pattern_id in PATTERN_IDS:
plan = plan_pattern(LAB, pattern_id, POSITIVE[pattern_id])
assert not plan.refused, plan.detail
assert plan.min_assurance == _card(pattern_id).min_assurance
assert plan.evidence, "%s applied without saying why" % pattern_id
assert len(plan.edits) == 2
assert plan.primary().file in plan.files
assert plan.files == tuple(edit.file for edit in plan.edits)
assert plan.target.endswith(TARGET_SEPARATOR + POSITIVE[pattern_id].split(TARGET_SEPARATOR)[1])
summary = plan.summary()
assert pattern_id in summary and "writes" in summary
def test_a_plan_that_refuses_reports_the_code_its_rule_gave() -> None:
for pattern_id in PATTERN_IDS:
plan = plan_pattern(LAB, pattern_id, NEGATIVE[pattern_id])
assert plan.refused
assert plan.edits == ()
assert plan.files == ()
assert plan.reason_code in _card(pattern_id).refuses_as
assert plan.detail, "%s refused without a sentence explaining it" % pattern_id
try:
plan.primary()
except ValueError:
pass
else:
raise AssertionError("a refused plan claimed an edit")
def test_the_catalog_refuses_to_choose_between_two_functions_of_the_same_shape() -> None:
plan = plan_pattern(LAB, "annotate-literal-defaults")
assert plan.refused
assert plan.reason_code == "AMBIGUOUS_TARGET"
for target in [label for label, _hit in scan_pattern(LAB, "annotate-literal-defaults")]:
assert target in plan.detail
def test_scan_names_every_function_of_a_workspace_a_card_claims() -> None:
for pattern_id in PATTERN_IDS:
found = [label for label, _hit in scan_pattern(LAB, pattern_id)]
assert POSITIVE[pattern_id] in found, "%s does not find the function planted for it" % pattern_id
assert NEGATIVE[pattern_id] not in found, "%s finds the function planted to be refused" % pattern_id
only_one = scan_pattern(LAB, "open-to-context-manager")
assert [label for label, _hit in only_one] == ["src/notes.py::read_note"]
def test_a_card_written_as_a_row_validates_against_the_kernel_schema() -> None:
rows: List[Dict[str, object]] = []
for pattern_id in PATTERN_IDS:
rows.append(plan_pattern(LAB, pattern_id, POSITIVE[pattern_id]).to_row("pos-%s" % pattern_id))
rows.append(plan_pattern(LAB, pattern_id, NEGATIVE[pattern_id]).to_row("neg-%s" % pattern_id))
assert validate_case_rows(rows) == []
for row in rows[:1] + rows[1:2]:
assert row["language"] == "python"
assert row["pattern_id"] in PATTERN_IDS
assert row["rule"] == row["pattern_id"]
assert row["intent_tags"] == sorted(_card(str(row["pattern_id"])).intent_tags)
assert row["note"] == _card(str(row["pattern_id"])).shape
assert int(row["min_assurance"]) == _card(str(row["pattern_id"])).min_assurance
for row in rows:
if row["expect"] == "REFUSED":
assert row["edits"] == []
assert str(row["reason_code"]) in _card(str(row["pattern_id"])).refuses_as
else:
assert len(row["edits"]) == 2
assert row.get("reason_code", "") == ""
def test_a_card_renders_as_a_card_a_person_can_read() -> None:
text = render_card(_card("chain-to-registry"))
assert text.startswith("chain-to-registry")
for part in ("family", "shape", "why", "needs", "companion", "lock", "refuses", "assurance"):
assert part in text
assert "adding a kind means editing the middle of a chain" in text
def test_the_corpus_on_disk_is_what_the_rules_generate() -> None:
proc = subprocess.run(
[sys.executable, "-B", str(ROOT / "tools" / "build_patterns.py"), "--check"],
cwd=str(ROOT),
capture_output=True,
text=True,
)
assert proc.returncode == 0, proc.stdout + proc.stderr
assert "PATTERNS: CONFIRMED" in proc.stdout
def test_the_corpus_holds_one_pair_for_every_card_and_validates() -> None:
rows = read_rows(CASES)
assert validate_case_rows(rows) == []
assert len(rows) == 2 * len(PATTERNS)
for pattern_id in PATTERN_IDS:
positive = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "VERIFIED"]
negative = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "REFUSED"]
assert [str(row["targets"][0]) for row in positive] == [POSITIVE[pattern_id]]
assert [str(row["targets"][0]) for row in negative] == [NEGATIVE[pattern_id]]
def test_coverage_states_the_fixture_as_its_denominator() -> None:
payload = json.loads(COVERAGE.read_text(encoding="utf-8"))
assert payload["fixture"] == "fixtures/pattern_lab"
assert "not over Python" in payload["denominator"]
assert payload["rows"] == len(read_rows(CASES))
assert sorted(str(entry["pattern_id"]) for entry in payload["patterns"]) == list(PATTERN_IDS)
for entry in payload["patterns"]:
assert entry["positive_rows"] == 1 and entry["negative_rows"] == 1
assert POSITIVE[str(entry["pattern_id"])] in entry["targets_in_shape"]
assert len(entry["refusals_recorded"]) == 1
assert entry["refusals_recorded"][0] in _card(str(entry["pattern_id"])).refuses_as