codex-python / tests /test_pattern_session.py
tailot's picture
Upload folder using huggingface_hub
e1de134 verified
Raw History Blame Contribute Delete
7.42 kB
"""Tests for applying a catalog card end to end: pair staged, six nodes judging, one commit."""
from __future__ import annotations
import hashlib
import subprocess
import sys
from pathlib import Path
from typing import Dict
from lingologos_codex.fsadapter import FileSystemAdapterError
from lingologos_python.patterns import PATTERNS, plan_pattern
from lingologos_python.session import DEFAULT_PROTECTED_PATTERNS, PythonWorkspaceSession
POSITIVE = {
"annotate-literal-defaults": "src/tokens.py::count_words",
"bare-assert-to-explicit-raise": "src/guards.py::open_ticket",
"bare-except-to-narrow-exception": "src/retries.py::call_or_none",
"chain-to-registry": "src/registry.py::render",
"empty-len-to-truthiness": "src/baskets.py::describe",
"mutable-default-to-none": "src/slugify.py::add_tag",
"none-comparison-to-identity": "src/labels.py::label_for",
"open-to-context-manager": "src/notes.py::read_note",
}
NEGATIVE = {
"annotate-literal-defaults": ("src/tokens.py::count_lines", "ALREADY_ANNOTATED"),
"bare-assert-to-explicit-raise": ("src/guards.py::close_ticket", "NOT_THE_FIRST_STATEMENT"),
"bare-except-to-narrow-exception": ("src/retries.py::call_or_note", "NO_BARE_EXCEPT"),
"chain-to-registry": ("src/registry.py::render_pair", "BRANCH_SHAPE_MISMATCH"),
"empty-len-to-truthiness": ("src/baskets.py::first_or_none", "NO_EMPTY_LEN_CHECK"),
"mutable-default-to-none": ("src/slugify.py::join_parts", "NOT_A_MUTABLE_DEFAULT"),
"none-comparison-to-identity": ("src/labels.py::is_missing", "NO_NONE_COMPARISON"),
"open-to-context-manager": ("src/notes.py::write_note", "ALREADY_SCOPED"),
}
def _tree_state(root: Path) -> Dict[str, str]:
state: Dict[str, str] = {}
for path in sorted(root.rglob("*")):
if path.is_file():
digest = hashlib.sha256(path.read_bytes()).hexdigest()
state[str(path.relative_to(root).as_posix())] = digest
return state
def _pytest_return_code(root: Path) -> int:
return subprocess.run(
[sys.executable, "-B", "-m", "pytest", "-q", "-p", "no:cacheprovider"],
cwd=str(root),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
).returncode
def test_every_card_lands_on_its_target_and_the_six_nodes_confirm_it(pattern_lab: Path) -> None:
session = PythonWorkspaceSession(pattern_lab)
for pattern_id in sorted(POSITIVE):
result = session.apply_pattern(pattern_id, target=POSITIVE[pattern_id])
assert result.verdict == "VERIFIED", "%s: %s %s" % (pattern_id, result.verdict, result.detail)
assert result.assurance == 3
assert result.committed is True
assert len(result.touched_files) == 2
assert result.dossier["pattern"] == pattern_id
assert result.dossier["companionFiles"] == [result.touched_files[1]]
assert _pytest_return_code(pattern_lab) == 0
source = (pattern_lab / "src" / "notes.py").read_text(encoding="utf-8")
assert "with open(" in source
test_text = (pattern_lab / "tests" / "test_notes.py").read_text(encoding="utf-8")
assert "def test_read_note_scopes_its_handle() -> None:" in test_text
def test_the_lock_test_fails_until_the_change_it_locks_lands(pattern_lab: Path) -> None:
assert _pytest_return_code(pattern_lab) == 0
plan = plan_pattern(pattern_lab, "chain-to-registry", POSITIVE["chain-to-registry"])
assert not plan.refused
companion = plan.companions()[0]
target = pattern_lab / "tests" / "test_registry.py"
original = target.read_text(encoding="utf-8", newline="")
assert companion.search in original
target.write_text(original.replace(companion.search, companion.replace, 1), encoding="utf-8", newline="")
assert _pytest_return_code(pattern_lab) != 0
target.write_text(original, encoding="utf-8", newline="")
assert _pytest_return_code(pattern_lab) == 0
def test_a_card_that_refuses_never_reaches_the_nodes_and_writes_nothing(pattern_lab: Path) -> None:
session = PythonWorkspaceSession(pattern_lab)
before = _tree_state(pattern_lab)
for pattern_id in sorted(NEGATIVE):
target, code = NEGATIVE[pattern_id]
result = session.apply_pattern(pattern_id, target=target)
assert result.verdict == "REFUSED"
assert result.assurance == 0
assert result.reason == code
assert result.committed is False
assert result.touched_files == ()
assert result.dossier["gates"] == []
assert _tree_state(pattern_lab) == before
def test_a_dry_run_verifies_the_pair_and_touches_no_file(pattern_lab: Path) -> None:
session = PythonWorkspaceSession(pattern_lab)
before = _tree_state(pattern_lab)
result = session.apply_pattern("open-to-context-manager", target=POSITIVE["open-to-context-manager"], commit=False)
assert result.verdict == "VERIFIED"
assert result.assurance == 3
assert result.committed is False
assert _tree_state(pattern_lab) == before
def test_applying_a_card_twice_is_a_refusal_and_not_a_second_change(pattern_lab: Path) -> None:
session = PythonWorkspaceSession(pattern_lab)
pattern_id = "open-to-context-manager"
first = session.apply_pattern(pattern_id, target=POSITIVE[pattern_id])
assert first.committed is True
after_first = _tree_state(pattern_lab)
second = session.apply_pattern(pattern_id, target=POSITIVE[pattern_id])
assert second.verdict == "REFUSED"
assert second.reason in PATTERNS[pattern_id].refuses_as
assert second.committed is False
assert _tree_state(pattern_lab) == after_first
def test_a_policy_that_blocks_the_lock_test_blocks_the_source_edit_too(pattern_lab: Path) -> None:
session = PythonWorkspaceSession(
pattern_lab,
protected_patterns=DEFAULT_PROTECTED_PATTERNS + ("tests/test_notes.py",),
)
before = _tree_state(pattern_lab)
result = session.apply_pattern("open-to-context-manager", target=POSITIVE["open-to-context-manager"])
assert result.verdict == "REFUSED"
assert result.reason == "PATH_POLICY"
assert result.committed is False
assert _tree_state(pattern_lab) == before
def test_a_commit_refused_by_the_disk_restores_the_whole_pair(pattern_lab: Path, monkeypatch) -> None:
"""A pair is written as one commit; a commit the disk refuses leaves both files as they were."""
session = PythonWorkspaceSession(pattern_lab)
real_os_fs = session._os_fs
class CommitRefusingFs:
def __init__(self, inner: object) -> None:
self._inner = inner
def __getattr__(self, name: str) -> object:
return getattr(self._inner, name)
def commit_transaction(self, tx: object) -> None:
raise FileSystemAdapterError("the disk refused the replace")
def os_fs(root: Path, *, check_allowed: bool = True) -> object:
fs = real_os_fs(root, check_allowed=check_allowed)
if Path(root).resolve() == pattern_lab.resolve():
return CommitRefusingFs(fs)
return fs
monkeypatch.setattr(session, "_os_fs", os_fs)
before = _tree_state(pattern_lab)
result = session.apply_pattern("chain-to-registry", target=POSITIVE["chain-to-registry"])
assert result.verdict == "REFUSED"
assert result.reason == "PATCH_NOT_APPLIED"
assert result.committed is False
assert "refused the replace" in result.detail
assert _tree_state(pattern_lab) == before