From 8bdfa2570708e0661169114f2383d17fbef9088e Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Wed, 7 Oct 2026 20:16:12 -0700 Subject: [PATCH] Skip a Symlink Test Where Windows Withholds the Privilege, and Run bash From PATH (#2508) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary This is the first step of #2488. It covers the two shared causes behind most of the suite's Windows failures. The rest of #2488 stays open for follow-up pull requests. - **Symlink fixtures.** Windows refuses `os.symlink` with WinError 1314 unless Developer Mode is on or the process is elevated. The new `tests/host_capability.py` probes this once. The 16 tests that build a symlink fixture now skip there with that reason, and two older ad-hoc catches use the same helper. The two `test_build_dist` tests that mix symlink and plain cases keep running their plain cases on Windows. - **A bare `bash` resolving to WSL.** A bare `"bash"` passed to `subprocess` on Windows is resolved by CreateProcess, which searches System32 before PATH. That finds the WSL launcher, which re-parses the script through a second shell. This caused the `read -a` errors and most of the `test_prose_lint`, `test_release_guards` and `test_publish_plan` failures. The tests now run the first `bash.exe` on PATH that is neither the launcher nor a `.cmd`/`.bat` shim. Where there is none, as from a PowerShell PATH, they skip with a reason saying to run the suite from Git Bash. - The receipt case in `test_local_review` now quotes its script path, in POSIX form, inside its `bash -c` string, since bash consumed the Windows path's backslashes. Linux CI is unaffected. There, `can_symlink()` is true, and `bash_path()` returns the same binary `shutil.which("bash")` did. ## Measured on a Windows 11 host, from Git Bash | | Before | After | | --- | --- | --- | | Failures | 47 | 15 | | Errors | 26 | 10 | | Skipped | 82 | 96 | From PowerShell, the bash-driven modules (`test_configure_*`, `test_prose_lint`, `test_release_guards`, `test_publish_plan`) now report `OK` with skips, where they failed before. ## Still open under #2488 - **`test_local_review`, 15.** These include two `ReceiptCase` tests that exit 120 on a closed pipe. That is a `local_review.py` Windows defect the WSL launcher had been masking by running the case under Linux. - **`test_spec_validate`, `test_host_gate`, `test_docker_lint`, 7.** These come from path-separator and output assumptions. - **`test_release_guards`, 1 test.** It fails under winget's jq 1.8.2, which rejects `\S`. Refs #2488 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- tests/host_capability.py | 97 +++++++++++++++++++++++ tests/test_build_dist.py | 26 +++++- tests/test_canonical_review.py | 11 +-- tests/test_carry.py | 4 + tests/test_configure_archived.py | 10 ++- tests/test_configure_environments.py | 4 +- tests/test_configure_project.py | 4 +- tests/test_configure_ruleset_id.py | 4 +- tests/test_configure_settings_live.py | 8 +- tests/test_configure_usage.py | 10 ++- tests/test_docker_lint.py | 4 + tests/test_host_capability.py | 109 ++++++++++++++++++++++++++ tests/test_local_review.py | 12 +-- tests/test_prose_lint.py | 8 +- tests/test_publish_plan.py | 4 +- tests/test_release_guards.py | 34 ++++---- tests/test_skills_install.py | 4 + 17 files changed, 303 insertions(+), 50 deletions(-) create mode 100644 tests/host_capability.py create mode 100755 tests/test_host_capability.py diff --git a/tests/host_capability.py b/tests/host_capability.py new file mode 100644 index 000000000..72ec60a8b --- /dev/null +++ b/tests/host_capability.py @@ -0,0 +1,97 @@ +"""Host capabilities a test needs and a Windows host may lack. + +A test that needs one of these skips with the reason when the host lacks it, rather than +erroring on a precondition that has nothing to do with the code under test. +""" + +from __future__ import annotations + +import functools +import ntpath +import os +import shutil +import tempfile +import unittest +from pathlib import Path + + +@functools.cache +def can_symlink() -> bool: + """Whether this host lets an unprivileged process create a symlink. + + Windows refuses one with WinError 1314 unless Developer Mode is on or the process is elevated. + """ + with tempfile.TemporaryDirectory() as tmp: + try: + (Path(tmp) / "link").symlink_to(Path(tmp) / "target") + except (OSError, NotImplementedError): + return False + return True + + +NO_SYMLINK = "this host cannot create a symlink without Developer Mode or elevation" +requires_symlink = unittest.skipUnless(can_symlink(), NO_SYMLINK) + + +_WINDOWS = os.name == "nt" + + +def _windows_path(path: str) -> str: + return ntpath.normcase(ntpath.normpath(path)) + + +def runs_a_script(found: str) -> bool: + """Whether found, an absolute path, is a bash that runs a script on this host. + + On Windows that rules out a Windows-supplied bash.exe, under the Windows directory or among + the WindowsApps aliases, which starts WSL rather than running bash here. Paths are compared by + ntpath rather than resolved, so the check reads the same on any host a test runs it on. + """ + if not _WINDOWS: + return True + path = _windows_path(found) + windows = _windows_path(os.environ.get("SystemRoot", r"C:\Windows")) + if path.startswith(windows + "\\"): + return False + profile = os.environ.get("LOCALAPPDATA") + return not profile or ntpath.dirname(path) != _windows_path( + ntpath.join(profile, "Microsoft", "WindowsApps") + ) + + +def _executable(path: str) -> bool: + return os.path.isfile(path) and os.access(path, os.X_OK) + + +def bash_path() -> str | None: + """The first bash on PATH that a workflow step's script can run under, or None. + + A bare "bash" passed to subprocess on Windows is resolved by CreateProcess, which searches + System32 before PATH and so finds the WSL launcher. That launcher hands the script to a second + shell that re-parses it, which mangles any quoting or expansion the script relies on, so the + PATH entry is named instead, passing over the launcher wherever PATH lists it. There each + absolute directory is probed for bash.exe itself rather than through shutil.which, which on + Windows would also look in the current directory first and admit a bash.cmd shim that cmd.exe + re-parses. Elsewhere shutil.which answers, as it did for a bare "bash". PATH is read on every + call rather than cached, since a test may change it for the duration of its run. + """ + if not _WINDOWS: + return shutil.which("bash") + for entry in os.environ.get("PATH", "").split(ntpath.pathsep): + directory = entry.strip('"') + if not ntpath.isabs(directory): + continue + candidate = ntpath.join(directory, "bash.exe") + if _executable(candidate) and runs_a_script(candidate): + return candidate + return None + + +def bash_or_skip() -> str: + """bash_path(), skipping the calling test where this host has none.""" + found = bash_path() + if found is None: + raise unittest.SkipTest( + "no bash on PATH that runs a script on this host, so run the suite from Git Bash" + ) + return found diff --git a/tests/test_build_dist.py b/tests/test_build_dist.py index 26a614d43..3502f87d2 100755 --- a/tests/test_build_dist.py +++ b/tests/test_build_dist.py @@ -17,6 +17,8 @@ import unittest from pathlib import Path +from host_capability import NO_SYMLINK, can_symlink, requires_symlink + sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import build_dist @@ -86,6 +88,7 @@ def make_skill(self, name: str, body: str = "content") -> None: class RegenerateCase(TreeCase): """Regeneration and staleness detection over the generated trees.""" + @requires_symlink def test_a_symlink_in_a_skill_directory_is_rejected_by_regenerate(self) -> None: """shutil.copytree() follows a symlink by default, which would silently pull content from outside .agents/skills/ into the generated, published plugin.""" @@ -94,12 +97,14 @@ def test_a_symlink_in_a_skill_directory_is_rejected_by_regenerate(self) -> None: with self.assertRaises(ValueError): build_dist.regenerate() + @requires_symlink def test_a_symlink_in_a_skill_directory_is_rejected_by_skill_digest(self) -> None: self.make_skill("foo") (self.skills_src / "foo" / "escape").symlink_to(self.tmp) with self.assertRaises(ValueError): build_dist.skill_digest("foo") + @requires_symlink def test_a_skill_directory_that_is_itself_a_symlink_is_rejected(self) -> None: """rglob("*") only yields paths inside the directory it walks, so a skill directory that is itself a symlink to another tree would otherwise walk straight into that tree without @@ -299,6 +304,7 @@ def test_a_missing_stamp_reports_stale(self) -> None: (build_dist.DIGEST_DIR / "foo").unlink() self.assertTrue(build_dist.is_stale()) + @requires_symlink def test_a_stamp_replaced_by_a_symlink_reports_stale(self) -> None: """is_file() follows a symlink, so a stamp pointing outside the tree would otherwise read as current whenever its target happens to hold the right digest.""" @@ -351,6 +357,7 @@ def test_removing_a_skill_after_regenerate_no_longer_carries_it(self) -> None: self.assertEqual(names, ["foo"]) self.assertFalse((self.dist_plugin / "skills" / "bar").exists()) + @requires_symlink def test_main_reports_a_symlink_cleanly_instead_of_a_raw_traceback(self) -> None: self.make_skill("foo") (self.skills_src / "foo" / "escape").symlink_to(self.tmp) @@ -360,6 +367,7 @@ def test_main_reports_a_symlink_cleanly_instead_of_a_raw_traceback(self) -> None exit_code = build_dist.main() self.assertEqual(exit_code, 1) + @requires_symlink def test_check_reports_a_symlink_as_2_not_1(self) -> None: """1 is --check's own documented "stale" result, so a caller reading the exit code (host-setup/menu.sh among them) needs a different code to tell a real failure apart from that finding. @@ -631,17 +639,21 @@ def test_a_near_miss_marker_is_refused_rather_than_read_as_content(self) -> None def test_a_source_outside_the_root_or_under_a_generated_tree_is_refused(self) -> None: outside = Path(self.enterContext(tempfile.TemporaryDirectory())) / "outside.md" outside.write_text("## Alpha\n\nx\n", encoding="utf-8") - (self.tmp / "link.md").symlink_to(outside) self.github_skills.mkdir(parents=True, exist_ok=True) (self.github_skills / "gen.md").write_text("## Alpha\n\nx\n", encoding="utf-8") + if can_symlink(): + (self.tmp / "link.md").symlink_to(outside) for rel in ( "../outside.md", str(outside), - "link.md", ".github/skills/gen.md", "missing.md", + # Last, since a skip inside a subTest stops the loop under failfast. + "link.md", ): with self.subTest(rel): + if rel == "link.md" and not can_symlink(): + self.skipTest(NO_SYMLINK) self.make_skill("foo", self.region(f"{rel} > Alpha")) with self.assertRaises(ValueError): build_dist.regenerate() @@ -694,6 +706,7 @@ def test_an_indented_marker_is_content(self) -> None: self.assertEqual(self.skill_text(), body) self.assertFalse(build_dist.is_stale()) + @requires_symlink def test_a_symlinked_skill_directory_is_refused_before_any_fill(self) -> None: """The fill writes through whatever the walk found, so the symlink check has to run before it.""" target = self.tmp / "elsewhere" @@ -706,6 +719,7 @@ def test_a_symlinked_skill_directory_is_refused_before_any_fill(self) -> None: build_dist.regenerate() self.assertEqual((target / "SKILL.md").read_text(encoding="utf-8"), original) + @requires_symlink def test_a_directory_symlink_on_the_way_is_refused(self) -> None: """A symlink inside the root can still alias a generated tree or the including file itself.""" self.github_skills.mkdir(parents=True, exist_ok=True) @@ -814,17 +828,21 @@ def test_a_declared_destination_that_is_not_in_the_tree_is_refused(self) -> None self.make_skill("foo", self.region("RULES.md > Alpha")) outside = Path(self.enterContext(tempfile.TemporaryDirectory())) / "outside.md" outside.write_text("## A\n\na\n", encoding="utf-8") - (self.tmp / "link.md").symlink_to(outside) self.dist_plugin.mkdir(parents=True, exist_ok=True) (self.dist_plugin / "GEN.md").write_text("## A\n\na\n", encoding="utf-8") + if can_symlink(): + (self.tmp / "link.md").symlink_to(outside) cases = { "missing": "docs/absent.md", - "through a symlink": "link.md", "under a generated tree": ".claude-plugin/fleet-skills/GEN.md", "outside the root": "../outside.md", + # Last, since a skip inside a subTest stops the loop under failfast. + "through a symlink": "link.md", } for label, rel in cases.items(): with self.subTest(label): + if rel == "link.md" and not can_symlink(): + self.skipTest(NO_SYMLINK) self.declare_destinations(rel) with self.assertRaises(ValueError) as caught: build_dist.regenerate() diff --git a/tests/test_canonical_review.py b/tests/test_canonical_review.py index dfb3f9990..9c7231f63 100755 --- a/tests/test_canonical_review.py +++ b/tests/test_canonical_review.py @@ -24,6 +24,8 @@ from pathlib import Path from typing import Any +from host_capability import requires_symlink + SCRIPTS = Path(__file__).resolve().parent.parent / "scripts" sys.path.insert(0, str(SCRIPTS)) sys.path.insert(0, str(SCRIPTS.parent / "spec")) @@ -756,19 +758,14 @@ def test_an_unexpected_failure_reports_the_boundary_rather_than_a_verdict(self) class CarriedPathCase(RepoCase): + @requires_symlink def test_a_symlinked_carried_path_is_refused(self) -> None: """carry.py refuses a symlink anywhere in a carried tree, and reading one here would follow it out of the repository the manifest describes.""" target = self.outside / "elsewhere.md" target.write_bytes(b"## Alpha\n\nnot ours\n") (self.tmp / "DOC.md").unlink() - try: - (self.tmp / "DOC.md").symlink_to(target) - except OSError as unprivileged: - # Windows refuses a symlink without the privilege or Developer Mode. - # That is an execution boundary rather than this guard failing. - (self.tmp / "DOC.md").write_bytes(b"## Alpha\n\nown\n") - raise unittest.SkipTest(f"this host cannot create a symlink: {unprivileged}") from None + (self.tmp / "DOC.md").symlink_to(target) with self.assertRaises(cr.CannotRun) as caught: cr.units(self.tmp) self.assertIn("DOC.md", str(caught.exception)) diff --git a/tests/test_carry.py b/tests/test_carry.py index e1bd9d8ef..d0b273efa 100755 --- a/tests/test_carry.py +++ b/tests/test_carry.py @@ -12,6 +12,8 @@ from collections.abc import Callable from unittest import mock +from host_capability import requires_symlink + sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "scripts")) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "spec")) import audit @@ -79,6 +81,7 @@ def test_inventory_digest_includes_empty_directories(self) -> None: self.assertNotEqual(left_inventory.digest, right_inventory.digest) + @requires_symlink def test_inventory_rejects_source_and_target_symlinks(self) -> None: with tempfile.TemporaryDirectory() as temp: root = pathlib.Path(temp) @@ -303,6 +306,7 @@ def test_rejects_backslash_anywhere(self) -> None: ): carry.relative_root(pathlib.Path(temp), value) + @requires_symlink def test_rejects_symlinked_declared_root(self) -> None: with tempfile.TemporaryDirectory() as temp: root = pathlib.Path(temp) diff --git a/tests/test_configure_archived.py b/tests/test_configure_archived.py index b6409d2d6..b0de6732f 100755 --- a/tests/test_configure_archived.py +++ b/tests/test_configure_archived.py @@ -21,6 +21,8 @@ import unittest from pathlib import Path +from host_capability import bash_or_skip + CONFIGURE = Path(__file__).resolve().parents[1] / "repo-config" / "configure.sh" @@ -40,7 +42,7 @@ def require(*tools: str) -> str: for tool in tools: if shutil.which(tool) is None: raise unittest.SkipTest(f"no {tool} on PATH, so the script's own lines cannot be run") - return str(shutil.which("bash")) + return bash_or_skip() def run_bash(script: str, *tools: str) -> subprocess.CompletedProcess[str]: @@ -132,7 +134,7 @@ def test_a_trailing_carriage_return_from_jq_is_stripped(self) -> None: stub.chmod(0o755) registry = self.registry(tmp, [{"name": "Fixture", "status": "archived"}]) script = ( - f"PATH={shlex.quote(str(bin_dir))}:$PATH\n" + f'PATH="$(cd {shlex.quote(str(bin_dir))} && pwd):$PATH"\n' f"registry={shlex.quote(str(registry))}\nname=Fixture\ncmd=check\nrepo=owner/Fixture\n" f"{ARCHIVED_EXEMPTION}echo REACHED_NEXT\n" ) @@ -165,7 +167,9 @@ def run_configure(self, status: str, cmd: str) -> subprocess.CompletedProcess[st encoding="utf-8", ) gh_stub.chmod(0o755) - env = dict(os.environ, PATH=f"{root / 'bin'}:{os.environ.get('PATH', os.defpath)}") + env = dict( + os.environ, PATH=f"{root / 'bin'}{os.pathsep}{os.environ.get('PATH', os.defpath)}" + ) return subprocess.run( [bash, str(root / "repo-config" / "configure.sh"), cmd, "owner/Fixture"], capture_output=True, diff --git a/tests/test_configure_environments.py b/tests/test_configure_environments.py index 90c8e0bc3..48d3b73d3 100755 --- a/tests/test_configure_environments.py +++ b/tests/test_configure_environments.py @@ -16,6 +16,8 @@ import unittest from pathlib import Path +from host_capability import bash_or_skip + CONFIGURE = Path(__file__).resolve().parents[1] / "repo-config" / "configure.sh" @@ -35,7 +37,7 @@ def require(*tools: str) -> str: for tool in tools: if shutil.which(tool) is None: raise unittest.SkipTest(f"no {tool} on PATH, so the script's own lines cannot be run") - return str(shutil.which("bash")) + return bash_or_skip() JQR = r"^(jqr\(\) \{.*?\}$)" diff --git a/tests/test_configure_project.py b/tests/test_configure_project.py index 17a20e702..487d8d089 100755 --- a/tests/test_configure_project.py +++ b/tests/test_configure_project.py @@ -21,6 +21,8 @@ import unittest from pathlib import Path +from host_capability import bash_or_skip + ROOT = Path(__file__).resolve().parents[1] CONFIGURE = ROOT / "repo-config" / "configure.sh" PAYLOAD = ROOT / "repo-config" / "project.json" @@ -45,7 +47,7 @@ def require(*tools: str) -> str: for tool in tools: if shutil.which(tool) is None: raise unittest.SkipTest(f"no {tool} on PATH, so the script's own lines cannot be run") - return str(shutil.which("bash")) + return bash_or_skip() def run_bash(script: str, *tools: str) -> subprocess.CompletedProcess[str]: diff --git a/tests/test_configure_ruleset_id.py b/tests/test_configure_ruleset_id.py index 6aed66405..71595546d 100755 --- a/tests/test_configure_ruleset_id.py +++ b/tests/test_configure_ruleset_id.py @@ -19,6 +19,8 @@ import unittest from pathlib import Path +from host_capability import bash_or_skip + ROOT = Path(__file__).resolve().parents[1] CONFIGURE = ROOT / "repo-config" / "configure.sh" @@ -39,7 +41,7 @@ def require(*tools: str) -> str: for tool in tools: if shutil.which(tool) is None: raise unittest.SkipTest(f"no {tool} on PATH, so the script's own lines cannot be run") - return str(shutil.which("bash")) + return bash_or_skip() def run_bash(script: str, *tools: str) -> subprocess.CompletedProcess[str]: diff --git a/tests/test_configure_settings_live.py b/tests/test_configure_settings_live.py index b52123ba9..bbbfa4e48 100755 --- a/tests/test_configure_settings_live.py +++ b/tests/test_configure_settings_live.py @@ -16,6 +16,8 @@ import unittest from pathlib import Path +from host_capability import bash_or_skip + ROOT = Path(__file__).resolve().parents[1] CONFIGURE = ROOT / "repo-config" / "configure.sh" @@ -45,9 +47,9 @@ class LiveSettingsCase(unittest.TestCase): """A 2xx settings response that is not a JSON object reports one FAIL and does not abort.""" def run_check(self, live: str) -> subprocess.CompletedProcess[str]: - bash = shutil.which("bash") - if bash is None or shutil.which("jq") is None: - raise unittest.SkipTest("no bash or jq on PATH") + bash = bash_or_skip() + if shutil.which("jq") is None: + raise unittest.SkipTest("no jq on PATH") with tempfile.TemporaryDirectory() as tmp: settings = Path(tmp) / "settings.json" settings.write_text(json.dumps({"delete_branch_on_merge": True}), encoding="utf-8") diff --git a/tests/test_configure_usage.py b/tests/test_configure_usage.py index 0defdf169..fa0eed4fd 100755 --- a/tests/test_configure_usage.py +++ b/tests/test_configure_usage.py @@ -15,6 +15,8 @@ import unittest from pathlib import Path +from host_capability import bash_or_skip + CONFIGURE = Path(__file__).resolve().parents[1] / "repo-config" / "configure.sh" @@ -22,9 +24,7 @@ class UsageCase(unittest.TestCase): """Help exits 0 and a usage error exits 1, each before any `gh` call.""" def run_configure(self, *args: str) -> tuple[subprocess.CompletedProcess[str], str]: - bash = shutil.which("bash") - if bash is None: - raise unittest.SkipTest("no bash on PATH, so the script cannot be run") + bash = bash_or_skip() with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) (root / "repo-config").mkdir() @@ -37,7 +37,9 @@ def run_configure(self, *args: str) -> tuple[subprocess.CompletedProcess[str], s encoding="utf-8", ) gh_stub.chmod(0o755) - env = dict(os.environ, PATH=f"{root / 'bin'}:{os.environ.get('PATH', os.defpath)}") + env = dict( + os.environ, PATH=f"{root / 'bin'}{os.pathsep}{os.environ.get('PATH', os.defpath)}" + ) result = subprocess.run( [bash, str(root / "repo-config" / "configure.sh"), *args], capture_output=True, diff --git a/tests/test_docker_lint.py b/tests/test_docker_lint.py index 67788ca00..ec3972afa 100755 --- a/tests/test_docker_lint.py +++ b/tests/test_docker_lint.py @@ -12,6 +12,8 @@ from pathlib import Path from unittest import mock +from host_capability import requires_symlink + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) import docker_lint @@ -165,6 +167,7 @@ def test_extensionless_shebang_script_merges_with_glob_matched_scripts(self) -> docker_lint.tracked_files(self.root, linter), ) + @requires_symlink def test_extensionless_symlink_is_never_followed(self) -> None: secret = self.outside / "secret" secret.write_text("#!/usr/bin/env bash\n", encoding="utf-8") @@ -173,6 +176,7 @@ def test_extensionless_symlink_is_never_followed(self) -> None: with mock.patch.object(Path, "open", side_effect=AssertionError("symlink target opened")): self.assertEqual([], docker_lint.tracked_files(self.root, linter)) + @requires_symlink def test_has_shell_shebang_reports_false_for_a_symlink_without_reading_it(self) -> None: secret = self.outside / "secret" secret.write_text("#!/usr/bin/env bash\n", encoding="utf-8") diff --git a/tests/test_host_capability.py b/tests/test_host_capability.py new file mode 100755 index 000000000..9949c10ad --- /dev/null +++ b/tests/test_host_capability.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Test the Windows bash selection in host_capability on any host, Linux CI included.""" + +from __future__ import annotations + +import ntpath +import os +import unittest +from collections.abc import Iterable +from unittest import mock + +import host_capability + +WINDOWS_ENV = {"SystemRoot": r"C:\Windows", "LOCALAPPDATA": r"D:\Profile\AppData\Local"} +SYSTEM = r"C:\WINDOWS\system32" +APPS = r"D:\Profile\AppData\Local\Microsoft\WindowsApps" +GIT = r"C:\Program Files\Git\usr\bin" +SHIMS = r"C:\tools\shims" + + +def bash_in(directory: str) -> str: + return ntpath.join(directory, "bash.exe") + + +class WindowsCase(unittest.TestCase): + """Runs each case as a Windows host would, whatever host runs the suite.""" + + def setUp(self) -> None: + self.enterContext(mock.patch.object(host_capability, "_WINDOWS", True)) + self.enterContext(mock.patch.dict(os.environ, WINDOWS_ENV)) + + +class RunsAScriptCase(WindowsCase): + def test_the_wsl_launchers_are_passed_over(self) -> None: + for launcher in (bash_in(SYSTEM), bash_in(APPS)): + with self.subTest(launcher): + self.assertFalse(host_capability.runs_a_script(launcher)) + + def test_git_bash_is_taken(self) -> None: + self.assertTrue(host_capability.runs_a_script(bash_in(GIT))) + + def test_a_sibling_sharing_the_windows_prefix_is_not_under_it(self) -> None: + self.assertTrue(host_capability.runs_a_script(r"C:\WindowsTools\bash.exe")) + + def test_the_windows_directory_is_still_passed_over_with_no_profile_set(self) -> None: + with mock.patch.dict(os.environ): + del os.environ["LOCALAPPDATA"] + self.assertFalse(host_capability.runs_a_script(bash_in(SYSTEM))) + self.assertTrue(host_capability.runs_a_script(bash_in(GIT))) + + def test_off_windows_every_bash_runs_a_script(self) -> None: + with mock.patch.object(host_capability, "_WINDOWS", False): + self.assertTrue(host_capability.runs_a_script("/usr/bin/bash")) + + +class BashPathCase(WindowsCase): + def walk(self, entries: Iterable[str], present: set[str]) -> tuple[str | None, list[str]]: + """bash_path() over a PATH of entries, where only the paths in present exist.""" + probed: list[str] = [] + + def executable(path: str) -> bool: + probed.append(path) + return path in present + + with ( + mock.patch.dict(os.environ, {"PATH": ntpath.pathsep.join(entries)}), + mock.patch.object(host_capability, "_executable", side_effect=executable), + ): + return host_capability.bash_path(), probed + + def test_the_first_bash_that_runs_a_script_is_taken(self) -> None: + present = {bash_in(SYSTEM), bash_in(APPS), bash_in(GIT)} + found, probed = self.walk([SYSTEM, "", APPS, GIT, r"C:\later"], present) + self.assertEqual(bash_in(GIT), found) + self.assertEqual([bash_in(SYSTEM), bash_in(APPS), bash_in(GIT)], probed) + + def test_a_shim_is_never_probed_for(self) -> None: + found, probed = self.walk([SHIMS], {ntpath.join(SHIMS, "bash.cmd")}) + self.assertIsNone(found) + self.assertEqual([bash_in(SHIMS)], probed) + + def test_a_relative_entry_is_skipped_rather_than_read_against_the_current_directory( + self, + ) -> None: + found, probed = self.walk([".", "bin", GIT], {bash_in("."), bash_in(GIT)}) + self.assertEqual(bash_in(GIT), found) + self.assertEqual([bash_in(GIT)], probed) + + def test_a_quoted_entry_is_read_unquoted(self) -> None: + self.assertEqual(bash_in(GIT), self.walk([f'"{GIT}"'], {bash_in(GIT)})[0]) + + def test_a_path_holding_only_launchers_has_no_bash(self) -> None: + self.assertIsNone(self.walk([SYSTEM, APPS], {bash_in(SYSTEM), bash_in(APPS)})[0]) + + def test_off_windows_shutil_which_answers_relative_entries_included(self) -> None: + with ( + mock.patch.object(host_capability, "_WINDOWS", False), + mock.patch.object(host_capability.shutil, "which", return_value="bin/bash") as which, + ): + self.assertEqual("bin/bash", host_capability.bash_path()) + which.assert_called_once_with("bash") + + def test_path_is_read_on_every_call(self) -> None: + self.assertIsNone(self.walk([SYSTEM], {bash_in(SYSTEM), bash_in(GIT)})[0]) + self.assertEqual(bash_in(GIT), self.walk([GIT], {bash_in(GIT)})[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_local_review.py b/tests/test_local_review.py index 56214f0b7..9920d8263 100755 --- a/tests/test_local_review.py +++ b/tests/test_local_review.py @@ -27,6 +27,8 @@ import unittest.mock from pathlib import Path +from host_capability import bash_or_skip, requires_symlink + SCRIPT = Path(__file__).resolve().parent.parent / "scripts" / "local_review.py" sys.path.insert(0, str(SCRIPT.parent)) import local_review @@ -370,14 +372,12 @@ def test_the_digest_mixes_the_merge_base(self) -> None: other = local_review.content_digest("0" * 40, marks) self.assertNotEqual(digest, other) + @requires_symlink def test_a_symlink_is_keyed_as_a_link_not_as_its_pointee(self) -> None: """git stores a link as its target path, so the key must not follow it out of the tree.""" outside = self.outside / "outside.txt" outside.write_text("secret\n", encoding="utf-8") - try: - (self.tmp / "link").symlink_to(outside) - except (OSError, NotImplementedError): - self.skipTest("this platform does not permit creating a symlink") + (self.tmp / "link").symlink_to(outside) mark = self.marks().get("link", "") if "120000:" not in mark: self.skipTest(f"this checkout does not store links as links: {mark}") @@ -988,9 +988,9 @@ def run_piped(self, args: list[str], shell: str) -> int: genuine EPIPE on a descriptor, and the exit code being tested includes the one the interpreter produces during its own shutdown flush, which no in-process case can reach. """ - script = f"python3 {SCRIPT} {' '.join(args)} {shell}" + script = f"python3 {shlex.quote(SCRIPT.as_posix())} {' '.join(args)} {shell}" proc = subprocess.run( - ["bash", "-c", f"{script}; exit ${{PIPESTATUS[0]}}"], + [bash_or_skip(), "-c", f"{script}; exit ${{PIPESTATUS[0]}}"], cwd=str(self.tmp), capture_output=True, text=True, diff --git a/tests/test_prose_lint.py b/tests/test_prose_lint.py index 86ba952e6..0ca7027fe 100755 --- a/tests/test_prose_lint.py +++ b/tests/test_prose_lint.py @@ -28,6 +28,8 @@ from typing import ClassVar from unittest import mock +from host_capability import bash_or_skip + try: import resource # POSIX only, absent on Windows entirely rather than merely restricted except ImportError: @@ -70,7 +72,7 @@ def run_prose_gate_action(root: Path, **extra: str) -> subprocess.CompletedProce | extra ) return subprocess.run( - ["bash", "-c", "\n".join(script_lines)], + [bash_or_skip(), "-c", "\n".join(script_lines)], cwd=root, env=env, text=True, @@ -118,7 +120,7 @@ def run_comments_label_step(live: str | None, payload: str) -> tuple[str, str, s "PAYLOAD_LABELED": payload, } result = subprocess.run( - ["bash", "-c", "\n".join(script_lines)], + [bash_or_skip(), "-c", "\n".join(script_lines)], env=env, text=True, encoding="utf-8", @@ -4072,7 +4074,7 @@ def run_block(self, extra: dict[str, str]) -> list[str]: env |= {"BASE": "HEAD", "PATHS": ".", "GITHUB_ACTION_PATH": str(stub_dir)} env |= extra r = subprocess.run( - ["bash", "-c", "\n".join(lines)], + [bash_or_skip(), "-c", "\n".join(lines)], cwd=str(root), capture_output=True, text=True, diff --git a/tests/test_publish_plan.py b/tests/test_publish_plan.py index 31378514e..abd60b8ce 100755 --- a/tests/test_publish_plan.py +++ b/tests/test_publish_plan.py @@ -9,6 +9,8 @@ import unittest from pathlib import Path +from host_capability import bash_or_skip + REPO = Path(__file__).resolve().parents[1] WORKFLOW = REPO / ".github" / "workflows" / "publish-plan-task.yml" @@ -47,7 +49,7 @@ def run_plan(self, ref: str) -> tuple[subprocess.CompletedProcess[str], str]: } ) result = subprocess.run( - ["bash", "-c", decision_script()], + [bash_or_skip(), "-c", decision_script()], check=False, capture_output=True, env=env, diff --git a/tests/test_release_guards.py b/tests/test_release_guards.py index 848ea6b9f..b9725589f 100755 --- a/tests/test_release_guards.py +++ b/tests/test_release_guards.py @@ -15,6 +15,8 @@ from subprocess import run from typing import NamedTuple +from host_capability import bash_or_skip + REPO = Path(__file__).resolve().parents[1] @@ -288,7 +290,7 @@ def compute(branch: str, semver2: str) -> int: env = {**os.environ, "BRANCH": branch, "SEMVER2": semver2} env["GITHUB_OUTPUT"] = str(output) verdict = run( - ["bash", "-c", script], + [bash_or_skip(), "-c", script], env=env, capture_output=True, text=True, @@ -321,7 +323,7 @@ def compute(branch: str, semver2: str) -> int: env = {**os.environ, "BRANCH": "main", "SEMVER2": injected} env["GITHUB_OUTPUT"] = str(output) verdict = run( - ["bash", "-c", script], + [bash_or_skip(), "-c", script], env=env, capture_output=True, text=True, @@ -340,7 +342,7 @@ def compute(branch: str, semver2: str) -> int: env = {**os.environ, "BRANCH": injected, "SEMVER2": "1.2.34"} env["GITHUB_OUTPUT"] = str(output) verdict = run( - ["bash", "-c", script], + [bash_or_skip(), "-c", script], env=env, capture_output=True, text=True, @@ -487,7 +489,7 @@ def git(cwd: Path, *args: str) -> str: head_sha = git(work, "rev-parse", "HEAD") activity.write_text(json.dumps(pushes(built_sha, head_sha)), encoding="utf-8") verdict = run( - ["bash", "-c", script], + [bash_or_skip(), "-c", script], cwd=built, env={ **env, @@ -573,7 +575,7 @@ def test_release_gate_refuses_a_branch_git_would_not_name(self) -> None: def gate(branch: str, semver2: str, smoke: str = "false") -> tuple[int, str]: env = {**os.environ, "BRANCH": branch, "SEMVER2": semver2, "SMOKE": smoke} verdict = run( - ["bash", "-c", script], + [bash_or_skip(), "-c", script], env=env, capture_output=True, text=True, @@ -1014,7 +1016,7 @@ def test_audit_runnable_blocks_parse_as_printed(self) -> None: # Naming the subTest must not be what fails when the document is what is wrong. with self.subTest(block=(source.splitlines() or [""])[0][:60]): parsed = run( - ["bash", "-n", "-c", source], + [bash_or_skip(), "-n", "-c", source], check=False, capture_output=True, text=True, @@ -1047,17 +1049,17 @@ def test_audit_probes_fail_before_local_path_checks(self) -> None: """ success = run( - ["bash", "-c", f"{fake_api}\n{probe}"], + [bash_or_skip(), "-c", f"{fake_api}\n{probe}"], check=False, capture_output=True, text=True, encoding="utf-8", ) - failure = run(["bash", "-c", f"gh() {{ return 17; }}\n{probe}"], check=False) + failure = run([bash_or_skip(), "-c", f"gh() {{ return 17; }}\n{probe}"], check=False) # One read failing is the fail-open the "every read fails" case above cannot see. one_read_fails = run( [ - "bash", + bash_or_skip(), "-c", f"{fake_api.replace('''repos/*/contents/.github\\?*) printf''', 'repos/*/contents/.github\\?*) return 17 ;; repos/*/never\\?*) printf')}\n{probe}", ], @@ -1074,7 +1076,7 @@ def test_audit_probes_fail_before_local_path_checks(self) -> None: """printf '%s\\n' '# - package-ecosystem: devcontainers' ' - package-ecosystem: \"github-actions2\"'""", ) missing = run( - ["bash", "-c", f"{missing_api}\n{probe}"], + [bash_or_skip(), "-c", f"{missing_api}\n{probe}"], check=False, capture_output=True, text=True, @@ -1165,7 +1167,7 @@ def run_python_tests_step( if not extra_env or "UV_PYTHON" not in extra_env: env.pop("UV_PYTHON", None) result = run( - ["bash", "-c", script], + [bash_or_skip(), "-c", script], cwd=work, env=env, capture_output=True, @@ -1674,7 +1676,7 @@ def test_validator_dotnet_leg_fails_when_no_report_was_written(self) -> None: "", encoding="utf-8" ) verdict = run( - ["bash", "-c", script], + [bash_or_skip(), "-c", script], cwd=work, env={ **os.environ, @@ -1754,7 +1756,7 @@ def test_validator_refuses_a_python_versions_value_fromjson_would_admit(self) -> for value, expected in cases.items(): with self.subTest(value=value): verdict = run( - ["bash", "-c", script], + [bash_or_skip(), "-c", script], env={**os.environ, "PYTHON_VERSIONS": value}, capture_output=True, text=True, @@ -1767,7 +1769,7 @@ def test_validator_refuses_a_python_versions_value_fromjson_would_admit(self) -> # The runner reads a workflow command off any line starting with one, so an unescaped newline starts a second. injected = '["3.13"]\n::error::injected' verdict = run( - ["bash", "-c", script], + [bash_or_skip(), "-c", script], env={**os.environ, "PYTHON_VERSIONS": injected}, capture_output=True, text=True, @@ -1781,7 +1783,7 @@ def test_validator_refuses_a_python_versions_value_fromjson_would_admit(self) -> # A carriage return is the third escape, and without this nothing here would notice its removal. verdict = run( - ["bash", "-c", script], + [bash_or_skip(), "-c", script], env={**os.environ, "PYTHON_VERSIONS": "x\ry"}, capture_output=True, text=True, @@ -1795,7 +1797,7 @@ def test_validator_refuses_a_python_versions_value_fromjson_would_admit(self) -> # Their order is what the %0A assertion above covers instead, not this one. # Substituting the percent last renders a newline %250A, which fails there and passes here. verdict = run( - ["bash", "-c", script], + [bash_or_skip(), "-c", script], env={**os.environ, "PYTHON_VERSIONS": "%"}, capture_output=True, text=True, diff --git a/tests/test_skills_install.py b/tests/test_skills_install.py index d7250f00b..03e8bbdbc 100755 --- a/tests/test_skills_install.py +++ b/tests/test_skills_install.py @@ -19,6 +19,8 @@ from pathlib import Path from unittest import mock +from host_capability import requires_symlink + sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import skills_install @@ -216,6 +218,7 @@ def test_a_retired_fleet_skill_is_removed_on_the_next_install(self) -> None: self.assertFalse((target / "bar").exists()) self.assertTrue((target / "foo").is_dir()) + @requires_symlink def test_a_symlinked_directory_in_the_cleanup_scan_is_skipped_not_crashed_on(self) -> None: """is_dir() alone follows a symlink, and shutil.rmtree() refuses a top-level symlink with an uncaught OSError. A stray symlink under the shared target, even one whose real @@ -265,6 +268,7 @@ def test_a_directory_without_skill_md_is_not_copied_as_a_skill(self) -> None: skills_install.materialize_global_skills(target) self.assertFalse((target / "not-a-skill").exists()) + @requires_symlink def test_a_symlink_in_a_skill_directory_is_rejected(self) -> None: """shutil.copytree() follows a symlink by default, which would silently pull content from outside .agents/skills/ into the shared, machine-wide skills directory."""