File size: 10,946 Bytes
1600cd6
 
 
 
 
 
 
2a9dc4c
1600cd6
2a9dc4c
 
1600cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""Tests for the five rules of the Python pattern catalog."""

from __future__ import annotations

from pathlib import Path
from typing import Callable, Dict, Optional

from lingologos_codex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch

from lingologos_python import rules
from lingologos_python.patterns import PATTERNS

ROOT = Path(__file__).resolve().parents[1]
LAB = ROOT / "fixtures" / "pattern_lab"


def _reader(root: Path) -> Callable[[str], Optional[str]]:
    def read(rel_posix: str) -> Optional[str]:
        path = root / Path(*rel_posix.split("/"))
        return path.read_text(encoding="utf-8", newline="") if path.is_file() else None

    return read


def _write(path: Path, text: str) -> None:
    """Write LF text on any host: the catalog anchors on LF, and Path.write_text would translate it."""

    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8", newline="\n") as handle:
        handle.write(text)


def _outcome(rel_posix: str, symbol: str, rule_id: str, root: Path = LAB) -> rules.Outcome:
    target, miss = rules.open_target(rel_posix, symbol, _reader(root))
    if target is None:
        assert miss is not None
        return miss
    return rules.RULES[rule_id](target)


def _plan(rel_posix: str, symbol: str, rule_id: str) -> rules.RuleHit:
    outcome = _outcome(rel_posix, symbol, rule_id)
    assert isinstance(outcome, rules.RuleHit), "expected a hit, got %r" % (outcome,)
    return outcome


def _miss_code(rel_posix: str, symbol: str, rule_id: str) -> str:
    outcome = _outcome(rel_posix, symbol, rule_id)
    assert isinstance(outcome, rules.RuleMiss), "expected a refusal, got %r" % (outcome,)
    return outcome.reason_code


def _patched(hit: rules.RuleHit) -> Dict[str, str]:
    """Every file of a hit after its edit is applied to the fixture text."""

    patched: Dict[str, str] = {}
    for edit in hit.edits:
        original = (LAB / Path(*edit.file.split("/"))).read_text(encoding="utf-8", newline="")
        result = apply_controlled_fuzzy_patch(
            original, SearchReplaceBlock(edit.search, edit.replace), FuzzyPatchConfig()
        )
        assert result.applied, "the anchor for '%s' does not apply" % edit.file
        patched[edit.file] = result.updated_text
    return patched


def test_every_card_asks_for_a_rule_this_bundle_holds() -> None:
    assert sorted(PATTERNS) == sorted(rules.RULE_IDS)
    for pattern_id, spec in PATTERNS.items():
        assert spec.rule == pattern_id
        assert pattern_id in rules.RULES


def test_annotating_a_literal_default_touches_the_signature_and_nothing_else() -> None:
    hit = _plan("src/tokens.py", "count_words", "annotate-literal-defaults")
    patched = _patched(hit)["src/tokens.py"]
    compile(patched, "tokens.py", "exec")
    original = (LAB / "src" / "tokens.py").read_text(encoding="utf-8", newline="")
    assert patched == original.replace(
        'def count_words(text="", unit="word"):',
        'def count_words(text: str = "", unit: str = "word"):',
    )


def test_a_default_that_already_states_its_type_is_left_alone() -> None:
    assert _miss_code("src/tokens.py", "count_lines", "annotate-literal-defaults") == rules.ALREADY_ANNOTATED


def test_a_tuple_default_is_not_the_shared_kind_a_rule_refuses() -> None:
    assert _miss_code("src/slugify.py", "join_parts", "mutable-default-to-none") == rules.NOT_A_MUTABLE_DEFAULT


def test_a_shared_default_moves_out_of_the_signature_into_the_body() -> None:
    hit = _plan("src/slugify.py", "add_tag", "mutable-default-to-none")
    source = hit.edits[0].replace
    assert "tags=None" in source
    assert "if tags is None:" in source
    assert "tags=[]" not in source
    compile(_patched(hit)["src/slugify.py"], "slugify.py", "exec")


def test_a_chain_of_one_name_becomes_one_visible_mapping() -> None:
    hit = _plan("src/registry.py", "render", "chain-to-registry")
    source = hit.edits[0].replace
    assert '"short": format_short' in source
    assert "handlers.get(kind)" in source
    assert "elif" not in source
    compile(_patched(hit)["src/registry.py"], "registry.py", "exec")


def test_a_chain_whose_branches_answer_differently_stays_a_chain() -> None:
    assert _miss_code("src/registry.py", "render_pair", "chain-to-registry") == rules.BRANCH_SHAPE_MISMATCH


def test_a_handle_that_escapes_its_function_is_placed_in_a_with_block() -> None:
    hit = _plan("src/notes.py", "read_note", "open-to-context-manager")
    source = hit.edits[0].replace
    assert "with open(" in source
    assert ".close()" not in source
    assert "body = handle.read()" in source
    compile(_patched(hit)["src/notes.py"], "notes.py", "exec")


def test_a_function_that_already_scopes_its_handle_is_not_touched() -> None:
    assert _miss_code("src/notes.py", "write_note", "open-to-context-manager") == rules.ALREADY_SCOPED


def test_a_bare_assert_becomes_a_raise_that_says_the_same_thing() -> None:
    hit = _plan("src/guards.py", "open_ticket", "bare-assert-to-explicit-raise")
    source = hit.edits[0].replace
    assert "raise AssertionError(" in source
    assert '"queue name is required"' in source
    assert "\n    assert " not in source
    compile(_patched(hit)["src/guards.py"], "guards.py", "exec")


def test_an_assert_that_is_not_the_guard_of_the_function_stays() -> None:
    assert _miss_code("src/guards.py", "close_ticket", "bare-assert-to-explicit-raise") == rules.NOT_THE_FIRST_STATEMENT


def test_every_hit_hangs_its_lock_on_the_test_file_of_its_target() -> None:
    pairs = [
        ("src/tokens.py", "count_words", "annotate-literal-defaults"),
        ("src/slugify.py", "add_tag", "mutable-default-to-none"),
        ("src/registry.py", "render", "chain-to-registry"),
        ("src/notes.py", "read_note", "open-to-context-manager"),
        ("src/guards.py", "open_ticket", "bare-assert-to-explicit-raise"),
    ]
    for rel_posix, symbol, rule_id in pairs:
        hit = _plan(rel_posix, symbol, rule_id)
        assert len(hit.edits) == 2
        assert hit.edits[1].file == rules.test_file_for(rel_posix)
        compile(_patched(hit)[hit.edits[1].file], hit.edits[1].file, "exec")


def test_a_rule_that_cannot_place_its_lock_refuses_the_whole_change(tmp_path: Path) -> None:
    root = tmp_path / "ws"
    (root / "src").mkdir(parents=True)
    (root / "tests").mkdir(parents=True)
    _write(root / "src" / "widget.py", "def pick(items=[]):\n    return items\n")
    twice = (
        "from src.widget import pick\n\n\n"
        "def test_pick_defaults() -> None:\n    assert pick() == []\n\n\n"
        "def test_pick_defaults() -> None:\n    assert pick() == []\n"
    )
    _write(root / "tests" / "test_widget.py", twice)
    outcome = _outcome("src/widget.py", "pick", "mutable-default-to-none", root)
    assert isinstance(outcome, rules.RuleMiss)
    assert outcome.reason_code == rules.AMBIGUOUS_TEST_ANCHOR


def test_a_module_with_no_test_file_beside_it_is_left_as_it_is(tmp_path: Path) -> None:
    root = tmp_path / "ws"
    (root / "src").mkdir(parents=True)
    _write(root / "src" / "widget.py", "def pick(items=[]):\n    return items\n")
    outcome = _outcome("src/widget.py", "pick", "mutable-default-to-none", root)
    assert isinstance(outcome, rules.RuleMiss)
    assert outcome.reason_code == rules.NO_TEST_FILE


def test_a_mutable_default_that_carries_an_annotation_is_outside_the_claim(tmp_path: Path) -> None:
    root = tmp_path / "ws"
    (root / "src").mkdir(parents=True)
    (root / "tests").mkdir(parents=True)
    _write(root / "src" / "widget.py", "def pick(items: list = []):\n    return items\n")
    _write(
        root / "tests" / "test_widget.py",
        "from src.widget import pick\n\n\ndef test_pick_defaults() -> None:\n    assert pick() == []\n",
    )
    outcome = _outcome("src/widget.py", "pick", "mutable-default-to-none", root)
    assert isinstance(outcome, rules.RuleMiss)
    assert outcome.reason_code == rules.ANNOTATED_MUTABLE_DEFAULT


def test_a_function_that_already_rebuilds_its_default_is_not_done_twice(tmp_path: Path) -> None:
    root = tmp_path / "ws"
    (root / "src").mkdir(parents=True)
    (root / "tests").mkdir(parents=True)
    _write(root / "src" / "widget.py", "def pick(items=[]):\n    if items is None:\n        items = []\n    return items\n")
    _write(
        root / "tests" / "test_widget.py",
        "from src.widget import pick\n\n\ndef test_pick_defaults() -> None:\n    assert pick() == []\n",
    )
    outcome = _outcome("src/widget.py", "pick", "mutable-default-to-none", root)
    assert isinstance(outcome, rules.RuleMiss)
    assert outcome.reason_code == rules.GUARD_ALREADY_PRESENT


def test_a_target_that_is_not_there_is_named_instead_of_guessed(tmp_path: Path) -> None:
    root = tmp_path / "ws"
    (root / "src").mkdir(parents=True)
    (root / "tests").mkdir(parents=True)
    _write(root / "src" / "widget.py", "def pick(items=[]):\n    return items\n")
    _write(
        root / "tests" / "test_widget.py",
        "from src.widget import pick\n\n\ndef test_pick_defaults() -> None:\n    assert pick() == []\n",
    )
    missing_file = _outcome("src/nothing.py", "pick", "mutable-default-to-none", root)
    assert isinstance(missing_file, rules.RuleMiss)
    assert missing_file.reason_code == rules.MISSING_TARGET_FILE
    missing_symbol = _outcome("src/widget.py", "absent", "mutable-default-to-none", root)
    assert isinstance(missing_symbol, rules.RuleMiss)
    assert missing_symbol.reason_code == rules.NO_SUCH_FUNCTION


def test_a_handle_that_outlives_its_function_is_left_to_a_larger_change(tmp_path: Path) -> None:
    root = tmp_path / "ws"
    (root / "src").mkdir(parents=True)
    (root / "tests").mkdir(parents=True)
    _write(
        root / "src" / "keep.py",
        'def take(path):\n    handle = open(path, "r", encoding="utf-8")\n    return handle\n',
    )
    _write(
        root / "tests" / "test_keep.py",
        "from src.keep import take\n\n\ndef test_take_exists() -> None:\n    assert callable(take)\n",
    )
    outcome = _outcome("src/keep.py", "take", "open-to-context-manager", root)
    assert isinstance(outcome, rules.RuleMiss)
    assert outcome.reason_code == rules.HANDLE_ESCAPE


def test_a_rule_that_anchors_on_text_refuses_text_it_cannot_anchor(tmp_path: Path) -> None:
    root = tmp_path / "ws"
    (root / "src").mkdir(parents=True)
    (root / "tests").mkdir(parents=True)
    with (root / "src" / "crlf.py").open("w", encoding="utf-8", newline="") as handle:
        handle.write("def pick(items=[]):\r\n    return items\r\n")
    _write(
        root / "tests" / "test_crlf.py",
        "from src.crlf import pick\n\n\ndef test_pick_defaults() -> None:\n    assert pick() == []\n",
    )
    outcome = _outcome("src/crlf.py", "pick", "mutable-default-to-none", root)
    assert isinstance(outcome, rules.RuleMiss)
    assert outcome.reason_code == rules.CRLF_TARGET