Repository navigation
Expand file tree
/
Copy pathtest_patch_claude_code.py
More file actions
223 lines (168 loc) · 8.8 KB
/
Copy pathtest_patch_claude_code.py
File metadata and controls
223 lines (168 loc) · 8.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
"""Check that patch-claude-code, when interrupted while writing a file,
leaves no half-written file that a later run would trust, that it applies
a group of patterns wholly or not at all, that it applies a pattern only
if its regex matches as many times as expected, and that it does not write
a JS file with a syntax error."""
import importlib.machinery
import importlib.util
import os
import re
import shutil
import subprocess
from pathlib import Path
import pytest
PATCHER = Path(__file__).resolve().with_name("patch-claude-code")
ORIGINAL = b"let size=13;\n"
PATCHED = b"let size=12;\n"
def load_patcher() -> object:
"""Import the patcher script (which has no .py suffix) as a module."""
loader = importlib.machinery.SourceFileLoader("patch_claude_code", str(PATCHER))
module = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))
loader.exec_module(module)
return module
patcher = load_patcher()
PATTERNS = [patcher.Pattern(re.compile(r"size=13"), "size=12")]
class Interrupted(BaseException):
"""The simulated interruption. Like KeyboardInterrupt, it is not an
Exception, but pytest does not take it as the user stopping the tests."""
def interrupt_write(monkeypatch: pytest.MonkeyPatch, path: Path) -> None:
"""Make the patcher's next write of `path` raise Interrupted once that
write's data is in the .patching file but before it is renamed over
`path`, as if the user hit Ctrl-C there."""
temp = str(path.resolve().with_name(path.name + patcher.TEMP_SUFFIX))
real_fsync = patcher.os.fsync
def fsync(fd: int) -> None:
if os.readlink(f"/proc/self/fd/{fd}") == temp:
raise Interrupted
real_fsync(fd)
monkeypatch.setattr(patcher.os, "fsync", fsync)
@pytest.fixture
def target(tmp_path: Path) -> Path:
"""Return the path of an unpatched extension file."""
path = tmp_path / "index.js"
path.write_bytes(ORIGINAL)
return path
def backup_of(path: Path) -> Path:
"""Return the path of the backup that the patcher keeps of `path`."""
return path.with_name(path.name + patcher.BACKUP_SUFFIX)
def assert_no_temp_files(directory: Path) -> None:
assert not list(directory.glob(f"*{patcher.TEMP_SUFFIX}"))
needs_node = pytest.mark.skipif(shutil.which("node") is None, reason="no node to check JS syntax with")
def test_interrupted_backup_write_leaves_no_backup(target: Path, monkeypatch: pytest.MonkeyPatch) -> None:
interrupt_write(monkeypatch, backup_of(target))
with pytest.raises(Interrupted):
patcher.patch_file(target, PATTERNS, None)
assert not backup_of(target).exists()
assert target.read_bytes() == ORIGINAL
assert_no_temp_files(target.parent)
monkeypatch.undo()
assert patcher.patch_file(target, PATTERNS, None)
assert backup_of(target).read_bytes() == ORIGINAL
assert target.read_bytes() == PATCHED
def test_interrupted_patched_write_leaves_original_whole(target: Path, monkeypatch: pytest.MonkeyPatch) -> None:
interrupt_write(monkeypatch, target)
with pytest.raises(Interrupted):
patcher.patch_file(target, PATTERNS, None)
assert backup_of(target).read_bytes() == ORIGINAL
assert target.read_bytes() == ORIGINAL
assert_no_temp_files(target.parent)
monkeypatch.undo()
assert patcher.patch_file(target, PATTERNS, None)
assert target.read_bytes() == PATCHED
def test_interrupted_undo_keeps_backup(target: Path, monkeypatch: pytest.MonkeyPatch) -> None:
assert patcher.patch_file(target, PATTERNS, None)
interrupt_write(monkeypatch, target)
with pytest.raises(Interrupted):
patcher.undo_dir(target.parent)
assert backup_of(target).read_bytes() == ORIGINAL
assert target.read_bytes() == PATCHED
assert_no_temp_files(target.parent)
monkeypatch.undo()
patcher.undo_dir(target.parent)
assert not backup_of(target).exists()
assert target.read_bytes() == ORIGINAL
def test_failed_interpreter_patch_leaves_no_partial_copy(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
binary = tmp_path / "claude"
binary.write_bytes(b"ELF whole")
def patchelf(*args: str | Path) -> str:
if args[0] == "--print-interpreter":
return "/lib64/ld-linux-x86-64.so.2"
Path(args[args.index("--output") + 1]).write_bytes(b"ELF ha")
raise subprocess.CalledProcessError(1, "patchelf")
monkeypatch.setattr(patcher, "patchelf", patchelf)
with pytest.raises(subprocess.CalledProcessError):
patcher.patch_interpreter(binary, "/nix/store/loader")
assert binary.read_bytes() == b"ELF whole"
assert_no_temp_files(tmp_path)
@pytest.mark.skipif(not Path("/etc/NIXOS").exists(), reason="not on NixOS")
def test_nixos_without_patchelf_exits_with_a_message(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(patcher.shutil, "which", lambda name: None)
with pytest.raises(SystemExit, match="patchelf is not on the PATH"):
patcher.nixos_interpreter()
def test_write_atomically_keeps_permission_bits(target: Path) -> None:
target.chmod(0o600)
patcher.write_atomically(target, PATCHED)
assert target.read_bytes() == PATCHED
assert target.stat().st_mode & 0o777 == 0o600
def test_patching_keeps_line_endings(tmp_path: Path) -> None:
path = tmp_path / "index.js"
path.write_bytes(b"let size=13;\r\nlet x;\r")
assert patcher.patch_file(path, PATTERNS, None)
assert path.read_bytes() == b"let size=12;\r\nlet x;\r"
def test_group_is_applied_all_or_none() -> None:
declare = patcher.Pattern(re.compile(r"let x;"), "let x,y;")
use = patcher.Pattern(re.compile(r"x\+1"), "y+1")
other = patcher.Pattern(re.compile(r"f\("), "g(")
assert patcher.apply_patterns("t.js", "let x;f(x);", [[declare, use], other]) == ("let x;g(x);", False)
assert patcher.apply_patterns("t.js", "let x;f(x+1);", [[declare, use], other]) == ("let x,y;g(y+1);", True)
assert patcher.apply_patterns("t.js", "let x;f(x+1,x+1);", [[declare, use], other]) == ("let x;g(x+1,x+1);", False)
def test_pattern_is_applied_only_with_the_expected_number_of_matches() -> None:
once = patcher.Pattern(re.compile(r"a"), "b")
sweep = patcher.Pattern(re.compile(r"a"), "b", sweep=True)
assert patcher.apply_patterns("t.js", "c;", [once]) == ("c;", False)
assert patcher.apply_patterns("t.js", "a;", [once]) == ("b;", True)
assert patcher.apply_patterns("t.js", "a;a;", [once]) == ("a;a;", False)
assert patcher.apply_patterns("t.js", "c;", [sweep]) == ("c;", False)
assert patcher.apply_patterns("t.js", "a;", [sweep]) == ("b;", True)
assert patcher.apply_patterns("t.js", "a;a;", [sweep]) == ("b;b;", True)
def test_pattern_with_too_many_matches_is_shown_and_kept_from_the_rest_of_its_group(capsys: pytest.CaptureFixture[str]) -> None:
twice = patcher.Pattern(re.compile(r"a"), "bb")
after = patcher.Pattern(re.compile(r"b"), "c")
assert patcher.apply_patterns("t.js", "a;a;b;", [[twice, after]]) == ("a;a;b;", False)
output = capsys.readouterr().out
assert "at character 0: 'a;a;b;'" in output
assert "at character 2: 'a;b;'" in output
# `after` saw the text without `twice`'s replacements, in which its regex matches once.
assert "t.js: 1x /b/" in output
def syntax_error_on_line(error: str | None, line: int) -> bool:
"""Return whether `error`, from js_syntax_error, is a syntax error on
line `line`, whatever words node's version puts it in."""
return error is not None and error.startswith("SyntaxError: ") and error.endswith(f" (line {line})")
@needs_node
def test_js_syntax_error_depends_on_how_the_file_is_loaded() -> None:
assert patcher.js_syntax_error("export let x=1;", "module") is None
assert syntax_error_on_line(patcher.js_syntax_error("export let x=1;", "commonjs"), 1)
# Only a module is always in strict mode.
assert patcher.js_syntax_error("with(Math)x=1;", "commonjs") is None
assert syntax_error_on_line(patcher.js_syntax_error("with(Math)x=1;", "module"), 1)
@needs_node
def test_js_syntax_error_is_reported_for_a_line_longer_than_a_pipe_holds() -> None:
text = "a=1;\n" * 3 + "b=2;" * 100_000 + ")"
assert syntax_error_on_line(patcher.js_syntax_error(text, "module"), 4)
def test_every_patched_js_file_has_an_input_type() -> None:
assert {rel for rel in patcher.patterns(True) if rel.endswith("js")} == set(patcher.JS_INPUT_TYPES)
@needs_node
def test_patch_that_breaks_syntax_leaves_file_as_it_was(target: Path, capsys: pytest.CaptureFixture[str]) -> None:
assert patcher.patch_file(target, PATTERNS, "module")
assert not patcher.patch_file(target, [patcher.Pattern(re.compile(r"size=13"), "size=)")], "module")
assert target.read_bytes() == PATCHED
assert backup_of(target).read_bytes() == ORIGINAL
assert_no_temp_files(target.parent)
assert "the patched file would not parse" in capsys.readouterr().out
@needs_node
def test_original_that_node_does_not_parse_is_not_blamed_on_the_patch(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
path = tmp_path / "index.js"
path.write_bytes(b"export let size=13;\n")
assert not patcher.patch_file(path, PATTERNS, "commonjs")
assert path.read_bytes() == b"export let size=13;\n"
assert "node does not parse even the original as commonjs JS" in capsys.readouterr().out