返回 last30days-skill
test_runtime_preflight_contract.py
根目录 / tests / test_runtime_preflight_contract.py
1 """Contract tests for the SKILL.md runtime preflight snippet."""
2
3 import re
4 import shlex
5 import shutil
6 import subprocess
7 import sys
8 import tempfile
9 import unittest
10 from pathlib import Path
11
12 from tests.skill_contract import contract_documents, reference_text, root_text
13
14 ROOT = Path(__file__).resolve().parents[1]
15 SKILL_MD = ROOT / "skills" / "last30days" / "SKILL.md"
16
17
18 class RuntimePreflightContractTests(unittest.TestCase):
19 def setUp(self) -> None:
20 self.skill_md = reference_text("runtime")
21
22 def test_windows_localappdata_python_install_dir_is_scanned_first(self) -> None:
23 scan_command = 'find "$windows_python_root" -maxdepth 2 -type f -iname python.exe'
24
25 self.assertIn('windows_path_to_unix "$LOCALAPPDATA")/Programs/Python', self.skill_md)
26 self.assertIn('windows_path_to_unix "$ProgramFiles"', self.skill_md)
27 self.assertIn("printenv 'ProgramFiles(x86)'", self.skill_md)
28 self.assertIn("cygpath -u", self.skill_md)
29 self.assertIn(scan_command, self.skill_md)
30 self.assertNotIn("/c/Users/", self.skill_md)
31 self.assertNotIn("Python314/python.exe", self.skill_md)
32 self.assertLess(self.skill_md.index(scan_command), self.skill_md.index("python3.14"))
33
34 def test_candidate_selection_accepts_any_python_3_12_or_newer(self) -> None:
35 self.assertIn("try_last30days_python()", self.skill_md)
36 self.assertIn("sys.version_info >= (3, 12)", self.skill_md)
37
38 def test_preflight_allows_explicit_interpreter_override(self) -> None:
39 self.assertIn('if [ -z "${LAST30DAYS_PYTHON:-}" ]; then', self.skill_md)
40 self.assertIn('ERROR: LAST30DAYS_PYTHON must point to Python 3.12+.', self.skill_md)
41
42 def test_inline_python_helpers_use_isolated_mode(self) -> None:
43 command = re.compile(
44 r'^[ \t]*(?:"?\$(?:candidate|LAST30DAYS_PYTHON|\{(?:candidate|LAST30DAYS_PYTHON)\})"?'
45 r'|python(?:3(?:\.\d+)?)?)[ \t]+'
46 r'(?P<flags>(?:-[A-Za-z]+[ \t]+)*)(?:-[cm]|-)(?=[ \t]|$)',
47 re.M,
48 )
49 found_in = set()
50 unisolated = []
51 for name, document in contract_documents().items():
52 for block in re.findall(r"```bash\n(.*?)\n```", document, re.S):
53 for match in command.finditer(block):
54 found_in.add(name)
55 if "-I" not in match["flags"].split():
56 unisolated.append((name, match[0].strip()))
57 self.assertTrue({"runtime", "comparison", "save-html-brief"} <= found_in)
58 self.assertEqual(unisolated, [])
59
60 def test_code_has_no_bare_positional_parameters(self) -> None:
61 # Claude Code replaces $<digit> in a skill body with words from the
62 # invocation arguments before the model reads it (anthropics/claude-code#94709),
63 # so shell/awk code in SKILL.md spells positional parameters as ${1} / $(2).
64 text = "\n".join(contract_documents().values())
65 fenced = re.findall(r"```.*?```", text, re.S)
66 inline = re.findall(r"`[^`\n]+`", re.sub(r"```.*?```", "", text, flags=re.S))
67 hits = [m.group(0) for block in fenced + inline for m in re.finditer(r"\$\d+(?![A-Za-z0-9_])", block)]
68 self.assertEqual(hits, [])
69
70
71 @unittest.skipUnless(shutil.which("bash") and shutil.which("awk"), "requires bash and awk")
72 class RuntimePreflightExecutionTests(unittest.TestCase):
73 def setUp(self) -> None:
74 self.skill_md = reference_text("runtime")
75 self.temp = tempfile.TemporaryDirectory()
76 self.addCleanup(self.temp.cleanup)
77 self.root = Path(self.temp.name)
78 self.bin = self.root / "bin"
79 self.bin.mkdir()
80 for name in ("printenv", "find", "sort", "awk"):
81 (self.bin / name).symlink_to(shutil.which(name))
82 self.skill_dir = self.root / "installed skill"
83 self.skill_dir.symlink_to(SKILL_MD.parent, target_is_directory=True)
84 self.save_dir = self.root / "saved research"
85 self.env = {
86 "PATH": str(self.bin),
87 "HOME": str(self.root),
88 "SKILL_DIR": str(self.skill_dir),
89 "LAST30DAYS_MEMORY_DIR": str(self.save_dir),
90 }
91
92 def _substitute_arguments(self, source: str) -> str:
93 arguments = shlex.split('runtime "Python releases" today')
94 return re.sub(
95 r"\$(\d+)(?!\w)",
96 lambda match: arguments[int(match[1])]
97 if int(match[1]) < len(arguments)
98 else match[0],
99 source,
100 )
101
102 def _python_candidate(self, name: str, version: tuple[int, int]) -> Path:
103 candidate = self.bin / name
104 version_probe = f"import sys; sys.version_info = {version!r}; exec(sys.argv[1])"
105 candidate.write_text(
106 "#!/bin/sh\n"
107 'if [ "$1" = "-I" ] && [ "$2" = "-c" ]; then\n'
108 f" exec {shlex.quote(sys.executable)} -I -c {shlex.quote(version_probe)} \"$3\"\n"
109 "fi\n"
110 f'exec {shlex.quote(sys.executable)} "$@"\n',
111 encoding="utf-8",
112 )
113 candidate.chmod(0o755)
114 return candidate
115
116 def _run(self, source: str, *, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
117 return subprocess.run(
118 [shutil.which("bash"), "--noprofile", "--norc", "-c", self._substitute_arguments(source)],
119 env=self.env,
120 cwd=cwd or self.root,
121 capture_output=True,
122 text=True,
123 timeout=15,
124 )
125
126 def _run_preflight(self) -> subprocess.CompletedProcess[str]:
127 snippet = re.search(r"```bash\n(try_last30days_python\(\).*?)\n```", self.skill_md, re.S)
128 self.assertIsNotNone(snippet)
129 resolution = re.search(r"## Save-directory resolution.*?```bash\n(.*?)\n```", self.skill_md, re.S)
130 self.assertIsNotNone(resolution)
131 self.assertLess(snippet.start(), resolution.start())
132 return self._run(snippet[1] + "\n" + resolution[1] + '\nprintf "Selected: <%s>\\n" "$LAST30DAYS_PYTHON"')
133
134 def test_missing_python_stops_before_engine(self) -> None:
135 result = self._run_preflight()
136 self.assertEqual(result.returncode, 1)
137 self.assertIn("ERROR: last30days v4 requires Python 3.12+", result.stderr)
138 self.assertNotIn("Resolved save directory:", result.stderr)
139
140 def test_old_python_stops_before_engine(self) -> None:
141 self._python_candidate("python3", (3, 11))
142 result = self._run_preflight()
143 self.assertEqual(result.returncode, 1)
144 self.assertIn("ERROR: last30days v4 requires Python 3.12+", result.stderr)
145 self.assertNotIn("Resolved save directory:", result.stderr)
146
147 def test_selects_supported_python_after_rejecting_old_candidate(self) -> None:
148 self._python_candidate("python3.14", (3, 11))
149 self._python_candidate("python3.13", (3, 13))
150 self._python_candidate("python3.12", (3, 12))
151 result = self._run_preflight()
152 self.assertEqual(result.returncode, 0, result.stderr)
153 self.assertEqual(
154 result.stdout,
155 f"LAST30DAYS_PYTHON={self.bin / 'python3.13'}\nSelected: <{self.bin / 'python3.13'}>\n",
156 )
157 self.assertIn(f"Resolved save directory: <{self.save_dir}>", result.stderr)
158
159 def test_explicit_python_path_with_spaces_is_preserved(self) -> None:
160 candidate = self._python_candidate("supported python", (3, 12))
161 self.env["LAST30DAYS_PYTHON"] = str(candidate)
162 result = self._run_preflight()
163 self.assertEqual(result.returncode, 0, result.stderr)
164 self.assertEqual(
165 result.stdout,
166 f"LAST30DAYS_PYTHON={shlex.quote(str(candidate))}\nSelected: <{candidate}>\n",
167 )
168 self.assertIn(f"Resolved save directory: <{self.save_dir}>", result.stderr)
169
170 def test_selected_python_runs_welcome_in_a_separate_shell(self) -> None:
171 candidate = self._python_candidate("supported python", (3, 12))
172 self.env["LAST30DAYS_PYTHON"] = f"./bin/{candidate.name}"
173 preflight = self._run_preflight()
174 self.assertEqual(preflight.returncode, 0, preflight.stderr)
175 assignment = next(
176 (line for line in preflight.stdout.splitlines() if line.startswith("LAST30DAYS_PYTHON=")),
177 None,
178 )
179 self.assertIsNotNone(assignment, "preflight must print a reusable shell assignment")
180 # Preflight anchors relative paths with `cd -P`, so expect the physical directory (macOS /var -> /private/var).
181 physical = candidate.parent.resolve() / candidate.name
182 self.assertEqual(assignment, f"LAST30DAYS_PYTHON={shlex.quote(str(physical))}")
183
184 installed = self.root / "welcome skill"
185 (installed / "scripts").mkdir(parents=True)
186 (installed / "scripts" / "last30days.py").write_text('print("welcome")\n', encoding="utf-8")
187 self.env.pop("LAST30DAYS_PYTHON")
188 self.env["SKILL_DIR"] = str(installed)
189 welcome = re.search(
190 r"\*\*1\. Welcome\.\*\* Run `([^`]+--welcome)`",
191 reference_text("setup-wizard"),
192 )
193 self.assertIsNotNone(welcome)
194 later_cwd = self.root / "later shell"
195 later_cwd.mkdir()
196 result = self._run(assignment + "\n" + welcome[1], cwd=later_cwd)
197 self.assertEqual(result.returncode, 0, result.stderr)
198 self.assertEqual(result.stdout, "welcome\n")
199
200 def test_invalid_explicit_python_does_not_fall_back(self) -> None:
201 self._python_candidate("python3.12", (3, 12))
202 old_python = self._python_candidate("old python", (3, 11))
203 for candidate in (old_python, self.bin / "missing python"):
204 with self.subTest(candidate=candidate):
205 self.env["LAST30DAYS_PYTHON"] = str(candidate)
206 result = self._run_preflight()
207 self.assertEqual(result.returncode, 1)
208 self.assertIn("ERROR: LAST30DAYS_PYTHON must point to Python 3.12+.", result.stderr)
209 self.assertNotIn("Resolved save directory:", result.stderr)
210
211 def test_windows_install_directory_with_spaces_precedes_path(self) -> None:
212 local_appdata = self.root / "Local App Data"
213 candidate = local_appdata / "Programs" / "Python" / "Python314" / "python.exe"
214 candidate.parent.mkdir(parents=True)
215 self._python_candidate("windows python", (3, 14)).replace(candidate)
216 self._python_candidate("python3.12", (3, 12))
217 self.env["LOCALAPPDATA"] = str(local_appdata)
218 result = self._run_preflight()
219 self.assertEqual(result.returncode, 0, result.stderr)
220 self.assertEqual(
221 result.stdout,
222 f"LAST30DAYS_PYTHON={shlex.quote(str(candidate))}\nSelected: <{candidate}>\n",
223 )
224 self.assertIn(f"Resolved save directory: <{self.save_dir}>", result.stderr)
225
226 def test_badge_block_copies_the_engine_line_without_a_version_command(self) -> None:
227 # The engine prints the badge with the version already resolved, so
228 # the instructions carry no shell command to look the version up.
229 badge = root_text().split("**BADGE", 1)[1].split("\n\n", 1)[0]
230 self.assertIn("Copy the engine's first line", badge)
231 self.assertNotIn("jq -r '.version'", root_text())
232 self.assertNotIn("awk '/^version:/", root_text())
233
234
235 if __name__ == "__main__":
236 unittest.main()
237
237 lines PYTHON