Skip to content
Merged
97 changes: 97 additions & 0 deletions tests/host_capability.py
Original file line number Diff line number Diff line change
@@ -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
26 changes: 22 additions & 4 deletions tests/test_build_dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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."""
Expand All @@ -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
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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)
Expand All @@ -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.

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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"
Expand All @@ -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)
Expand Down Expand Up @@ -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()
Expand Down
11 changes: 4 additions & 7 deletions tests/test_canonical_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down Expand Up @@ -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))
Expand Down
4 changes: 4 additions & 0 deletions tests/test_carry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
10 changes: 7 additions & 3 deletions tests/test_configure_archived.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"


Expand All @@ -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()
Comment thread
ptr727 marked this conversation as resolved.
Resolved


def run_bash(script: str, *tools: str) -> subprocess.CompletedProcess[str]:
Expand Down Expand Up @@ -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"
)
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 3 additions & 1 deletion tests/test_configure_environments.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"


Expand All @@ -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\(\) \{.*?\}$)"
Expand Down
4 changes: 3 additions & 1 deletion tests/test_configure_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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]:
Expand Down
4 changes: 3 additions & 1 deletion tests/test_configure_ruleset_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -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]:
Expand Down
8 changes: 5 additions & 3 deletions tests/test_configure_settings_live.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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()
Comment thread
ptr727 marked this conversation as resolved.
Resolved
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")
Expand Down
Loading
Loading