File size: 20,182 Bytes
db2c7db 1600cd6 1ed2d7f 1600cd6 2a9dc4c 1600cd6 2a9dc4c 1600cd6 db2c7db 1600cd6 1ed2d7f f4952b6 1ed2d7f f4952b6 1ed2d7f f4952b6 1ed2d7f db2c7db | 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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 | """Tests for the eight rules of the Python pattern catalog."""
from __future__ import annotations
from pathlib import Path
from typing import Any, 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"),
("src/retries.py", "call_or_none", "bare-except-to-narrow-exception"),
("src/labels.py", "label_for", "none-comparison-to-identity"),
("src/baskets.py", "describe", "empty-len-to-truthiness"),
]
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
def _apply_to(root: Path, edit: Any) -> str:
"""Apply one edit of a hit to the workspace on disk and return the resulting text."""
original = (root / 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
return result.updated_text
def test_a_handle_reused_after_another_statement_is_not_one_scoped_block(tmp_path: Path) -> None:
root = tmp_path / "ws"
_write(
root / "src" / "leaky.py",
"def read_twice(path):\n handle = open(path)\n first = handle.read()\n"
" step = 1\n second = handle.read()\n handle.close()\n return first, second\n",
)
_write(
root / "tests" / "test_leaky.py",
"from src.leaky import read_twice\n\n\ndef test_read_twice_exists() -> None:\n assert callable(read_twice)\n",
)
outcome = _outcome("src/leaky.py", "read_twice", "open-to-context-manager", root)
assert isinstance(outcome, rules.RuleMiss)
assert outcome.reason_code == rules.HANDLE_ESCAPE
def test_a_guard_lands_below_the_docstring_it_has_to_keep(tmp_path: Path) -> None:
root = tmp_path / "ws"
_write(
root / "src" / "documented.py",
'def collect(items=[]):\n """Collect one item."""\n items.append(1)\n return items\n',
)
_write(
root / "tests" / "test_documented.py",
"from src.documented import collect\n\n\ndef test_collect_defaults() -> None:\n assert collect() == [1]\n",
)
outcome = _outcome("src/documented.py", "collect", "mutable-default-to-none", root)
assert isinstance(outcome, rules.RuleHit)
patched = _apply_to(root, outcome.edits[0])
assert patched.index('"""Collect one item."""') < patched.index("if items is None:")
namespace: Dict[str, Any] = {}
exec(patched, namespace)
assert namespace["collect"].__doc__ == "Collect one item."
first = namespace["collect"]()
second = namespace["collect"]()
assert first == [1] and second == [1] and first is not second
def test_a_docstring_only_body_gets_its_guard_after_the_docstring(tmp_path: Path) -> None:
root = tmp_path / "ws"
_write(root / "src" / "quiet.py", 'def keep(items=[]):\n """Keep them."""\n')
_write(
root / "tests" / "test_quiet.py",
"from src.quiet import keep\n\n\ndef test_keep_exists() -> None:\n assert callable(keep)\n",
)
outcome = _outcome("src/quiet.py", "keep", "mutable-default-to-none", root)
assert isinstance(outcome, rules.RuleHit)
patched = _apply_to(root, outcome.edits[0])
compile(patched, "quiet.py", "exec")
namespace: Dict[str, Any] = {}
exec(patched, namespace)
assert namespace["keep"].__doc__ == "Keep them."
def test_an_assert_whose_message_is_built_at_call_time_is_named_as_outside_the_rule(tmp_path: Path) -> None:
root = tmp_path / "ws"
_write(root / "src" / "loud.py", 'def shout(value):\n assert value, f"bad {value}"\n return value\n')
_write(
root / "tests" / "test_loud.py",
"from src.loud import shout\n\n\ndef test_shout_exists() -> None:\n assert callable(shout)\n",
)
outcome = _outcome("src/loud.py", "shout", "bare-assert-to-explicit-raise", root)
assert isinstance(outcome, rules.RuleMiss)
assert outcome.reason_code == rules.NON_LITERAL_ASSERT_MESSAGE
def test_a_card_refuses_a_coroutine_only_when_its_lock_does_not_wait_for_one(tmp_path: Path) -> None:
root = tmp_path / "ws"
_write(root / "src" / "coro.py", "async def gather(items=[]):\n return items\n")
_write(
root / "tests" / "test_coro.py",
"from src.coro import gather\n\n\ndef test_gather_exists() -> None:\n assert callable(gather)\n",
)
claimed = _outcome("src/coro.py", "gather", "mutable-default-to-none", root)
assert isinstance(claimed, rules.RuleHit)
assert "asyncio.run(" in claimed.edits[1].replace
assert "import asyncio" in claimed.edits[1].replace
for rule_id in ("chain-to-registry", "open-to-context-manager", "bare-except-to-narrow-exception"):
refusal = _outcome("src/coro.py", "gather", rule_id, root)
assert isinstance(refusal, rules.RuleMiss)
assert refusal.reason_code == rules.ASYNC_TARGET
def test_a_test_file_the_lock_cannot_append_to_is_refused_as_a_target(tmp_path: Path) -> None:
root = tmp_path / "ws"
_write(root / "src" / "pairing.py", "def pick(items=[]):\n return items\n")
(root / "tests").mkdir(parents=True)
with (root / "tests" / "test_pairing.py").open("w", encoding="utf-8", newline="") as handle:
handle.write("def test_pairing_defaults() -> None:\r\n assert pick() == []\r\n")
outcome = _outcome("src/pairing.py", "pick", "mutable-default-to-none", root)
assert isinstance(outcome, rules.RuleMiss)
assert outcome.reason_code == rules.CRLF_TARGET
def test_a_module_path_no_lock_import_can_reach_is_refused_by_name(tmp_path: Path) -> None:
root = tmp_path / "ws"
_write(root / "my-src" / "tool.py", "def pick(items=[]):\n return items\n")
_write(
root / "tests" / "test_tool.py",
"from src.tool import pick\n\n\ndef test_pick_defaults() -> None:\n assert pick() == []\n",
)
outcome = _outcome("my-src/tool.py", "pick", "mutable-default-to-none", root)
assert isinstance(outcome, rules.RuleMiss)
assert outcome.reason_code == rules.INVALID_COMPANION_PATH
def test_a_bare_handler_becomes_a_named_one_without_touching_its_body() -> None:
hit = _plan("src/retries.py", "call_or_none", "bare-except-to-narrow-exception")
patched = _patched(hit)["src/retries.py"]
compile(patched, "retries.py", "exec")
original = (LAB / "src" / "retries.py").read_text(encoding="utf-8", newline="")
assert patched == original.replace(" except:\n", " except Exception:\n")
assert "return \"\"" in patched
def test_a_handler_that_already_names_its_class_is_left_alone() -> None:
assert _miss_code("src/retries.py", "call_or_note", "bare-except-to-narrow-exception") == rules.NO_BARE_EXCEPT
def test_a_bare_handler_that_re_raises_is_refused_by_name(tmp_path: Path) -> None:
root = tmp_path / "ws"
_write(
root / "src" / "lift.py",
"def carry(source):\n try:\n return source.read()\n except:\n raise\n",
)
_write(root / "tests" / "test_lift.py", "def test_lift_reads() -> None:\n assert True\n")
outcome = _outcome("src/lift.py", "carry", "bare-except-to-narrow-exception", root)
assert isinstance(outcome, rules.RuleMiss)
assert outcome.reason_code == rules.BARE_EXCEPT_RE_RAISES
def test_a_count_of_none_becomes_an_identity_test_and_leaves_the_rest_alone() -> None:
hit = _plan("src/labels.py", "label_for", "none-comparison-to-identity")
patched = _patched(hit)["src/labels.py"]
compile(patched, "labels.py", "exec")
assert "if value is None:" in patched
assert "if value is not None and value == \"\":" in patched
assert "== None" not in patched
def test_a_test_that_already_asks_with_identity_is_left_alone() -> None:
assert _miss_code("src/labels.py", "is_missing", "none-comparison-to-identity") == rules.NO_NONE_COMPARISON
def test_a_chained_comparison_against_none_is_refused_by_name(tmp_path: Path) -> None:
root = tmp_path / "ws"
_write(root / "src" / "same.py", "def agrees(one, two):\n return one == two == None\n")
_write(root / "tests" / "test_same.py", "def test_agrees_exists() -> None:\n assert True\n")
outcome = _outcome("src/same.py", "agrees", "none-comparison-to-identity", root)
assert isinstance(outcome, rules.RuleMiss)
assert outcome.reason_code == rules.NONE_COMPARISON_IS_CHAINED
def test_counting_to_ask_for_emptiness_becomes_a_truthiness_test() -> None:
hit = _plan("src/baskets.py", "describe", "empty-len-to-truthiness")
patched = _patched(hit)["src/baskets.py"]
compile(patched, "baskets.py", "exec")
original = (LAB / "src" / "baskets.py").read_text(encoding="utf-8", newline="")
assert patched == original.replace("if len(items) == 0:", "if not items:")
def test_an_emptiness_test_that_already_asks_directly_is_left_alone() -> None:
assert _miss_code("src/baskets.py", "first_or_none", "empty-len-to-truthiness") == rules.NO_EMPTY_LEN_CHECK
def test_a_count_of_something_that_is_not_a_name_is_refused_by_name(tmp_path: Path) -> None:
root = tmp_path / "ws"
_write(root / "src" / "box.py", "def show(box):\n if len(box.items) == 0:\n return 0\n return 1\n")
_write(root / "tests" / "test_box.py", "def test_box_shows() -> None:\n assert True\n")
outcome = _outcome("src/box.py", "show", "empty-len-to-truthiness", root)
assert isinstance(outcome, rules.RuleMiss)
assert outcome.reason_code == rules.LEN_TARGET_IS_NOT_A_NAME
|