File size: 9,924 Bytes
1600cd6
 
 
 
 
 
 
 
1ed2d7f
1600cd6
2a9dc4c
1600cd6
2a9dc4c
1600cd6
 
 
1ed2d7f
1600cd6
 
 
 
 
 
 
 
2a9dc4c
1600cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
1600cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""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 Any, Dict, List

from lingologos_codex.casecorpus import read_rows, validate_case_rows

from lingologos_python.patterns import (
    FAMILIES,
    PATTERNS,
    PATTERN_IDS,
    SHARED_REFUSALS,
    PatternSpec,
    pattern_card,
    plan_pattern,
    render_card,
    scan_pattern,
    split_target,
    TARGET_SEPARATOR,
)
from lingologos_python.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 lingologos_python 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


def test_every_card_lists_the_refusals_a_plan_can_answer_with() -> None:
    for pattern_id in PATTERN_IDS:
        card = _card(pattern_id)
        for code in SHARED_REFUSALS:
            assert code in card.refuses_as
        assert len(set(card.refuses_as)) == len(card.refuses_as)


def test_a_rule_that_breaks_while_building_its_anchors_ends_in_a_named_refusal(tmp_path: Path, monkeypatch) -> None:
    from lingologos_python import rules

    root = tmp_path / "ws"
    (root / "src").mkdir(parents=True)
    (root / "tests").mkdir(parents=True)
    (root / "src" / "widget.py").write_text("def pick(items=[]):\n    return items\n", encoding="utf-8", newline="\n")
    (root / "tests" / "test_widget.py").write_text(
        "from src.widget import pick\n\n\ndef test_pick_defaults() -> None:\n    assert pick() == []\n",
        encoding="utf-8",
        newline="\n",
    )

    def colliding(target: Any) -> Any:
        raise ValueError("the anchors of this rule overlap")

    monkeypatch.setitem(rules.RULES, "mutable-default-to-none", colliding)
    plan = plan_pattern(root, "mutable-default-to-none", "src/widget.py::pick")
    assert plan.refused
    assert plan.reason_code == rules.ANCHOR_OVERLAP