codex-python / tests /test_rules.py
tailot's picture
Upload folder using huggingface_hub
1600cd6 verified
Raw History Blame
10.9 kB
"""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 lgcodex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch
from lgpython import rules
from lgpython.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