Enhance mechanical-refactor-verify skill with a whole-chain verifier, new relocation primitives, and generator inference (#30585)
This commit is contained in:
+322
@@ -0,0 +1,322 @@
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from generator_testlib import _commit, _git, _write # noqa: F401
|
||||
from mechanical_refactor_proof_generator import (
|
||||
build_repro,
|
||||
infer_recipe,
|
||||
recipe_to_script,
|
||||
)
|
||||
|
||||
|
||||
def test_infer_extract_function_with_returned_local(repo: Path) -> None:
|
||||
"""A block ending in ``pool = make(...)`` carved into a helper that returns ``pool`` infers
|
||||
an extract_function whose body is the verbatim block and whose return_text is authored.
|
||||
"""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def dispatch(self, n):\n"
|
||||
" base = self.setup()\n"
|
||||
" if self.flag:\n"
|
||||
" x = self.a\n"
|
||||
" y = x + n\n"
|
||||
" pool = make(\n"
|
||||
" a=x,\n"
|
||||
" b=y,\n"
|
||||
" )\n"
|
||||
" return pool\n"
|
||||
"\n"
|
||||
" def keep(self):\n"
|
||||
" return 0\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def dispatch(self, n):\n"
|
||||
" base = self.setup()\n"
|
||||
" if self.flag:\n"
|
||||
" pool = self._build_pool(n=n)\n"
|
||||
" return pool\n"
|
||||
"\n"
|
||||
" def _build_pool(self, *, n):\n"
|
||||
" x = self.a\n"
|
||||
" y = x + n\n"
|
||||
" pool = make(\n"
|
||||
" a=x,\n"
|
||||
" b=y,\n"
|
||||
" )\n"
|
||||
" return pool\n"
|
||||
"\n"
|
||||
" def keep(self):\n"
|
||||
" return 0\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
_commit(repo, "extract _build_pool from dispatch")
|
||||
recipe = infer_recipe("HEAD", str(repo))
|
||||
assert recipe.supported
|
||||
assert recipe.moves == []
|
||||
assert len(recipe.extract_functions) == 1
|
||||
ex = recipe.extract_functions[0]
|
||||
assert ex["name"] == "_build_pool"
|
||||
assert ex["src"] == "kv.py" and ex["dst"] == "kv.py"
|
||||
assert ex["into_class"] == "C"
|
||||
assert ex["before"] == "keep"
|
||||
assert ex["body_indent"] == 12
|
||||
assert ex["body"] == (
|
||||
" x = self.a\n"
|
||||
" y = x + n\n"
|
||||
" pool = make(\n"
|
||||
" a=x,\n"
|
||||
" b=y,\n"
|
||||
" )\n"
|
||||
)
|
||||
assert ex["call"] == " pool = self._build_pool(n=n)\n"
|
||||
assert ex["return_text"] == " return pool"
|
||||
assert ex["signature"] == " def _build_pool(self, *, n):\n"
|
||||
|
||||
|
||||
def test_infer_extract_function_keeps_leading_comment_in_body(repo: Path) -> None:
|
||||
"""A block whose first line is a comment extracts with that comment in the body, not
|
||||
absorbed into the authored signature (which is the def header through its colon only).
|
||||
"""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def dispatch(self, n):\n"
|
||||
" if self.flag:\n"
|
||||
" # pick the pool class for this backend\n"
|
||||
" cls = PoolA\n"
|
||||
" pool = cls(n)\n"
|
||||
" return pool\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def dispatch(self, n):\n"
|
||||
" if self.flag:\n"
|
||||
" pool = self._build_pool(n=n)\n"
|
||||
" return pool\n"
|
||||
"\n"
|
||||
" def _build_pool(self, *, n):\n"
|
||||
" # pick the pool class for this backend\n"
|
||||
" cls = PoolA\n"
|
||||
" pool = cls(n)\n"
|
||||
" return pool\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "extract _build_pool with a leading comment")
|
||||
recipe = infer_recipe(commit, str(repo))
|
||||
assert len(recipe.extract_functions) == 1
|
||||
ex = recipe.extract_functions[0]
|
||||
assert ex["signature"] == " def _build_pool(self, *, n):\n"
|
||||
assert ex["body"].lstrip().startswith("# pick the pool class")
|
||||
assert build_repro(recipe, repo_root=str(repo)).run() == ""
|
||||
|
||||
|
||||
def test_infer_extract_function_no_return_text_when_body_is_whole_helper(
|
||||
repo: Path,
|
||||
) -> None:
|
||||
"""When the helper body reproduces the source block with no trailing return, return_text
|
||||
is None (the block is a side-effecting statement sequence, not a value producer)."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def run(self):\n"
|
||||
" self.pre()\n"
|
||||
" self.log(1)\n"
|
||||
" self.log(2)\n"
|
||||
" self.post()\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def run(self):\n"
|
||||
" self.pre()\n"
|
||||
" self._emit()\n"
|
||||
" self.post()\n"
|
||||
"\n"
|
||||
" def _emit(self):\n"
|
||||
" self.log(1)\n"
|
||||
" self.log(2)\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
_commit(repo, "extract _emit from run")
|
||||
recipe = infer_recipe("HEAD", str(repo))
|
||||
assert recipe.supported
|
||||
assert len(recipe.extract_functions) == 1
|
||||
ex = recipe.extract_functions[0]
|
||||
assert ex["name"] == "_emit"
|
||||
assert ex["return_text"] is None
|
||||
assert ex["call"] == " self._emit()\n"
|
||||
|
||||
|
||||
def test_infer_extract_function_edited_body_does_not_pass(repo: Path) -> None:
|
||||
"""A helper whose body was edited (not a verbatim cut) never yields a false pass: the
|
||||
reproduction's byte-diff surfaces the bundled change as a non-empty residual."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def run(self):\n"
|
||||
" self.pre()\n"
|
||||
" self.log(1)\n"
|
||||
" self.post()\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def run(self):\n"
|
||||
" self.pre()\n"
|
||||
" self._emit()\n"
|
||||
" self.post()\n"
|
||||
"\n"
|
||||
" def _emit(self):\n"
|
||||
" self.log(2)\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "extract _emit but change the arg")
|
||||
recipe = infer_recipe(commit, str(repo))
|
||||
residual = build_repro(recipe, repo_root=str(repo)).run()
|
||||
assert residual != ""
|
||||
|
||||
|
||||
def test_infer_extract_function_when_block_and_call_share_closing_paren(
|
||||
repo: Path,
|
||||
) -> None:
|
||||
"""The removed block and its replacement call both end in a lone ``)``; the prefix/suffix
|
||||
split must not absorb that shared line, or the extracted body loses its final line.
|
||||
"""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def dispatch(self, n):\n"
|
||||
" if self.flag:\n"
|
||||
" pool = make_pool(\n"
|
||||
" a=n,\n"
|
||||
" b=self.b,\n"
|
||||
" )\n"
|
||||
" return pool\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def dispatch(self, n):\n"
|
||||
" if self.flag:\n"
|
||||
" pool = self._build_pool(\n"
|
||||
" n=n,\n"
|
||||
" )\n"
|
||||
" return pool\n"
|
||||
"\n"
|
||||
" def _build_pool(self, *, n):\n"
|
||||
" pool = make_pool(\n"
|
||||
" a=n,\n"
|
||||
" b=self.b,\n"
|
||||
" )\n"
|
||||
" return pool\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "extract _build_pool")
|
||||
recipe = infer_recipe(commit, str(repo))
|
||||
assert len(recipe.extract_functions) == 1
|
||||
ex = recipe.extract_functions[0]
|
||||
assert ex["body"].rstrip().endswith(")")
|
||||
assert ex["return_text"] == " return pool"
|
||||
assert build_repro(recipe, repo_root=str(repo)).run() == ""
|
||||
|
||||
|
||||
def test_emitted_script_passes_on_extract_function(repo: Path, tmp_path: Path) -> None:
|
||||
"""The recipe for an extract_function reproduces the commit byte-for-byte (bare repo, no
|
||||
formatter) so build_repro returns an empty residual."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def dispatch(self, n):\n"
|
||||
" base = self.setup()\n"
|
||||
" if self.flag:\n"
|
||||
" x = self.a\n"
|
||||
" pool = make(\n"
|
||||
" a=x,\n"
|
||||
" )\n"
|
||||
" return pool\n"
|
||||
"\n"
|
||||
" def keep(self):\n"
|
||||
" return 0\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def dispatch(self, n):\n"
|
||||
" base = self.setup()\n"
|
||||
" if self.flag:\n"
|
||||
" pool = self._build_pool(n=n)\n"
|
||||
" return pool\n"
|
||||
"\n"
|
||||
" def _build_pool(self, *, n):\n"
|
||||
" x = self.a\n"
|
||||
" pool = make(\n"
|
||||
" a=x,\n"
|
||||
" )\n"
|
||||
" return pool\n"
|
||||
"\n"
|
||||
" def keep(self):\n"
|
||||
" return 0\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "extract _build_pool from dispatch")
|
||||
recipe = infer_recipe(commit, str(repo))
|
||||
residual = build_repro(recipe, repo_root=str(repo)).run()
|
||||
assert residual == "", residual
|
||||
assert "extract_function" in recipe_to_script(recipe, "extract")
|
||||
+280
@@ -38,6 +38,56 @@ def test_infer_recipe_method_onto_class(repo: Path) -> None:
|
||||
assert recipe.import_additions == []
|
||||
|
||||
|
||||
def test_infer_recipe_move_before_typechecking_uses_after_anchor(repo: Path) -> None:
|
||||
"""A module-level def relocated to land just above an ``if TYPE_CHECKING:`` guard cannot
|
||||
be anchored with before= (the next def sits past the guard), so the recipe anchors it with
|
||||
after=<the preceding assignment>."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": (
|
||||
"def keep():\n return 0\n\n\ndef helper(x):\n return x + 1\n"
|
||||
),
|
||||
"util.py": (
|
||||
"from u import is_hip\n"
|
||||
"\n"
|
||||
"_is_hip = is_hip()\n"
|
||||
"\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from m import Thing\n"
|
||||
),
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": "def keep():\n return 0\n",
|
||||
"util.py": (
|
||||
"from u import is_hip\n"
|
||||
"\n"
|
||||
"_is_hip = is_hip()\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def helper(x):\n"
|
||||
" return x + 1\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from m import Thing\n"
|
||||
),
|
||||
},
|
||||
)
|
||||
_commit(repo, "move helper above the TYPE_CHECKING guard")
|
||||
recipe = infer_recipe("HEAD", str(repo))
|
||||
assert recipe.supported
|
||||
assert len(recipe.moves) == 1
|
||||
move = recipe.moves[0]
|
||||
assert move["name"] == "helper" and move["dst"] == "util.py"
|
||||
assert move["before"] is None
|
||||
assert move["after"] == "_is_hip"
|
||||
|
||||
|
||||
def test_infer_recipe_free_function_move_uses_requalify(repo: Path) -> None:
|
||||
"""A move to a module-level free function dedents and requalifies the call site
|
||||
(drops the qualifier), rather than lowering a receiver."""
|
||||
@@ -288,3 +338,233 @@ def test_infer_recipe_records_the_source_class_for_disambiguation(repo: Path) ->
|
||||
assert [mv["from_class"] for mv in recipe.moves] == ["M"]
|
||||
script = recipe_to_script(recipe, "move M.foo onto C")
|
||||
assert "from_class='M'" in script
|
||||
|
||||
|
||||
def test_infer_recipe_module_level_def_shadowed_by_method_name(repo: Path) -> None:
|
||||
"""A column-0 cut resolves to the module-level def even when a method shares its name."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": (
|
||||
"def foo(*, x):\n"
|
||||
" return x + 1\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"class M:\n"
|
||||
" def foo(self):\n"
|
||||
" return foo(x=self.x)\n"
|
||||
),
|
||||
"util.py": "def keep():\n return 1\n",
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": (
|
||||
"from util import foo\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"class M:\n"
|
||||
" def foo(self):\n"
|
||||
" return foo(x=self.x)\n"
|
||||
),
|
||||
"util.py": (
|
||||
"def keep():\n"
|
||||
" return 1\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def foo(*, x):\n"
|
||||
" return x + 1\n"
|
||||
),
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "move module-level foo to util")
|
||||
|
||||
recipe = infer_recipe(commit, str(repo))
|
||||
|
||||
assert recipe.supported
|
||||
assert [mv["name"] for mv in recipe.moves] == ["foo"]
|
||||
assert recipe.moves[0]["from_class"] is None
|
||||
assert recipe.moves[0]["into_class"] is None
|
||||
|
||||
|
||||
def test_infer_recipe_class_move_between_existing_files(repo: Path) -> None:
|
||||
"""A top-level class relocated to an existing module moves whole; its methods do not."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": (
|
||||
"class Payload:\n"
|
||||
" def get(self):\n"
|
||||
" return 1\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def stay():\n"
|
||||
" return 2\n"
|
||||
),
|
||||
"comp.py": "def keep():\n return 3\n",
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": "def stay():\n return 2\n",
|
||||
"comp.py": (
|
||||
"def keep():\n"
|
||||
" return 3\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"class Payload:\n"
|
||||
" def get(self):\n"
|
||||
" return 1\n"
|
||||
),
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "move Payload to comp")
|
||||
|
||||
recipe = infer_recipe(commit, str(repo))
|
||||
|
||||
assert recipe.supported
|
||||
assert [mv["name"] for mv in recipe.moves] == ["Payload"]
|
||||
assert recipe.moves[0]["from_class"] is None
|
||||
assert recipe.moves[0]["into_class"] is None
|
||||
|
||||
|
||||
def test_infer_recipe_move_leaving_a_forwarding_delegate(repo: Path) -> None:
|
||||
"""A same-named stub re-added to the source infers leave_delegate on the move."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": (
|
||||
"class M:\n" " def work(self, x):\n" " return x + 1\n"
|
||||
),
|
||||
"comp.py": "class C:\n def keep(self):\n return 1\n",
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": (
|
||||
"class M:\n"
|
||||
" def work(self, x):\n"
|
||||
" return self.comp.work(x)\n"
|
||||
),
|
||||
"comp.py": (
|
||||
"class C:\n"
|
||||
" def keep(self):\n"
|
||||
" return 1\n"
|
||||
"\n"
|
||||
" def work(self, x):\n"
|
||||
" return x + 1\n"
|
||||
),
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "move M.work onto C, leaving a delegate")
|
||||
|
||||
recipe = infer_recipe(commit, str(repo))
|
||||
|
||||
assert recipe.supported
|
||||
assert [mv["name"] for mv in recipe.moves] == ["work"]
|
||||
assert recipe.moves[0]["dst"] == "comp.py"
|
||||
assert recipe.moves[0]["leave_delegate"] == "comp"
|
||||
assert recipe.moves[0]["delegate_name"] is None
|
||||
script = recipe_to_script(recipe, "move with delegate")
|
||||
assert "leave_delegate='comp'" in script
|
||||
|
||||
|
||||
def test_infer_recipe_constant_relocated_with_the_move(repo: Path) -> None:
|
||||
"""A module constant that vanished from the source and appeared in the existing
|
||||
destination becomes a move_assign."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": (
|
||||
"RATIO = 3\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def work(x):\n"
|
||||
" return x * RATIO\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def stay():\n"
|
||||
" return 1\n"
|
||||
),
|
||||
"comp.py": "import os\n\n\ndef keep():\n return 2\n",
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": "def stay():\n return 1\n",
|
||||
"comp.py": (
|
||||
"import os\n"
|
||||
"\n"
|
||||
"RATIO = 3\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def keep():\n"
|
||||
" return 2\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def work(x):\n"
|
||||
" return x * RATIO\n"
|
||||
),
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "move work + RATIO to comp")
|
||||
|
||||
recipe = infer_recipe(commit, str(repo))
|
||||
|
||||
assert recipe.supported
|
||||
assert [am["name"] for am in recipe.assign_moves] == ["RATIO"]
|
||||
script = recipe_to_script(recipe, "move with constant")
|
||||
assert "move_assign" in script
|
||||
|
||||
|
||||
def test_infer_recipe_in_file_method_reorder(repo: Path) -> None:
|
||||
"""A method cut and re-inserted elsewhere in the same class (no other file gains it) infers
|
||||
an in-file move_symbol (src == dst) anchored above its new next sibling."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"m.py": (
|
||||
"class C:\n"
|
||||
" def a(self):\n"
|
||||
" return 1\n"
|
||||
"\n"
|
||||
" def b(self):\n"
|
||||
" return 2\n"
|
||||
"\n"
|
||||
" def c(self):\n"
|
||||
" return 3\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"m.py": (
|
||||
"class C:\n"
|
||||
" def c(self):\n"
|
||||
" return 3\n"
|
||||
"\n"
|
||||
" def a(self):\n"
|
||||
" return 1\n"
|
||||
"\n"
|
||||
" def b(self):\n"
|
||||
" return 2\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "move c above a")
|
||||
recipe = infer_recipe(commit, str(repo))
|
||||
assert recipe.supported
|
||||
assert len(recipe.moves) == 1
|
||||
mv = recipe.moves[0]
|
||||
assert mv["name"] == "c" and mv["src"] == "m.py" and mv["dst"] == "m.py"
|
||||
assert mv["into_class"] == "C" and mv["before"] == "a"
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from generator_testlib import _commit, _write # noqa: F401
|
||||
from mechanical_refactor_proof_generator import _main
|
||||
|
||||
|
||||
def _extract_function_commit(repo: Path) -> str:
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def dispatch(self, n):\n"
|
||||
" x = self.a\n"
|
||||
" y = x + n\n"
|
||||
" return y\n"
|
||||
"\n"
|
||||
" def keep(self):\n"
|
||||
" return 0\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"kv.py": (
|
||||
"class C:\n"
|
||||
" def dispatch(self, n):\n"
|
||||
" y = self._combine(n=n)\n"
|
||||
" return y\n"
|
||||
"\n"
|
||||
" def _combine(self, *, n):\n"
|
||||
" x = self.a\n"
|
||||
" y = x + n\n"
|
||||
" return y\n"
|
||||
"\n"
|
||||
" def keep(self):\n"
|
||||
" return 0\n"
|
||||
)
|
||||
},
|
||||
)
|
||||
return _commit(repo, "extract _combine from dispatch")
|
||||
|
||||
|
||||
def test_single_commit_extract_function_reproduces_instead_of_unsupported(
|
||||
repo: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A pure intra-file extract_function commit run in single-commit mode reproduces (exit 0),
|
||||
not UNSUPPORTED -- the relocates check must count extract_functions like the range path.
|
||||
"""
|
||||
sha = _extract_function_commit(repo)
|
||||
monkeypatch.chdir(repo)
|
||||
assert _main([sha]) == 0
|
||||
|
||||
|
||||
def test_single_commit_pure_rename_is_unsupported(
|
||||
repo: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A commit that relocates no definition (a bare rename) stays UNSUPPORTED with exit 1."""
|
||||
_write(repo, **{"m.py": "def foo():\n return 1\n"})
|
||||
_commit(repo, "base")
|
||||
_write(repo, **{"m.py": "def bar():\n return 1\n"})
|
||||
sha = _commit(repo, "rename foo to bar")
|
||||
monkeypatch.chdir(repo)
|
||||
assert _main([sha]) == 1
|
||||
+140
-1
@@ -25,7 +25,8 @@ def test_recipe_to_script_is_self_contained_and_ordered(repo: Path) -> None:
|
||||
script = recipe_to_script(infer_recipe("HEAD", str(repo)), "move foo onto C")
|
||||
assert "from mechanical_refactor_reproduction_utils import Repro" in script
|
||||
assert script.index("lower_call_sites") < script.index("move_symbol")
|
||||
assert "r.run()" in script
|
||||
assert "residual = r.run()" in script
|
||||
assert "sys.exit(1 if residual else 0)" in script
|
||||
# importing nothing else from the skill keeps the script auditable in isolation
|
||||
assert "mechanical_refactor_verify_utils" not in script
|
||||
assert "mechanical_refactor_proof_generator" not in script
|
||||
@@ -40,6 +41,144 @@ def test_recipe_to_script_orders_import_ops_after_moves(repo: Path) -> None:
|
||||
assert script.index("move_symbol") < script.index("add_import")
|
||||
|
||||
|
||||
def _emit_runnable_script(repo: Path, out: Path, commit: str, subject: str) -> Path:
|
||||
"""Write the emitted script plus its util dependency into a proof-folder layout."""
|
||||
scripts_dir = out / "repro_scripts"
|
||||
scripts_dir.mkdir(parents=True, exist_ok=True)
|
||||
utils_src = Path(__file__).resolve().parents[2] / (
|
||||
"mechanical_refactor_reproduction_utils.py"
|
||||
)
|
||||
(out / "mechanical_refactor_reproduction_utils.py").write_text(
|
||||
utils_src.read_text()
|
||||
)
|
||||
script = recipe_to_script(infer_recipe(commit, str(repo)), subject)
|
||||
script_path = scripts_dir / f"{commit[:9]}.py"
|
||||
script_path.write_text(script)
|
||||
return script_path
|
||||
|
||||
|
||||
def test_emitted_script_exits_zero_on_faithful_commit(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""Running the emitted script on a clean move exits 0 and prints the PASS verdict."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": "def keep():\n return 0\n\n\ndef resolve(m):\n return m\n",
|
||||
"util.py": "import os\n",
|
||||
"caller.py": (
|
||||
"from model import resolve\n\n\ndef run(m):\n return resolve(m)\n"
|
||||
),
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
# The after-state is the primitives' exact output (this bare repo has no formatter
|
||||
# to absorb the cut's leftover blank lines, unlike a pre-commit-clean real repo).
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": "def keep():\n return 0\n\n\n",
|
||||
"util.py": "import os\n\ndef resolve(m):\n return m\n",
|
||||
"caller.py": (
|
||||
"from util import resolve\n\n\ndef run(m):\n return resolve(m)\n"
|
||||
),
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "move resolve to util")
|
||||
script_path = _emit_runnable_script(repo, tmp_path / "out", commit, "move")
|
||||
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(script_path)], cwd=repo, capture_output=True, text=True
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert "PASS" in result.stdout
|
||||
|
||||
|
||||
def test_emitted_script_exits_nonzero_on_bundled_change(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A commit bundling a non-move change makes the emitted script exit non-zero."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": "def keep():\n return 0\n\n\ndef resolve(m):\n return m\n",
|
||||
"util.py": "import os\n",
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": "def keep():\n return 99\n",
|
||||
"util.py": "import os\n\n\ndef resolve(m):\n return m\n",
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "move resolve AND change keep")
|
||||
script_path = _emit_runnable_script(repo, tmp_path / "out", commit, "dirty move")
|
||||
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(script_path)], cwd=repo, capture_output=True, text=True
|
||||
)
|
||||
|
||||
assert result.returncode == 1, result.stdout + result.stderr
|
||||
assert "RESIDUAL" in result.stdout
|
||||
|
||||
|
||||
def test_emitted_script_passes_on_move_above_typechecking_guard(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A module-level def relocated to just above an ``if TYPE_CHECKING:`` guard reproduces
|
||||
via an inferred after= anchor and the emitted script exits 0."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": (
|
||||
"def keep():\n return 0\n\n\ndef helper(x):\n return x + 1\n"
|
||||
),
|
||||
"util.py": (
|
||||
"from u import is_hip\n"
|
||||
"\n"
|
||||
"_is_hip = is_hip()\n"
|
||||
"\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from m import Thing\n"
|
||||
),
|
||||
},
|
||||
)
|
||||
_commit(repo, "base")
|
||||
# After-state = the primitive's exact output (bare repo, no formatter to absorb blanks).
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": "def keep():\n return 0\n\n\n",
|
||||
"util.py": (
|
||||
"from u import is_hip\n"
|
||||
"\n"
|
||||
"_is_hip = is_hip()\n"
|
||||
"\n"
|
||||
"def helper(x):\n"
|
||||
" return x + 1\n"
|
||||
"\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from m import Thing\n"
|
||||
),
|
||||
},
|
||||
)
|
||||
commit = _commit(repo, "move helper above the TYPE_CHECKING guard")
|
||||
script_path = _emit_runnable_script(
|
||||
repo, tmp_path / "out", commit, "after-anchor move"
|
||||
)
|
||||
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(script_path)], cwd=repo, capture_output=True, text=True
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert "PASS" in result.stdout
|
||||
assert "after='_is_hip'" in script_path.read_text()
|
||||
|
||||
|
||||
def test_per_file_diff_keeps_content_lines_starting_with_plus_signs(repo: Path) -> None:
|
||||
"""An added content line beginning with '++' is collected, not mistaken for a header."""
|
||||
from mechanical_refactor_proof_generator import _per_file_diff
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
_PASSING_PROOF = (
|
||||
"import sys\n"
|
||||
'print("PASS: reproduces the commit byte-for-byte.")\n'
|
||||
"sys.exit(0)\n"
|
||||
)
|
||||
_FAILING_PROOF = (
|
||||
"import sys\n" 'print("RESIDUAL (2 lines):\\n+x\\n-y")\n' "sys.exit(1)\n"
|
||||
)
|
||||
|
||||
|
||||
def _git(repo: Path, *args: str) -> str:
|
||||
return subprocess.run(
|
||||
["git", *args], cwd=repo, check=True, capture_output=True, text=True
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
def _write(repo: Path, **files: "str | None") -> None:
|
||||
for name, content in files.items():
|
||||
path = repo / name.replace("__", "/")
|
||||
if content is None:
|
||||
path.unlink()
|
||||
else:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content)
|
||||
|
||||
|
||||
def _commit(repo: Path, message: str) -> str:
|
||||
_git(repo, "add", "-A")
|
||||
_git(repo, "commit", "-q", "-m", message)
|
||||
return _git(repo, "rev-parse", "HEAD")
|
||||
|
||||
|
||||
def _chain(repo: Path, messages: "list[str]") -> "tuple[str, list[str]]":
|
||||
"""A base commit plus one single-file commit per message, on a `chain` branch.
|
||||
Returns (base_sha, commit_shas)."""
|
||||
_write(repo, **{"seed.py": "SEED = 0\n"})
|
||||
base = _commit(repo, "base")
|
||||
_git(repo, "switch", "-q", "-c", "chain")
|
||||
shas: "list[str]" = []
|
||||
for i, message in enumerate(messages):
|
||||
_write(repo, **{f"file_{i}.py": f"VALUE = {i}\n"})
|
||||
shas.append(_commit(repo, message))
|
||||
return base, shas
|
||||
|
||||
|
||||
def _write_stub_proof(
|
||||
proof_dir: Path,
|
||||
sha: str,
|
||||
*,
|
||||
passing: bool = True,
|
||||
flat: bool = False,
|
||||
stem_len: int = 9,
|
||||
) -> Path:
|
||||
"""A stand-in proof script printing the arbiter's verdict line and exiting to match."""
|
||||
directory = proof_dir if flat else proof_dir / "repro_scripts"
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f"{sha[:stem_len]}.py"
|
||||
path.write_text(_PASSING_PROOF if passing else _FAILING_PROOF)
|
||||
return path
|
||||
@@ -0,0 +1,20 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from cli_testlib import _git
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo(tmp_path: Path) -> Path:
|
||||
root = tmp_path / "repo"
|
||||
root.mkdir()
|
||||
_git(root, "init", "-q", "-b", "main")
|
||||
_git(root, "config", "user.email", "test@example.com")
|
||||
_git(root, "config", "user.name", "test")
|
||||
_git(root, "config", "commit.gpgsign", "false")
|
||||
return root
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from cli_testlib import _chain, _write_stub_proof
|
||||
from mechanical_refactor_reproduction_cli import (
|
||||
KIND_MECHANICAL,
|
||||
KIND_NON_MECHANICAL,
|
||||
VERDICT_AMBIGUOUS_KIND,
|
||||
VERDICT_HUMAN_REVIEW,
|
||||
VERDICT_PASS,
|
||||
VERDICT_UNCLASSIFIED,
|
||||
verify_chain,
|
||||
)
|
||||
|
||||
|
||||
def _single_verdict(repo: Path, tmp_path: Path, message: str, *, with_proof: bool):
|
||||
proof = tmp_path / "proof"
|
||||
proof.mkdir(exist_ok=True)
|
||||
base, shas = _chain(repo, [message])
|
||||
if with_proof:
|
||||
_write_stub_proof(proof, shas[0])
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
return result.verdicts[0]
|
||||
|
||||
|
||||
def test_mechanical_provable_word_classifies_the_commit_as_mechanical(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A message carrying mechanical_provable is classified mechanical and needs a proof."""
|
||||
verdict = _single_verdict(
|
||||
repo, tmp_path, "grp(step,mechanical_provable): move foo", with_proof=True
|
||||
)
|
||||
assert verdict.kind == KIND_MECHANICAL
|
||||
assert verdict.verdict == VERDICT_PASS
|
||||
|
||||
|
||||
def test_non_mechanical_provable_word_is_not_double_counted_as_the_bare_word(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""non_mechanical_provable classifies as non-mechanical, not as both words at once."""
|
||||
verdict = _single_verdict(
|
||||
repo,
|
||||
tmp_path,
|
||||
"grp(step,non_mechanical_provable): rework foo",
|
||||
with_proof=False,
|
||||
)
|
||||
assert verdict.kind == KIND_NON_MECHANICAL
|
||||
assert verdict.verdict == VERDICT_HUMAN_REVIEW
|
||||
|
||||
|
||||
def test_message_without_either_word_is_unclassified_and_fails_the_chain(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A commit missing both words gets UNCLASSIFIED and the chain does not pass."""
|
||||
proof = tmp_path / "proof"
|
||||
proof.mkdir()
|
||||
base, _ = _chain(repo, ["plain subject with no kind word"])
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
assert result.verdicts[0].verdict == VERDICT_UNCLASSIFIED
|
||||
assert result.verdicts[0].kind is None
|
||||
assert not result.passed
|
||||
|
||||
|
||||
def test_message_with_both_words_is_ambiguous(repo: Path, tmp_path: Path) -> None:
|
||||
"""A commit declaring both kinds gets AMBIGUOUS_KIND and fails the chain."""
|
||||
verdict = _single_verdict(
|
||||
repo,
|
||||
tmp_path,
|
||||
"subject mechanical_provable\n\nbody also says non_mechanical_provable",
|
||||
with_proof=True,
|
||||
)
|
||||
assert verdict.verdict == VERDICT_AMBIGUOUS_KIND
|
||||
assert verdict.kind is None
|
||||
|
||||
|
||||
def test_kind_word_must_stand_alone_not_as_a_substring(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""xmechanical_provable / mechanical_provable_x do not count as the standalone word."""
|
||||
verdict = _single_verdict(
|
||||
repo,
|
||||
tmp_path,
|
||||
"xmechanical_provable and mechanical_provable_x only",
|
||||
with_proof=False,
|
||||
)
|
||||
assert verdict.verdict == VERDICT_UNCLASSIFIED
|
||||
|
||||
|
||||
def test_kind_word_delimited_by_punctuation_counts(repo: Path, tmp_path: Path) -> None:
|
||||
"""The word inside punctuation, e.g. (step,mechanical_provable), is a valid match."""
|
||||
verdict = _single_verdict(
|
||||
repo, tmp_path, "grp(step,mechanical_provable): move", with_proof=True
|
||||
)
|
||||
assert verdict.kind == KIND_MECHANICAL
|
||||
|
||||
|
||||
def test_repeating_the_same_kind_word_is_accepted(repo: Path, tmp_path: Path) -> None:
|
||||
"""Multiple occurrences of one kind word still classify unambiguously."""
|
||||
verdict = _single_verdict(
|
||||
repo,
|
||||
tmp_path,
|
||||
"mechanical_provable move\n\nthis commit is mechanical_provable",
|
||||
with_proof=True,
|
||||
)
|
||||
assert verdict.kind == KIND_MECHANICAL
|
||||
assert verdict.verdict == VERDICT_PASS
|
||||
|
||||
|
||||
def test_kind_word_in_the_body_counts_when_subject_is_free_form(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""Classification scans the whole message, so a body-only word is enough."""
|
||||
verdict = _single_verdict(
|
||||
repo,
|
||||
tmp_path,
|
||||
"Move resolve to util\n\nKind: non_mechanical_provable",
|
||||
with_proof=False,
|
||||
)
|
||||
assert verdict.kind == KIND_NON_MECHANICAL
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from cli_testlib import _chain, _write_stub_proof
|
||||
from mechanical_refactor_reproduction_cli import (
|
||||
VERDICT_AMBIGUOUS_PROOF,
|
||||
VERDICT_MISSING_PROOF,
|
||||
VERDICT_PASS,
|
||||
verify_chain,
|
||||
)
|
||||
|
||||
_MSG = "mechanical_provable: move foo"
|
||||
|
||||
|
||||
def _run_single(repo: Path, proof: Path):
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
return shas[0], verify_chain(
|
||||
base=base, branch="chain", proof=proof, repo_root=str(repo)
|
||||
)
|
||||
|
||||
|
||||
def test_proof_is_found_under_repro_scripts_by_sha_prefix(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""The generator layout repro_scripts/<sha9>.py resolves to the commit's proof."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
_write_stub_proof(proof, shas[0], stem_len=9)
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
assert result.verdicts[0].verdict == VERDICT_PASS
|
||||
|
||||
|
||||
def test_proof_is_found_flat_in_the_proof_folder_by_full_sha(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A flat <proof>/<full-sha>.py layout is also accepted."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
_write_stub_proof(proof, shas[0], flat=True, stem_len=40)
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
assert result.verdicts[0].verdict == VERDICT_PASS
|
||||
|
||||
|
||||
def test_provable_commit_without_a_proof_script_is_missing_proof(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A mechanical_provable commit with no matching script fails as MISSING_PROOF."""
|
||||
proof = tmp_path / "proof"
|
||||
proof.mkdir()
|
||||
sha, result = _run_single(repo, proof)
|
||||
assert result.verdicts[0].verdict == VERDICT_MISSING_PROOF
|
||||
assert not result.passed
|
||||
|
||||
|
||||
def test_unrelated_and_non_hex_scripts_do_not_match(repo: Path, tmp_path: Path) -> None:
|
||||
"""Scripts named for another sha or with a non-hex stem are not this commit's proof."""
|
||||
proof = tmp_path / "proof"
|
||||
scripts = proof / "repro_scripts"
|
||||
scripts.mkdir(parents=True)
|
||||
(scripts / "0123456789abcdef.py").write_text("raise SystemExit(1)\n")
|
||||
(scripts / "not_a_sha.py").write_text("raise SystemExit(1)\n")
|
||||
sha, result = _run_single(repo, proof)
|
||||
assert result.verdicts[0].verdict == VERDICT_MISSING_PROOF
|
||||
|
||||
|
||||
def test_two_scripts_matching_one_commit_are_ambiguous(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A commit matched by both a nested and a flat script fails as AMBIGUOUS_PROOF."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
_write_stub_proof(proof, shas[0], stem_len=9)
|
||||
_write_stub_proof(proof, shas[0], flat=True, stem_len=12)
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
assert result.verdicts[0].verdict == VERDICT_AMBIGUOUS_PROOF
|
||||
assert not result.passed
|
||||
|
||||
|
||||
def test_short_hex_stem_below_minimum_length_is_ignored(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A 6-char hex stem is too short to name a commit and is not treated as a proof."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
_write_stub_proof(proof, shas[0], stem_len=6)
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
assert result.verdicts[0].verdict == VERDICT_MISSING_PROOF
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from cli_testlib import _chain, _write_stub_proof
|
||||
from mechanical_refactor_reproduction_cli import main, render_report, verify_chain
|
||||
|
||||
|
||||
def _mixed_chain_result(repo: Path, tmp_path: Path):
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(
|
||||
repo,
|
||||
[
|
||||
"mechanical_provable: move foo",
|
||||
"non_mechanical_provable: rework bar",
|
||||
"mechanical_provable: move baz",
|
||||
],
|
||||
)
|
||||
_write_stub_proof(proof, shas[0])
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
return proof, base, shas, result
|
||||
|
||||
|
||||
def test_report_has_header_table_row_per_commit_and_chain_verdict(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""The report carries base/branch/proof, one table row per commit, and the verdict."""
|
||||
proof, base, shas, result = _mixed_chain_result(repo, tmp_path)
|
||||
report = render_report(result)
|
||||
|
||||
assert "# Mechanical refactor chain report" in report
|
||||
assert f"`{base[:12]}`" in report
|
||||
assert "chain verdict: **FAIL**" in report
|
||||
assert "3 total — 2 mechanical_provable, 1 non_mechanical_provable" in report
|
||||
for sha in shas:
|
||||
assert f"`{sha[:9]}`" in report
|
||||
assert "| mechanical_provable | PASS |" in report
|
||||
assert "| non_mechanical_provable | HUMAN_REVIEW |" in report
|
||||
assert "| mechanical_provable | MISSING_PROOF |" in report
|
||||
|
||||
|
||||
def test_report_lists_failure_details_for_each_non_ok_commit(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""Every non-ok commit gets a failure-details section with its explanation."""
|
||||
proof, base, shas, result = _mixed_chain_result(repo, tmp_path)
|
||||
report = render_report(result)
|
||||
|
||||
assert "## Failure details" in report
|
||||
assert f"### `{shas[2][:9]}` — MISSING_PROOF" in report
|
||||
assert "no proof script found" in report
|
||||
|
||||
|
||||
def test_passing_report_has_no_failure_details_section(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A fully verified chain renders a PASS report without a failure section."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, ["mechanical_provable: move foo"])
|
||||
_write_stub_proof(proof, shas[0])
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
report = render_report(result)
|
||||
|
||||
assert "chain verdict: **PASS**" in report
|
||||
assert "proofs: 1/1 PASS" in report
|
||||
assert "## Failure details" not in report
|
||||
|
||||
|
||||
def test_main_writes_the_report_into_the_proof_folder_by_default(
|
||||
repo: Path, tmp_path: Path, capsys
|
||||
) -> None:
|
||||
"""main prints the report and writes <proof>/chain_report.md (or --report PATH)."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, ["mechanical_provable: move foo"])
|
||||
_write_stub_proof(proof, shas[0])
|
||||
args = [
|
||||
"--base",
|
||||
base,
|
||||
"--branch",
|
||||
"chain",
|
||||
"--proof",
|
||||
str(proof),
|
||||
"--repo-root",
|
||||
str(repo),
|
||||
]
|
||||
|
||||
assert main(args) == 0
|
||||
default_report = proof / "chain_report.md"
|
||||
assert "chain verdict: **PASS**" in default_report.read_text()
|
||||
assert "chain verdict: **PASS**" in capsys.readouterr().out
|
||||
|
||||
custom = tmp_path / "custom_report.md"
|
||||
assert main([*args, "--report", str(custom)]) == 0
|
||||
assert "chain verdict: **PASS**" in custom.read_text()
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from cli_testlib import _chain, _write_stub_proof
|
||||
from mechanical_refactor_reproduction_cli import (
|
||||
VERDICT_FAIL,
|
||||
VERDICT_PASS,
|
||||
main,
|
||||
render_report,
|
||||
verify_chain,
|
||||
)
|
||||
|
||||
_MSG = "mechanical_provable: move foo"
|
||||
|
||||
|
||||
def _counting_proof(script: Path, counter: Path, *, passing: bool = True) -> None:
|
||||
"""Make the stub proof bump a run counter so re-execution is observable."""
|
||||
verdict = (
|
||||
'print("PASS: reproduces the commit byte-for-byte.")\nsys.exit(0)\n'
|
||||
if passing
|
||||
else 'print("RESIDUAL (1 lines):\\n+x")\nsys.exit(1)\n'
|
||||
)
|
||||
script.write_text(
|
||||
"import sys\n"
|
||||
f"counter = __import__('pathlib').Path({str(counter)!r})\n"
|
||||
"runs = int(counter.read_text()) if counter.exists() else 0\n"
|
||||
"counter.write_text(str(runs + 1))\n" + verdict
|
||||
)
|
||||
|
||||
|
||||
def _cache_file(repo: Path) -> Path:
|
||||
return repo / ".git" / "mechanical_refactor_passed_proofs.json"
|
||||
|
||||
|
||||
def test_skip_passed_reuses_an_unchanged_pass_without_rerunning(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A PASS recorded on the first run is reused: the proof does not execute again."""
|
||||
proof = tmp_path / "proof"
|
||||
counter = tmp_path / "runs"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
_counting_proof(_write_stub_proof(proof, shas[0]), counter)
|
||||
args = dict(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
|
||||
first = verify_chain(**args)
|
||||
assert first.verdicts[0].verdict == VERDICT_PASS
|
||||
assert counter.read_text() == "1"
|
||||
|
||||
second = verify_chain(**args, skip_passed=True)
|
||||
assert second.verdicts[0].verdict == VERDICT_PASS
|
||||
assert second.verdicts[0].cached
|
||||
assert counter.read_text() == "1"
|
||||
assert second.passed
|
||||
|
||||
|
||||
def test_without_the_flag_the_proof_always_reruns(repo: Path, tmp_path: Path) -> None:
|
||||
"""The cache is recorded on every run but consulted only under skip_passed."""
|
||||
proof = tmp_path / "proof"
|
||||
counter = tmp_path / "runs"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
_counting_proof(_write_stub_proof(proof, shas[0]), counter)
|
||||
args = dict(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
|
||||
verify_chain(**args)
|
||||
result = verify_chain(**args)
|
||||
|
||||
assert counter.read_text() == "2"
|
||||
assert not result.verdicts[0].cached
|
||||
|
||||
|
||||
def test_editing_the_proof_script_invalidates_the_cache(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A changed script hash misses the cache, so the edited (failing) proof reruns."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
script = _write_stub_proof(proof, shas[0])
|
||||
|
||||
verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
script.write_text('print("RESIDUAL (1 lines):\\n+x")\nraise SystemExit(1)\n')
|
||||
result = verify_chain(
|
||||
base=base, branch="chain", proof=proof, repo_root=str(repo), skip_passed=True
|
||||
)
|
||||
|
||||
assert result.verdicts[0].verdict == VERDICT_FAIL
|
||||
|
||||
|
||||
def test_editing_the_utils_copy_invalidates_the_cache(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""The utils module next to the scripts is part of the key: editing it forces a rerun."""
|
||||
proof = tmp_path / "proof"
|
||||
counter = tmp_path / "runs"
|
||||
utils = proof / "mechanical_refactor_reproduction_utils.py"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
_counting_proof(_write_stub_proof(proof, shas[0]), counter)
|
||||
utils.parent.mkdir(parents=True, exist_ok=True)
|
||||
utils.write_text("ENGINE = 1\n")
|
||||
args = dict(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
|
||||
verify_chain(**args)
|
||||
utils.write_text("ENGINE = 2\n")
|
||||
result = verify_chain(**args, skip_passed=True)
|
||||
|
||||
assert counter.read_text() == "2"
|
||||
assert not result.verdicts[0].cached
|
||||
|
||||
|
||||
def test_a_fail_is_never_recorded_in_the_cache(repo: Path, tmp_path: Path) -> None:
|
||||
"""Only PASS verdicts enter the cache; a failing proof leaves no entry for its sha."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
_write_stub_proof(proof, shas[0], passing=False)
|
||||
|
||||
verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
|
||||
cache = _cache_file(repo)
|
||||
assert not cache.exists() or shas[0] not in json.loads(cache.read_text())["passed"]
|
||||
|
||||
|
||||
def test_corrupt_cache_file_is_treated_as_empty(repo: Path, tmp_path: Path) -> None:
|
||||
"""A garbage cache file never crashes the walk; the proof simply runs."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
_write_stub_proof(proof, shas[0])
|
||||
_cache_file(repo).write_text("{not json")
|
||||
|
||||
result = verify_chain(
|
||||
base=base, branch="chain", proof=proof, repo_root=str(repo), skip_passed=True
|
||||
)
|
||||
|
||||
assert result.verdicts[0].verdict == VERDICT_PASS
|
||||
assert not result.verdicts[0].cached
|
||||
|
||||
|
||||
def test_cache_lives_in_the_git_common_dir_and_records_the_pass(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A PASS writes the (sha, script hash, utils hash) entry under .git/."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
_write_stub_proof(proof, shas[0])
|
||||
|
||||
verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
|
||||
entry = json.loads(_cache_file(repo).read_text())["passed"][shas[0]]
|
||||
assert set(entry) == {"script_sha256", "utils_sha256"}
|
||||
assert len(entry["script_sha256"]) == 64
|
||||
|
||||
|
||||
def test_report_counts_reused_proofs_and_main_accepts_the_flag(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""The report carries the reused count and --skip-passed works through main."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, [_MSG])
|
||||
_write_stub_proof(proof, shas[0])
|
||||
cli_args = [
|
||||
"--base",
|
||||
base,
|
||||
"--branch",
|
||||
"chain",
|
||||
"--proof",
|
||||
str(proof),
|
||||
"--repo-root",
|
||||
str(repo),
|
||||
]
|
||||
|
||||
assert main(cli_args) == 0
|
||||
result = verify_chain(
|
||||
base=base, branch="chain", proof=proof, repo_root=str(repo), skip_passed=True
|
||||
)
|
||||
report = render_report(result)
|
||||
|
||||
assert "reused from the passed-proof cache (--skip-passed): 1" in report
|
||||
assert main([*cli_args, "--skip-passed"]) == 0
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from cli_testlib import _chain, _commit, _git, _write, _write_stub_proof
|
||||
from mechanical_refactor_proof_generator import generate_range
|
||||
from mechanical_refactor_reproduction_cli import (
|
||||
VERDICT_FAIL,
|
||||
VERDICT_HUMAN_REVIEW,
|
||||
VERDICT_PASS,
|
||||
ChainVerificationError,
|
||||
main,
|
||||
verify_chain,
|
||||
)
|
||||
|
||||
|
||||
def test_chain_of_proved_and_declared_commits_passes(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A proved mechanical commit plus a declared non-mechanical one verifies as PASS."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(
|
||||
repo,
|
||||
["mechanical_provable: move foo", "non_mechanical_provable: rework bar"],
|
||||
)
|
||||
_write_stub_proof(proof, shas[0])
|
||||
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
|
||||
assert [v.verdict for v in result.verdicts] == [VERDICT_PASS, VERDICT_HUMAN_REVIEW]
|
||||
assert result.passed
|
||||
|
||||
|
||||
def test_failing_proof_fails_the_commit_and_the_chain(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A proof that exits non-zero yields FAIL with the output tail in the detail."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, ["mechanical_provable: move foo"])
|
||||
_write_stub_proof(proof, shas[0], passing=False)
|
||||
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
|
||||
assert result.verdicts[0].verdict == VERDICT_FAIL
|
||||
assert "RESIDUAL" in result.verdicts[0].detail
|
||||
assert not result.passed
|
||||
|
||||
|
||||
def test_proof_exiting_zero_without_a_pass_line_is_a_fail(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""PASS needs exit 0 AND the PASS: verdict line, so a residual under exit 0 fails."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, ["mechanical_provable: move foo"])
|
||||
script = _write_stub_proof(proof, shas[0])
|
||||
script.write_text('print("RESIDUAL (1 lines):\\n+x")\n')
|
||||
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
|
||||
assert result.verdicts[0].verdict == VERDICT_FAIL
|
||||
|
||||
|
||||
def test_main_exit_codes_reflect_the_chain_verdict(repo: Path, tmp_path: Path) -> None:
|
||||
"""main returns 0 for a verified chain and 1 once an unverifiable commit appears."""
|
||||
proof = tmp_path / "proof"
|
||||
base, shas = _chain(repo, ["mechanical_provable: move"])
|
||||
_write_stub_proof(proof, shas[0])
|
||||
args = [
|
||||
"--base",
|
||||
base,
|
||||
"--branch",
|
||||
"chain",
|
||||
"--proof",
|
||||
str(proof),
|
||||
"--repo-root",
|
||||
str(repo),
|
||||
]
|
||||
|
||||
assert main(args) == 0
|
||||
|
||||
_git(repo, "commit", "-q", "--allow-empty", "-m", "plain subject with no kind word")
|
||||
assert main(args) == 1
|
||||
|
||||
|
||||
def test_unresolvable_refs_and_missing_proof_folder_are_setup_errors(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""Bad --base/--branch/--proof inputs raise ChainVerificationError (exit code 2)."""
|
||||
proof = tmp_path / "proof"
|
||||
proof.mkdir()
|
||||
base, _ = _chain(repo, ["mechanical_provable: move"])
|
||||
|
||||
with pytest.raises(ChainVerificationError):
|
||||
verify_chain(
|
||||
base=base, branch="no-such-branch", proof=proof, repo_root=str(repo)
|
||||
)
|
||||
with pytest.raises(ChainVerificationError):
|
||||
verify_chain(
|
||||
base=base,
|
||||
branch="chain",
|
||||
proof=tmp_path / "missing",
|
||||
repo_root=str(repo),
|
||||
)
|
||||
assert (
|
||||
main(
|
||||
[
|
||||
"--base",
|
||||
base,
|
||||
"--branch",
|
||||
"no-such-branch",
|
||||
"--proof",
|
||||
str(proof),
|
||||
"--repo-root",
|
||||
str(repo),
|
||||
]
|
||||
)
|
||||
== 2
|
||||
)
|
||||
|
||||
|
||||
def test_non_ancestor_base_and_empty_range_are_setup_errors(
|
||||
repo: Path, tmp_path: Path
|
||||
) -> None:
|
||||
"""A base off the branch or an empty base..branch range refuses to verify."""
|
||||
proof = tmp_path / "proof"
|
||||
proof.mkdir()
|
||||
base, shas = _chain(repo, ["mechanical_provable: move"])
|
||||
_git(repo, "switch", "-q", "main")
|
||||
_write(repo, **{"other.py": "OTHER = 1\n"})
|
||||
off_branch = _commit(repo, "unrelated main-side commit")
|
||||
|
||||
with pytest.raises(ChainVerificationError):
|
||||
verify_chain(base=off_branch, branch="chain", proof=proof, repo_root=str(repo))
|
||||
with pytest.raises(ChainVerificationError):
|
||||
verify_chain(base=shas[0], branch=shas[0], proof=proof, repo_root=str(repo))
|
||||
|
||||
|
||||
def test_merge_commit_in_the_chain_is_a_setup_error(repo: Path, tmp_path: Path) -> None:
|
||||
"""A non-linear chain (contains a merge commit) refuses to verify."""
|
||||
proof = tmp_path / "proof"
|
||||
proof.mkdir()
|
||||
base, _ = _chain(repo, ["mechanical_provable: move"])
|
||||
_git(repo, "switch", "-q", "main")
|
||||
_write(repo, **{"other.py": "OTHER = 1\n"})
|
||||
_commit(repo, "mechanical_provable: main-side")
|
||||
_git(repo, "switch", "-q", "chain")
|
||||
_git(repo, "merge", "-q", "--no-ff", "-m", "non_mechanical_provable: merge", "main")
|
||||
|
||||
with pytest.raises(ChainVerificationError):
|
||||
verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
|
||||
|
||||
def test_proofs_run_concurrently_up_to_jobs(repo: Path, tmp_path: Path) -> None:
|
||||
"""With jobs>=2 a proof that waits on a sibling proof's sentinel still completes."""
|
||||
proof = tmp_path / "proof"
|
||||
sentinel = tmp_path / "sentinel"
|
||||
base, shas = _chain(
|
||||
repo, ["mechanical_provable: move a", "mechanical_provable: move b"]
|
||||
)
|
||||
waiter = _write_stub_proof(proof, shas[0])
|
||||
waiter.write_text(
|
||||
"import sys, time\n"
|
||||
f"deadline = time.monotonic() + 30\n"
|
||||
f"while not __import__('pathlib').Path({str(sentinel)!r}).exists():\n"
|
||||
" if time.monotonic() > deadline:\n"
|
||||
" sys.exit(1)\n"
|
||||
" time.sleep(0.05)\n"
|
||||
'print("PASS: reproduces the commit byte-for-byte.")\n'
|
||||
"sys.exit(0)\n"
|
||||
)
|
||||
creator = _write_stub_proof(proof, shas[1])
|
||||
creator.write_text(
|
||||
"import sys\n"
|
||||
f"__import__('pathlib').Path({str(sentinel)!r}).write_text('go')\n"
|
||||
'print("PASS: reproduces the commit byte-for-byte.")\n'
|
||||
"sys.exit(0)\n"
|
||||
)
|
||||
|
||||
result = verify_chain(
|
||||
base=base, branch="chain", proof=proof, repo_root=str(repo), jobs=2
|
||||
)
|
||||
|
||||
assert [v.verdict for v in result.verdicts] == [VERDICT_PASS, VERDICT_PASS]
|
||||
assert [v.sha for v in result.verdicts] == shas
|
||||
assert result.passed
|
||||
|
||||
|
||||
def test_end_to_end_with_a_generated_proof_folder(repo: Path, tmp_path: Path) -> None:
|
||||
"""A real move commit proved by generate_range verifies through the CLI end-to-end."""
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": "def keep():\n return 0\n\n\ndef resolve(m):\n return m\n",
|
||||
"util.py": "import os\n",
|
||||
},
|
||||
)
|
||||
base = _commit(repo, "base")
|
||||
_git(repo, "switch", "-q", "-c", "chain")
|
||||
# The after-state is the primitives' exact output (this bare repo has no formatter
|
||||
# to absorb the cut's leftover blank lines, unlike a pre-commit-clean real repo).
|
||||
_write(
|
||||
repo,
|
||||
**{
|
||||
"model.py": "def keep():\n return 0\n\n\n",
|
||||
"util.py": "import os\n\ndef resolve(m):\n return m\n",
|
||||
},
|
||||
)
|
||||
move_sha = _commit(repo, "mechanical_provable: move resolve to util")
|
||||
|
||||
proof = tmp_path / "proof"
|
||||
generate_range(f"{base}..chain", out_dir=str(proof), repo_root=str(repo))
|
||||
result = verify_chain(base=base, branch="chain", proof=proof, repo_root=str(repo))
|
||||
|
||||
assert result.verdicts[0].sha == move_sha
|
||||
assert result.verdicts[0].verdict == VERDICT_PASS
|
||||
assert result.passed
|
||||
+145
-3
@@ -34,6 +34,49 @@ def test_add_import_appends_after_last_top_level_import(tmp_path: Path) -> None:
|
||||
).read_text() == "import os\nimport sys\nfrom pkg import Thing\n\nx = 1\n"
|
||||
|
||||
|
||||
# --- add_imported_name ---------------------------------------------------------
|
||||
|
||||
|
||||
def test_add_imported_name_extends_a_single_line_import(tmp_path: Path) -> None:
|
||||
"""A new name is appended to an existing from-import on the same statement."""
|
||||
(tmp_path / "m.py").write_text("from pkg import a\n\nx = 1\n")
|
||||
r = Repro("b", "t").add_imported_name("m.py", module="pkg", name="b")
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == "from pkg import a, b\n\nx = 1\n"
|
||||
|
||||
|
||||
def test_add_imported_name_carries_an_asname(tmp_path: Path) -> None:
|
||||
"""The added name keeps its `as` alias."""
|
||||
(tmp_path / "m.py").write_text("from pkg import a\n")
|
||||
r = Repro("b", "t").add_imported_name("m.py", module="pkg", name="b", asname="c")
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == "from pkg import a, b as c\n"
|
||||
|
||||
|
||||
def test_add_imported_name_refuses_a_commented_import(tmp_path: Path) -> None:
|
||||
"""An import carrying comments is refused, since a rebuild would drop them."""
|
||||
(tmp_path / "m.py").write_text("from pkg import (\n a, # keep\n)\n")
|
||||
r = Repro("b", "t").add_imported_name("m.py", module="pkg", name="b")
|
||||
with pytest.raises(AssertionError):
|
||||
_apply(r, tmp_path)
|
||||
|
||||
|
||||
def test_add_imported_name_rejects_a_name_already_present(tmp_path: Path) -> None:
|
||||
"""Adding a name the import already has fails loudly."""
|
||||
(tmp_path / "m.py").write_text("from pkg import a, b\n")
|
||||
r = Repro("b", "t").add_imported_name("m.py", module="pkg", name="b")
|
||||
with pytest.raises(AssertionError):
|
||||
_apply(r, tmp_path)
|
||||
|
||||
|
||||
def test_add_imported_name_raises_without_a_matching_import(tmp_path: Path) -> None:
|
||||
"""A file lacking a `from module import` for the module fails loudly."""
|
||||
(tmp_path / "m.py").write_text("from other import a\n")
|
||||
r = Repro("b", "t").add_imported_name("m.py", module="pkg", name="b")
|
||||
with pytest.raises(AssertionError):
|
||||
_apply(r, tmp_path)
|
||||
|
||||
|
||||
# --- repath_import / add_typechecking_import -----------------------------------
|
||||
|
||||
|
||||
@@ -64,6 +107,33 @@ def test_add_typechecking_import_inserts_in_block(tmp_path: Path) -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_add_typechecking_import_creates_missing_block(tmp_path: Path) -> None:
|
||||
"""With no TYPE_CHECKING block, one is created after the trailing module import."""
|
||||
(tmp_path / "m.py").write_text(
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"\n"
|
||||
"from a import X\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def f():\n"
|
||||
" pass\n"
|
||||
)
|
||||
r = Repro("b", "t").add_typechecking_import("m.py", "from b import Y")
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == (
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"\n"
|
||||
"from a import X\n"
|
||||
"\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from b import Y\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def f():\n"
|
||||
" pass\n"
|
||||
)
|
||||
|
||||
|
||||
def test_add_import_into_an_empty_file(tmp_path: Path) -> None:
|
||||
"""Adding an import to an empty file writes just the statement."""
|
||||
(tmp_path / "m.py").write_text("")
|
||||
@@ -134,9 +204,81 @@ def test_add_typechecking_import_after_a_multiline_final_import(tmp_path: Path)
|
||||
)
|
||||
|
||||
|
||||
def test_add_typechecking_import_raises_without_a_block(tmp_path: Path) -> None:
|
||||
"""A file lacking a TYPE_CHECKING block fails loudly."""
|
||||
(tmp_path / "m.py").write_text("import os\n\nx = 1\n")
|
||||
def test_add_typechecking_import_raises_without_imports(tmp_path: Path) -> None:
|
||||
"""A file with no imports cannot anchor a new TYPE_CHECKING block and fails loudly."""
|
||||
(tmp_path / "m.py").write_text("x = 1\n")
|
||||
r = Repro("b", "t").add_typechecking_import("m.py", "from b import Y")
|
||||
with pytest.raises(AssertionError):
|
||||
_apply(r, tmp_path)
|
||||
|
||||
|
||||
def test_add_typechecking_import_drops_a_lone_pass_placeholder(tmp_path: Path) -> None:
|
||||
"""Populating a `pass`-only TYPE_CHECKING block replaces the placeholder."""
|
||||
(tmp_path / "m.py").write_text(
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" pass\n"
|
||||
"\n"
|
||||
"x = 1\n"
|
||||
)
|
||||
r = Repro("b", "t").add_typechecking_import("m.py", "from b import Y")
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == (
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from b import Y\n"
|
||||
"\n"
|
||||
"x = 1\n"
|
||||
)
|
||||
|
||||
|
||||
def test_add_typechecking_import_keeps_a_pass_that_is_not_alone(tmp_path: Path) -> None:
|
||||
"""A `pass` beside a real import is left untouched; only the new import is appended."""
|
||||
(tmp_path / "m.py").write_text(
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from a import X\n"
|
||||
" pass\n"
|
||||
"\n"
|
||||
"x = 1\n"
|
||||
)
|
||||
r = Repro("b", "t").add_typechecking_import("m.py", "from b import Y")
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == (
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from a import X\n"
|
||||
" pass\n"
|
||||
" from b import Y\n"
|
||||
"\n"
|
||||
"x = 1\n"
|
||||
)
|
||||
|
||||
|
||||
# --- add_import(after=...) -----------------------------------------------------
|
||||
|
||||
|
||||
def test_add_import_after_anchors_into_a_split_import_block(tmp_path: Path) -> None:
|
||||
"""With `after`, the import lands right after the named import -- needed when a
|
||||
statement splits the imports into separate blocks and the default (after the last
|
||||
import) would land in the wrong block."""
|
||||
(tmp_path / "m.py").write_text(
|
||||
"import os\n\n_flag = os.getpid()\n\nfrom pkg import a\n\nx = 1\n"
|
||||
)
|
||||
r = Repro("b", "t").add_import("m.py", "from new import Thing", after="import os")
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == (
|
||||
"import os\nfrom new import Thing\n\n_flag = os.getpid()\n\nfrom pkg import a\n\nx = 1\n"
|
||||
)
|
||||
|
||||
|
||||
def test_add_import_after_raises_when_anchor_absent(tmp_path: Path) -> None:
|
||||
"""An `after` substring that matches no top-level import raises."""
|
||||
(tmp_path / "m.py").write_text("import os\n\nx = 1\n")
|
||||
r = Repro("b", "t").add_import("m.py", "from new import Thing", after="import nope")
|
||||
with pytest.raises(AssertionError):
|
||||
_apply(r, tmp_path)
|
||||
|
||||
+32
@@ -79,6 +79,38 @@ def test_requalify_call_sites_drops_the_qualifier(tmp_path: Path) -> None:
|
||||
assert (tmp_path / "m.py").read_text() == "y = bar(a, b)\n"
|
||||
|
||||
|
||||
def test_route_call_sites_through_field_inserts_the_field(tmp_path: Path) -> None:
|
||||
"""recv.bar(a) becomes recv.updater.bar(a) when bar moves onto a collaborator field."""
|
||||
(tmp_path / "m.py").write_text("y = self.worker.runner.bar(a)\n")
|
||||
r = Repro("b", "t").route_call_sites_through_field(
|
||||
"bar", field="updater", paths=["m.py"]
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == "y = self.worker.runner.updater.bar(a)\n"
|
||||
|
||||
|
||||
def test_route_call_sites_through_field_skips_an_already_routed_call(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A call already going through the field is left alone, so the pass converges."""
|
||||
(tmp_path / "m.py").write_text("y = self.runner.updater.bar(a)\n")
|
||||
r = Repro("b", "t").route_call_sites_through_field(
|
||||
"bar", field="updater", paths=["m.py"]
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == "y = self.runner.updater.bar(a)\n"
|
||||
|
||||
|
||||
def test_route_call_sites_through_field_honors_owner_filter(tmp_path: Path) -> None:
|
||||
"""With owner set, only calls on that exact receiver are routed through the field."""
|
||||
(tmp_path / "m.py").write_text("a = x.bar(1)\nb = y.bar(2)\n")
|
||||
r = Repro("b", "t").route_call_sites_through_field(
|
||||
"bar", field="updater", paths=["m.py"], owner="x"
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == "a = x.updater.bar(1)\nb = y.bar(2)\n"
|
||||
|
||||
|
||||
# --- adversarial audit: call-site rewrites ---------------------------------------
|
||||
|
||||
|
||||
|
||||
+19
@@ -46,4 +46,23 @@ def test_delete_file_on_a_missing_path_is_a_no_op(tmp_path: Path) -> None:
|
||||
assert not (tmp_path / "nope.py").exists()
|
||||
|
||||
|
||||
def test_delete_file_allows_a_bare_module_logger(tmp_path: Path) -> None:
|
||||
"""A leftover module holding only imports and a `logger` is deletable scaffolding."""
|
||||
(tmp_path / "gone.py").write_text(
|
||||
"import logging\n\nlogger = logging.getLogger(__name__)\n"
|
||||
)
|
||||
r = Repro("b", "t").delete_file("gone.py")
|
||||
_apply(r, tmp_path)
|
||||
assert not (tmp_path / "gone.py").exists()
|
||||
|
||||
|
||||
def test_delete_file_still_refuses_a_non_logger_assignment(tmp_path: Path) -> None:
|
||||
"""A leftover module-level assignment other than a logger blocks deletion."""
|
||||
(tmp_path / "live.py").write_text("CONFIG = {'a': 1}\n")
|
||||
r = Repro("b", "t").delete_file("live.py")
|
||||
with pytest.raises(AssertionError):
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "live.py").exists()
|
||||
|
||||
|
||||
# --- adversarial audit: extract_function -----------------------------------------
|
||||
|
||||
+65
@@ -144,6 +144,30 @@ def test_extract_symbols_to_new_module_asserts_unknown_drop_assign(
|
||||
_apply(r, tmp_path)
|
||||
|
||||
|
||||
def test_extract_symbols_to_new_module_header_accepts_a_typechecking_block(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""An authored header may carry an `if TYPE_CHECKING:` import block; the audit accepts it
|
||||
and the block is reproduced verbatim in the new module."""
|
||||
(tmp_path / "src.py").write_text("def moved(x):\n return x\n")
|
||||
header = (
|
||||
"from __future__ import annotations\n"
|
||||
"\n"
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from other import Thing\n"
|
||||
"\n"
|
||||
)
|
||||
r = Repro("b", "t").extract_symbols_to_new_module(
|
||||
"src.py", "new.py", symbols=["moved"], header=header, order=["moved"]
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
new_out = (tmp_path / "new.py").read_text()
|
||||
assert "if TYPE_CHECKING:\n from other import Thing\n" in new_out
|
||||
assert "def moved(x):\n return x\n" in new_out
|
||||
|
||||
|
||||
# --- extract_function ----------------------------------------------------------
|
||||
|
||||
|
||||
@@ -197,3 +221,44 @@ def test_extract_symbols_drop_assigns_preserves_other_targets_of_chained_assign(
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
assert "B" in (tmp_path / "src.py").read_text()
|
||||
|
||||
|
||||
def test_extract_symbols_to_new_module_allows_a_rederived_surviving_constant(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A header constant that also survives verbatim in the source (re-derived boilerplate,
|
||||
e.g. `_is_hip = is_hip()`) is allowed: it is provably not fiction because the same
|
||||
statement remains in the source."""
|
||||
(tmp_path / "src.py").write_text(
|
||||
"from pkg import is_hip\n"
|
||||
"\n"
|
||||
"_is_hip = is_hip()\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def moved():\n"
|
||||
" return _is_hip\n"
|
||||
)
|
||||
header = "from pkg import is_hip\n\n_is_hip = is_hip()\n"
|
||||
r = Repro("b", "t").extract_symbols_to_new_module(
|
||||
"src.py", "new.py", symbols=["moved"], header=header, order=["moved"]
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
assert "_is_hip = is_hip()" in (tmp_path / "src.py").read_text()
|
||||
assert "_is_hip = is_hip()" in (tmp_path / "new.py").read_text()
|
||||
|
||||
|
||||
def test_extract_symbols_to_new_module_rejects_a_fictional_header_constant(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A header constant that is neither dropped from nor surviving in the source is fiction
|
||||
and raises: the audit refuses code the extraction cannot vouch for."""
|
||||
(tmp_path / "src.py").write_text("def moved():\n return 1\n")
|
||||
r = Repro("b", "t").extract_symbols_to_new_module(
|
||||
"src.py",
|
||||
"new.py",
|
||||
symbols=["moved"],
|
||||
header="_fake = evil()\n",
|
||||
order=["moved"],
|
||||
)
|
||||
with pytest.raises(AssertionError):
|
||||
_apply(r, tmp_path)
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from mechanical_refactor_reproduction_utils import Repro
|
||||
from reproduction_testlib import _apply # noqa: F401
|
||||
|
||||
|
||||
def test_move_assign_relocates_a_module_constant(tmp_path: Path) -> None:
|
||||
"""The assignment is cut verbatim from the source and lands after the destination's imports."""
|
||||
(tmp_path / "src.py").write_text(
|
||||
"import os\n\nLIMIT = 480 # seconds\n\n\ndef stay():\n return LIMIT\n"
|
||||
)
|
||||
(tmp_path / "dst.py").write_text("import sys\n\n\ndef keep():\n return 1\n")
|
||||
r = Repro("b", "t").move_assign("LIMIT", src="src.py", dst="dst.py")
|
||||
_apply(r, tmp_path)
|
||||
assert "LIMIT" not in (tmp_path / "src.py").read_text().split("def stay")[0]
|
||||
assert (tmp_path / "dst.py").read_text() == (
|
||||
"import sys\n"
|
||||
"\n"
|
||||
"LIMIT = 480 # seconds\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def keep():\n"
|
||||
" return 1\n"
|
||||
)
|
||||
|
||||
|
||||
def test_move_assign_pastes_above_the_named_sibling(tmp_path: Path) -> None:
|
||||
"""With before=, the constant lands immediately above the named top-level statement."""
|
||||
(tmp_path / "src.py").write_text("RATIO = 3\n")
|
||||
(tmp_path / "dst.py").write_text("def first():\n return 1\n")
|
||||
r = Repro("b", "t").move_assign("RATIO", src="src.py", dst="dst.py", before="first")
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "dst.py").read_text() == (
|
||||
"RATIO = 3\n\ndef first():\n return 1\n"
|
||||
)
|
||||
|
||||
|
||||
def test_move_assign_relocates_an_annotated_constant(tmp_path: Path) -> None:
|
||||
"""An annotated module constant (AnnAssign) is cut verbatim with its annotation intact."""
|
||||
(tmp_path / "src.py").write_text(
|
||||
"import os\n\nLIMIT: int = 480\n\n\ndef stay():\n return LIMIT\n"
|
||||
)
|
||||
(tmp_path / "dst.py").write_text("import sys\n\n\ndef keep():\n return 1\n")
|
||||
r = Repro("b", "t").move_assign("LIMIT", src="src.py", dst="dst.py")
|
||||
_apply(r, tmp_path)
|
||||
assert "LIMIT" not in (tmp_path / "src.py").read_text().split("def stay")[0]
|
||||
assert (tmp_path / "dst.py").read_text() == (
|
||||
"import sys\n"
|
||||
"\n"
|
||||
"LIMIT: int = 480\n"
|
||||
"\n"
|
||||
"\n"
|
||||
"def keep():\n"
|
||||
" return 1\n"
|
||||
)
|
||||
|
||||
|
||||
def test_move_assign_missing_source_raises(tmp_path: Path) -> None:
|
||||
"""A name with no module-level assignment in the source fails loudly."""
|
||||
(tmp_path / "src.py").write_text("x = 1\n")
|
||||
(tmp_path / "dst.py").write_text("import os\n")
|
||||
r = Repro("b", "t").move_assign("MISSING", src="src.py", dst="dst.py")
|
||||
with pytest.raises(AssertionError):
|
||||
_apply(r, tmp_path)
|
||||
+87
@@ -321,6 +321,76 @@ def test_move_symbol_rejects_ambiguous_duplicate_names(tmp_path: Path) -> None:
|
||||
_apply(r, tmp_path)
|
||||
|
||||
|
||||
def test_move_symbol_after_inserts_below_named_function(tmp_path: Path) -> None:
|
||||
"""With after=, the relocated def lands immediately below that sibling def."""
|
||||
(tmp_path / "src.py").write_text("def moved():\n return 1\n")
|
||||
(tmp_path / "dst.py").write_text(
|
||||
"def first():\n return 0\n\n\ndef last():\n return 2\n"
|
||||
)
|
||||
r = Repro("b", "t").move_symbol(
|
||||
"moved", src="src.py", dst="dst.py", into_class=None, after="first"
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
dst_out = (tmp_path / "dst.py").read_text()
|
||||
assert (
|
||||
dst_out.index("def first")
|
||||
< dst_out.index("def moved")
|
||||
< dst_out.index("def last")
|
||||
)
|
||||
|
||||
|
||||
def test_move_symbol_after_assign_lands_before_typechecking_guard(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""after= anchors on a module-level assignment target, landing the def just below it and
|
||||
above a following ``if TYPE_CHECKING:`` guard (which is not a nameable anchor)."""
|
||||
(tmp_path / "src.py").write_text("def helper(x):\n return x + 1\n")
|
||||
(tmp_path / "dst.py").write_text(
|
||||
"from u import is_hip\n"
|
||||
"\n"
|
||||
"_is_hip = is_hip()\n"
|
||||
"\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from m import Thing\n"
|
||||
)
|
||||
r = Repro("b", "t").move_symbol(
|
||||
"helper", src="src.py", dst="dst.py", into_class=None, after="_is_hip"
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
dst_out = (tmp_path / "dst.py").read_text()
|
||||
assert (
|
||||
dst_out.index("_is_hip = is_hip()")
|
||||
< dst_out.index("def helper")
|
||||
< dst_out.index("if TYPE_CHECKING:")
|
||||
)
|
||||
|
||||
|
||||
def test_move_symbol_before_and_after_are_mutually_exclusive(tmp_path: Path) -> None:
|
||||
"""Passing both before= and after= is rejected up front."""
|
||||
(tmp_path / "src.py").write_text("def moved():\n return 1\n")
|
||||
(tmp_path / "dst.py").write_text("def z():\n return 0\n")
|
||||
with pytest.raises(AssertionError):
|
||||
Repro("b", "t").move_symbol(
|
||||
"moved",
|
||||
src="src.py",
|
||||
dst="dst.py",
|
||||
into_class=None,
|
||||
before="z",
|
||||
after="z",
|
||||
)
|
||||
|
||||
|
||||
def test_move_symbol_asserts_when_after_symbol_missing(tmp_path: Path) -> None:
|
||||
"""An after= anchor absent from the destination must raise, not fall back to append."""
|
||||
(tmp_path / "src.py").write_text("def moved():\n return 1\n")
|
||||
(tmp_path / "dst.py").write_text("def z():\n return 0\n")
|
||||
r = Repro("b", "t").move_symbol(
|
||||
"moved", src="src.py", dst="dst.py", into_class=None, after="NO_SUCH_SYMBOL"
|
||||
)
|
||||
with pytest.raises(AssertionError):
|
||||
_apply(r, tmp_path)
|
||||
|
||||
|
||||
def test_move_symbol_asserts_when_before_sibling_missing(tmp_path: Path) -> None:
|
||||
"""A before= anchor absent from the destination must raise, not fall back to append."""
|
||||
(tmp_path / "src.py").write_text("def moved():\n return 1\n")
|
||||
@@ -357,4 +427,21 @@ def test_move_symbol_negative_dedent_indents_into_the_class(tmp_path: Path) -> N
|
||||
assert " def helper(x):\n return x\n" in (tmp_path / "dst.py").read_text()
|
||||
|
||||
|
||||
def test_move_symbol_relocates_a_top_level_class(tmp_path: Path) -> None:
|
||||
"""move_symbol relocates a whole top-level class (with its methods) verbatim."""
|
||||
(tmp_path / "src.py").write_text(
|
||||
"x = 1\n\n\nclass Widget:\n def get(self, rank):\n return rank\n"
|
||||
)
|
||||
(tmp_path / "dst.py").write_text("y = 2\n")
|
||||
r = Repro("b", "t").move_symbol(
|
||||
"Widget", src="src.py", dst="dst.py", into_class=None
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
assert "class Widget:" not in (tmp_path / "src.py").read_text()
|
||||
assert (
|
||||
"class Widget:\n def get(self, rank):\n return rank\n"
|
||||
in (tmp_path / "dst.py").read_text()
|
||||
)
|
||||
|
||||
|
||||
# --- adversarial audit: leave_delegate stubs -------------------------------------
|
||||
|
||||
+118
@@ -193,3 +193,121 @@ def test_move_symbol_async_leave_delegate_awaits_the_forwarded_call(
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
assert "return await self.cfg.compute(n)" in (tmp_path / "src.py").read_text()
|
||||
|
||||
|
||||
def test_move_symbol_leave_delegate_on_self_annotated_staticmethod(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A de-self'd staticmethod (self: Target) moves into Target; the stub drops the
|
||||
decorator and the self annotation."""
|
||||
(tmp_path / "src.py").write_text(
|
||||
"class Runner:\n"
|
||||
" @staticmethod\n"
|
||||
" def work(self: Comp, n: int) -> int:\n"
|
||||
" return n + self.base\n"
|
||||
)
|
||||
(tmp_path / "dst.py").write_text(
|
||||
"class Comp:\n def existing(self):\n return 0\n"
|
||||
)
|
||||
r = Repro("b", "t").move_symbol(
|
||||
"work",
|
||||
src="src.py",
|
||||
dst="dst.py",
|
||||
into_class="Comp",
|
||||
from_class="Runner",
|
||||
drop_self_annotation=True,
|
||||
leave_delegate="comp",
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "src.py").read_text() == (
|
||||
"class Runner:\n"
|
||||
" def work(self, n: int) -> int:\n"
|
||||
" return self.comp.work(n)\n"
|
||||
)
|
||||
assert (tmp_path / "dst.py").read_text() == (
|
||||
"class Comp:\n"
|
||||
" def existing(self):\n"
|
||||
" return 0\n"
|
||||
"\n"
|
||||
" def work(self, n: int) -> int:\n"
|
||||
" return n + self.base\n"
|
||||
)
|
||||
|
||||
|
||||
def test_move_symbol_leave_delegate_keeps_unrelated_self_annotation(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A self annotation naming a class other than the destination survives in the stub."""
|
||||
(tmp_path / "src.py").write_text(
|
||||
"class Mixin:\n"
|
||||
" def work(self: Runner, n: int) -> int:\n"
|
||||
" return n + self.base\n"
|
||||
)
|
||||
(tmp_path / "dst.py").write_text(
|
||||
"class Comp:\n def existing(self):\n return 0\n"
|
||||
)
|
||||
r = Repro("b", "t").move_symbol(
|
||||
"work",
|
||||
src="src.py",
|
||||
dst="dst.py",
|
||||
into_class="Comp",
|
||||
from_class="Mixin",
|
||||
drop_self_annotation=True,
|
||||
leave_delegate="comp",
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "src.py").read_text() == (
|
||||
"class Mixin:\n"
|
||||
" def work(self: Runner, n: int) -> int:\n"
|
||||
" return self.comp.work(n)\n"
|
||||
)
|
||||
|
||||
|
||||
def test_move_symbol_delegate_name_forwards_to_the_renamed_collaborator_method(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""delegate_name makes the stub call a differently-named method on the collaborator."""
|
||||
(tmp_path / "src.py").write_text(
|
||||
"class Mixin:\n"
|
||||
" def compute(self, n: int) -> int:\n"
|
||||
" return n + self.cfg.base\n"
|
||||
)
|
||||
(tmp_path / "dst.py").write_text(
|
||||
"class Cfg:\n def existing(self):\n return 0\n"
|
||||
)
|
||||
r = Repro("b", "t").move_symbol(
|
||||
"compute",
|
||||
src="src.py",
|
||||
dst="dst.py",
|
||||
into_class="Cfg",
|
||||
leave_delegate="cfg",
|
||||
delegate_name="compute_impl",
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
assert "return self.cfg.compute_impl(n)" in (tmp_path / "src.py").read_text()
|
||||
assert "def compute(self, n: int) -> int:" in (tmp_path / "dst.py").read_text()
|
||||
|
||||
|
||||
def test_move_symbol_leave_delegate_on_unannotated_staticmethod_raises(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A staticmethod with no self: Target annotation has no receiver to forward through, so
|
||||
leave_delegate refuses rather than author a bogus self.<field>.<name>(...) stub."""
|
||||
(tmp_path / "src.py").write_text(
|
||||
"class Runner:\n"
|
||||
" @staticmethod\n"
|
||||
" def work(x: int) -> int:\n"
|
||||
" return x + 1\n"
|
||||
)
|
||||
(tmp_path / "dst.py").write_text(
|
||||
"class Comp:\n def existing(self):\n return 0\n"
|
||||
)
|
||||
r = Repro("b", "t").move_symbol(
|
||||
"work",
|
||||
src="src.py",
|
||||
dst="dst.py",
|
||||
into_class="Comp",
|
||||
leave_delegate="comp",
|
||||
)
|
||||
with pytest.raises(AssertionError):
|
||||
_apply(r, tmp_path)
|
||||
|
||||
+15
@@ -118,6 +118,21 @@ def test_remove_import_leaves_other_statements_on_a_semicolon_line(
|
||||
assert "import sys" in out and "print(sys.path)" in out
|
||||
|
||||
|
||||
def test_remove_import_trailing_on_a_semicolon_line_leaves_no_dangling_separator(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Removing the trailing import on a semicolon-joined line drops the dangling ';' too
|
||||
(a trailing space may remain for the formatter to strip, but the separator is gone).
|
||||
"""
|
||||
(tmp_path / "m.py").write_text("import sys; import os\nprint(sys.path)\n")
|
||||
r = Repro("b", "t").remove_import("m.py", "import os")
|
||||
_apply(r, tmp_path)
|
||||
out = (tmp_path / "m.py").read_text()
|
||||
assert ";" not in out
|
||||
assert "import os" not in out
|
||||
assert "import sys" in out and "print(sys.path)" in out
|
||||
|
||||
|
||||
def test_remove_import_does_not_overmatch_a_submodule_import(tmp_path: Path) -> None:
|
||||
"""Removing 'import os' must not also remove 'import os.path'."""
|
||||
(tmp_path / "m.py").write_text("import os\nimport os.path\nprint(os.path.sep)\n")
|
||||
|
||||
+53
-3
@@ -75,16 +75,49 @@ def test_remove_imported_name_asserts_when_absent(tmp_path: Path) -> None:
|
||||
# --- add_import ----------------------------------------------------------------
|
||||
|
||||
|
||||
def test_remove_imported_name_collapses_a_multiline_import_to_one_line(
|
||||
def test_remove_imported_name_preserves_the_multiline_form(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Pruning a name from a parenthesized import rebuilds it as a single sorted-later line."""
|
||||
"""Pruning a name from an exploded import deletes only that line, so the parens and the
|
||||
magic trailing comma survive and the formatter keeps it multi-line (a flat rebuild would
|
||||
collapse an import the target left multi-line)."""
|
||||
(tmp_path / "m.py").write_text(
|
||||
"from pkg import (\n a,\n moved,\n b,\n)\n\nx = a + b\n"
|
||||
)
|
||||
r = Repro("b", "t").remove_imported_name("m.py", module="pkg", name="moved")
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == "from pkg import a, b\n\nx = a + b\n"
|
||||
assert (
|
||||
tmp_path / "m.py"
|
||||
).read_text() == "from pkg import (\n a,\n b,\n)\n\nx = a + b\n"
|
||||
|
||||
|
||||
def test_remove_imported_name_multiline_down_to_one_collapses(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Pruning an exploded import down to a single surviving name collapses it to one line:
|
||||
the formatter does not keep a lone name exploded, so a preserved-multiline form would
|
||||
not match the target."""
|
||||
(tmp_path / "m.py").write_text(
|
||||
"from pkg import (\n moved,\n a,\n)\n\nx = a\n"
|
||||
)
|
||||
r = Repro("b", "t").remove_imported_name("m.py", module="pkg", name="moved")
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == "from pkg import a\n\nx = a\n"
|
||||
|
||||
|
||||
def test_remove_imported_name_down_to_one_with_a_comment_stays_exploded(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A lone survivor that carries a comment stays exploded (a rebuild would drop the
|
||||
comment); only its own line is deleted."""
|
||||
(tmp_path / "m.py").write_text(
|
||||
"from pkg import (\n moved,\n a, # keep me\n)\n\nx = a\n"
|
||||
)
|
||||
r = Repro("b", "t").remove_imported_name("m.py", module="pkg", name="moved")
|
||||
_apply(r, tmp_path)
|
||||
assert (
|
||||
tmp_path / "m.py"
|
||||
).read_text() == "from pkg import (\n a, # keep me\n)\n\nx = a\n"
|
||||
|
||||
|
||||
def test_remove_imported_name_matches_a_relative_module(tmp_path: Path) -> None:
|
||||
@@ -111,3 +144,20 @@ def test_remove_imported_name_preserves_comments_in_a_multiline_import(
|
||||
r = Repro("b", "t").remove_imported_name("m.py", module="pkg", name="moved")
|
||||
_apply(r, tmp_path)
|
||||
assert "# used by frobnicator" in (tmp_path / "m.py").read_text()
|
||||
|
||||
|
||||
def test_remove_imported_name_keep_exploded_holds_a_lone_survivor_multiline(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""With keep_exploded, pruning down to a single survivor deletes only the removed line,
|
||||
so the survivor keeps its magic trailing comma and the import stays multi-line (the
|
||||
author's choice, which the source cannot reveal). A regenerating impl would collapse.
|
||||
"""
|
||||
(tmp_path / "m.py").write_text(
|
||||
"from pkg import (\n moved,\n a,\n)\n\nx = a\n"
|
||||
)
|
||||
r = Repro("b", "t").remove_imported_name(
|
||||
"m.py", module="pkg", name="moved", keep_exploded=True
|
||||
)
|
||||
_apply(r, tmp_path)
|
||||
assert (tmp_path / "m.py").read_text() == "from pkg import (\n a,\n)\n\nx = a\n"
|
||||
|
||||
Reference in New Issue
Block a user