File size: 7,417 Bytes
1600cd6
 
 
 
 
 
 
 
 
 
e1de134
 
2a9dc4c
 
1600cd6
 
 
 
db2c7db
1600cd6
db2c7db
1600cd6
db2c7db
1600cd6
 
 
 
 
db2c7db
1600cd6
db2c7db
1600cd6
db2c7db
1600cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"""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