blob: 960d120972c7125ff5a4103ed268c3b5febbd0e2 [file]
#!/usr/bin/env fuchsia-vendored-python
# Copyright 2026 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit tests for tools/devshell/lib/shac_runner.py."""
import io
import json
import os
import pathlib
import shlex
import signal
import subprocess
import sys
import tempfile
import types
import unittest
from collections.abc import Collection, Mapping, Sequence
from typing import NoReturn
from unittest import mock
import scm
import shac_runner
def _fail_with_sarif(
cmd: Sequence[str], check_results: Sequence[tuple[str, str]]
) -> NoReturn:
for arg in cmd:
if arg.startswith("--json-output="):
pathlib.Path(arg.split("=", 1)[1]).write_text(
json.dumps(
{
"version": "2.1.0",
"runs": tuple(
{
"tool": {"driver": {"name": check_name}},
"results": ({"level": level},),
}
for check_name, level in check_results
),
}
)
)
raise subprocess.CalledProcessError(returncode=1, cmd=cmd)
def _make_shac_os_namespace() -> types.SimpleNamespace:
return types.SimpleNamespace(
environ=os.environ,
path=os.path,
access=os.access,
X_OK=os.X_OK,
kill=mock.create_autospec(
os.kill, spec_set=True, side_effect=ProcessLookupError
),
)
class _PermissionErrorPath(pathlib.PosixPath):
"""Path subclass whose `read_text()` and `stat()` raise `PermissionError`."""
def read_text(self, *args: object, **kwargs: object) -> str:
raise PermissionError("denied")
def stat(self, *, follow_symlinks: bool = True) -> os.stat_result:
raise PermissionError("denied")
class ShacRunnerTest(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
temp_dir = self.enterContext(tempfile.TemporaryDirectory())
self.fuchsia_dir = pathlib.Path(temp_dir)
self.build_dir = self.fuchsia_dir / "out" / "default"
self.build_dir.mkdir(parents=True)
self.shac_binary = self.fuchsia_dir / "shac"
self.shac_binary.touch()
self.enterContext(
mock.patch.dict(
os.environ,
{"PREBUILT_SHAC": str(self.shac_binary)},
)
)
def test_run_shac_validates_explicit_files(self) -> None:
existing = self.fuchsia_dir / "foo.cc"
existing.touch()
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("foo.cc",),
),
)
with (
mock.patch.object(
scm, "get_repo_groups", autospec=True, return_value=repo_groups
) as mock_get_groups,
mock.patch.object(
subprocess,
"run",
autospec=True,
return_value=subprocess.CompletedProcess(args=[], returncode=0),
),
mock.patch.object(
sys, "stderr", new_callable=io.StringIO
) as mock_stderr,
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
explicit_files=("//foo.cc", "//missing.cc"),
)
mock_get_groups.assert_called_once_with(
self.fuchsia_dir,
self.fuchsia_dir,
explicit_files=("//foo.cc",),
all_repos=False,
)
self.assertIn("ERROR: no such file:", mock_stderr.getvalue())
def test_run_shac_returns_early_when_all_explicit_files_missing(
self,
) -> None:
with (
mock.patch.object(
scm, "get_repo_groups", autospec=True
) as mock_get_groups,
mock.patch.object(
sys, "stderr", new_callable=io.StringIO
) as mock_stderr,
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
explicit_files=("//missing.cc", " "),
)
mock_get_groups.assert_not_called()
self.assertIn("ERROR: no such file:", mock_stderr.getvalue())
def test_run_shac_raises_when_shac_binary_missing(self) -> None:
missing_shac = self.fuchsia_dir / "nonexistent_shac"
with (
mock.patch.dict(os.environ, {"PREBUILT_SHAC": str(missing_shac)}),
self.assertRaises(FileNotFoundError),
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
def _populate_static_check_tools(
self,
*,
labels: Mapping[str, str | None] | None = None,
) -> None:
host_os, host_cpu = shac_runner._host_platform_and_cpu()
host_dir = self.build_dir / f"host_{host_cpu}"
host_dir.mkdir(parents=True, exist_ok=True)
custom_labels = labels if labels is not None else {}
entries = []
for tool_name in sorted(shac_runner._STATIC_CHECK_TOOLS):
relative_path = f"host_{host_cpu}/{tool_name}"
tool_binary = self.build_dir / relative_path
tool_binary.touch(mode=0o755)
tool_binary.chmod(0o755)
entry = {
"name": tool_name,
"path": relative_path,
"os": host_os,
"cpu": host_cpu,
}
if tool_name in custom_labels:
label = custom_labels[tool_name]
if label is not None:
entry["label"] = label
else:
entry["label"] = (
f"//tools/{tool_name}:{tool_name}"
f"(//build/toolchain:host_{host_cpu})"
)
entries.append(entry)
(self.build_dir / "tool_paths.json").write_text(json.dumps(entries))
def test_run_shac_skips_build_when_no_repo_has_shac(self) -> None:
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=False,
files=(),
),
)
with (
mock.patch.object(
scm, "get_repo_groups", autospec=True, return_value=repo_groups
),
mock.patch.object(subprocess, "run", autospec=True) as mock_run,
mock.patch.object(
sys, "stderr", new_callable=io.StringIO
) as mock_stderr,
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
mock_run.assert_not_called()
self.assertEqual(
mock_stderr.getvalue(),
f"WARNING: no shac.textproto found in {self.fuchsia_dir};"
" nothing to do.\n",
)
def test_run_shac_skips_build_when_static_check_tools_present(self) -> None:
self._populate_static_check_tools()
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("foo.cc",),
),
)
with (
mock.patch.object(
scm, "get_repo_groups", autospec=True, return_value=repo_groups
),
mock.patch.object(
subprocess,
"run",
autospec=True,
return_value=subprocess.CompletedProcess(args=[], returncode=0),
) as mock_run,
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
mock_run.assert_called_once()
command = mock_run.call_args.args[0]
self.assertEqual(command[0], str(self.shac_binary))
def test_run_shac_builds_when_static_check_tool_missing_from_disk(
self,
) -> None:
self._populate_static_check_tools()
_, host_cpu = shac_runner._host_platform_and_cpu()
(self.build_dir / f"host_{host_cpu}" / "cmc").unlink()
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("foo.cml",),
),
)
with (
mock.patch.object(
scm, "get_repo_groups", autospec=True, return_value=repo_groups
),
mock.patch.object(
subprocess,
"run",
autospec=True,
return_value=subprocess.CompletedProcess(args=[], returncode=0),
) as mock_run,
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
self.assertEqual(mock_run.call_count, 2)
def test_run_shac_builds_when_tool_paths_json_malformed(self) -> None:
(self.build_dir / "tool_paths.json").write_text("{not valid json")
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("foo.cc",),
),
)
with (
mock.patch.object(
scm, "get_repo_groups", autospec=True, return_value=repo_groups
),
mock.patch.object(
subprocess,
"run",
autospec=True,
return_value=subprocess.CompletedProcess(args=[], returncode=0),
) as mock_run,
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
self.assertEqual(mock_run.call_count, 2)
def test_run_shac_uses_prebuilt_shac_env(self) -> None:
custom_shac = self.fuchsia_dir / "custom_shac"
custom_shac.touch()
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("foo.cc",),
),
)
with (
mock.patch.dict(os.environ, {"PREBUILT_SHAC": str(custom_shac)}),
mock.patch.object(
scm, "get_repo_groups", autospec=True, return_value=repo_groups
),
mock.patch.object(
subprocess,
"run",
autospec=True,
return_value=subprocess.CompletedProcess(args=[], returncode=0),
) as mock_run,
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
self.assertEqual(mock_run.call_count, 2)
command = mock_run.call_args_list[1].args[0]
self.assertEqual(command[0], str(custom_shac))
def test_run_shac_command_construction(self) -> None:
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("foo.cc",),
),
)
with (
mock.patch.object(
scm, "get_repo_groups", autospec=True, return_value=repo_groups
) as mock_get_groups,
mock.patch.object(
subprocess,
"run",
autospec=True,
return_value=subprocess.CompletedProcess(args=[], returncode=0),
) as mock_run,
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
all_files=True,
only_checks=("clang_format", "commit_msg"),
skip_checks=("rustfmt",),
extra_args=("--no-color",),
)
mock_get_groups.assert_called_once_with(
self.fuchsia_dir,
self.fuchsia_dir,
explicit_files=None,
all_repos=False,
)
self.assertEqual(mock_run.call_count, 2)
build_call = mock_run.call_args_list[0]
self.assertSequenceEqual(
build_call.args[0],
(
str(self.fuchsia_dir / "scripts" / "fx"),
"build",
"--host",
"//bundles/buildbot/static_checks",
),
)
self.assertEqual(
build_call.kwargs["env"]["FUCHSIA_DIR"],
str(self.fuchsia_dir),
)
self.assertEqual(
build_call.kwargs["env"]["FUCHSIA_BUILD_DIR"],
str(self.build_dir),
)
shac_command = mock_run.call_args_list[1].args[0]
json_output_args = tuple(
arg for arg in shac_command if arg.startswith("--json-output=")
)
self.assertEqual(len(json_output_args), 1)
self.assertSequenceEqual(
tuple(
arg
for arg in shac_command
if not arg.startswith("--json-output=")
),
(
str(self.shac_binary),
"check",
"-C",
str(self.fuchsia_dir),
"--var=fuchsia_dir=.",
"--var=fuchsia_build_dir=out/default",
"--all",
"--no-untracked",
"--quiet",
"--only=clang_format,commit_msg",
"--skip=rustfmt",
"--no-color",
"foo.cc",
),
)
def test_run_shac_verbose_command_construction(self) -> None:
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("foo.cc",),
),
)
with (
mock.patch.object(
scm, "get_repo_groups", autospec=True, return_value=repo_groups
),
mock.patch.object(
subprocess,
"run",
autospec=True,
return_value=subprocess.CompletedProcess(args=[], returncode=0),
) as mock_run,
mock.patch.object(
sys, "stdout", new_callable=io.StringIO
) as mock_stdout,
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
verbose=True,
)
self.assertEqual(mock_run.call_count, 2)
shac_command = mock_run.call_args_list[1].args[0]
self.assertSequenceEqual(
tuple(
arg
for arg in shac_command
if not arg.startswith("--json-output=")
),
(
str(self.shac_binary),
"check",
"-C",
str(self.fuchsia_dir),
"--var=fuchsia_dir=.",
"--var=fuchsia_build_dir=out/default",
"--no-untracked",
"--verbose",
"foo.cc",
),
)
self.assertIn(
"build --host //bundles/buildbot/static_checks",
mock_stdout.getvalue(),
)
def test_run_shac_include_untracked_omits_no_untracked_flag(self) -> None:
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=(),
),
)
self._populate_static_check_tools()
for subcommand in ("check", "fix", "fmt"):
for include_untracked in (False, True):
with self.subTest(
subcommand=subcommand, include_untracked=include_untracked
):
with (
mock.patch.object(
scm,
"get_repo_groups",
autospec=True,
return_value=repo_groups,
),
mock.patch.object(
subprocess,
"run",
autospec=True,
return_value=subprocess.CompletedProcess(
args=[], returncode=0
),
) as mock_run,
):
shac_runner.run_shac(
subcommand,
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
include_untracked=include_untracked,
)
self.assertEqual(mock_run.call_count, 1)
shac_command = mock_run.call_args_list[0].args[0]
if include_untracked:
self.assertNotIn("--no-untracked", shac_command)
else:
self.assertIn("--no-untracked", shac_command)
def test_run_shac_dry_run_skips_execution(self) -> None:
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("foo.cc",),
),
)
for subcommand in ("check", "fix"):
with self.subTest(subcommand=subcommand):
with (
mock.patch.object(
scm,
"get_repo_groups",
autospec=True,
return_value=repo_groups,
),
mock.patch.object(
subprocess, "run", autospec=True
) as mock_run,
mock.patch.object(
sys, "stdout", new_callable=io.StringIO
) as mock_stdout,
):
shac_runner.run_shac(
subcommand,
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
dry_run=True,
)
mock_run.assert_not_called()
stdout = mock_stdout.getvalue()
self.assertIn(
"[dry-run] Would execute:"
f" {self.fuchsia_dir / 'scripts' / 'fx'} build --host"
" //bundles/buildbot/static_checks",
stdout,
)
self.assertIn(
f"[dry-run] Would execute: {self.shac_binary} {subcommand}",
stdout,
)
self.assertNotIn("--json-output=", stdout)
def test_run_shac_propagates_build_error(self) -> None:
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("foo.cc",),
),
)
with (
mock.patch.object(
scm, "get_repo_groups", autospec=True, return_value=repo_groups
),
mock.patch.object(
subprocess,
"run",
autospec=True,
side_effect=subprocess.CalledProcessError(
returncode=1, cmd=["fx", "build"]
),
) as mock_run,
self.assertRaises(subprocess.CalledProcessError),
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
mock_run.assert_called_once()
def test_run_shac_propagates_subprocess_error(self) -> None:
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("foo.cc",),
),
)
with (
mock.patch.object(
scm, "get_repo_groups", autospec=True, return_value=repo_groups
),
mock.patch.object(
subprocess,
"run",
autospec=True,
side_effect=(
subprocess.CompletedProcess(args=[], returncode=0),
subprocess.CalledProcessError(
returncode=1, cmd=["shac", "check"]
),
),
) as mock_run,
self.assertRaises(subprocess.CalledProcessError) as cm,
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
self.assertEqual(mock_run.call_count, 2)
self.assertFalse(getattr(cm.exception, "__notes__", ()))
def test_run_shac_executes_across_multiple_repos(self) -> None:
subrepo = self.fuchsia_dir / "vendor" / "google"
subrepo.mkdir(parents=True)
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("src/main.cc",),
),
scm.RepoGroup(
repo_root=subrepo,
has_shac=True,
files=("foo/bar.cc",),
),
)
with (
mock.patch.object(
scm, "get_repo_groups", autospec=True, return_value=repo_groups
) as mock_get_groups,
mock.patch.object(
subprocess,
"run",
autospec=True,
return_value=subprocess.CompletedProcess(args=[], returncode=0),
) as mock_run,
):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
all_repos=True,
)
mock_get_groups.assert_called_once_with(
self.fuchsia_dir,
self.fuchsia_dir,
explicit_files=None,
all_repos=True,
)
self.assertEqual(mock_run.call_count, 3)
build_command = mock_run.call_args_list[0].args[0]
first_shac_command = mock_run.call_args_list[1].args[0]
second_shac_command = mock_run.call_args_list[2].args[0]
self.assertSequenceEqual(
build_command,
(
str(self.fuchsia_dir / "scripts" / "fx"),
"build",
"--host",
"//bundles/buildbot/static_checks",
),
)
self.assertSequenceEqual(
tuple(
arg
for arg in first_shac_command
if not arg.startswith("--json-output=")
),
(
str(self.shac_binary),
"check",
"-C",
str(self.fuchsia_dir),
"--var=fuchsia_dir=.",
"--var=fuchsia_build_dir=out/default",
"--no-untracked",
"--quiet",
"src/main.cc",
),
)
self.assertSequenceEqual(
tuple(
arg
for arg in second_shac_command
if not arg.startswith("--json-output=")
),
(
str(self.shac_binary),
"check",
"-C",
str(subrepo),
"--var=fuchsia_dir=../..",
"--var=fuchsia_build_dir=out/default",
"--no-untracked",
"--quiet",
"foo/bar.cc",
),
)
def test_split_comma_separated(self) -> None:
self.assertSequenceEqual(
shac_runner.split_comma_separated(()),
(),
)
self.assertSequenceEqual(
shac_runner.split_comma_separated(
("clang_format, rustfmt ", "", "commit_msg , ")
),
("clang_format", "rustfmt", "commit_msg"),
)
def test_resolve_workspace_paths_defaults(self) -> None:
env_without_dirs = {
key: value
for key, value in os.environ.items()
if key not in ("FUCHSIA_DIR", "FUCHSIA_BUILD_DIR")
}
with mock.patch.dict(os.environ, env_without_dirs, clear=True):
fuchsia_dir, build_dir, _ = shac_runner.resolve_workspace_paths(
self.fuchsia_dir
)
self.assertEqual(fuchsia_dir, self.fuchsia_dir.resolve())
self.assertEqual(
build_dir, (self.fuchsia_dir / "out" / "default").resolve()
)
def test_resolve_workspace_paths_from_env(self) -> None:
custom_build_dir = self.fuchsia_dir / "out" / "custom"
with mock.patch.dict(
os.environ,
{
"FUCHSIA_DIR": str(self.fuchsia_dir),
"FUCHSIA_BUILD_DIR": str(custom_build_dir),
},
):
fuchsia_dir, build_dir, _ = shac_runner.resolve_workspace_paths(
pathlib.Path("/unused/fallback")
)
self.assertEqual(fuchsia_dir, self.fuchsia_dir.resolve())
self.assertEqual(build_dir, custom_build_dir.resolve())
def _bump_tool_binary(self, tool_name: str) -> None:
_, host_cpu = shac_runner._host_platform_and_cpu()
tool_binary = self.build_dir / f"host_{host_cpu}" / tool_name
tool_binary.write_bytes(tool_binary.read_bytes() + b"x")
def _run_shac_with_mocked_subprocess(
self,
*,
subcommand: str = "check",
files: Collection[str] = ("docs/foo.md",),
only_checks: Collection[str] = (),
skip_checks: Collection[str] = (),
extra_args: Sequence[str] = (),
side_effect: object = None,
) -> mock.MagicMock:
repo_groups = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=tuple(files),
),
)
if side_effect is not None:
run_side_effect = side_effect
else:
def _succeed(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
return subprocess.CompletedProcess(args=cmd, returncode=0)
run_side_effect = _succeed
with (
mock.patch.object(
shac_runner, "scm", autospec=True, spec_set=True
) as mock_scm,
mock.patch.object(
shac_runner, "subprocess", autospec=True, spec_set=True
) as mock_subprocess,
):
mock_scm.get_repo_groups.return_value = repo_groups
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
mock_subprocess.DEVNULL = subprocess.DEVNULL
mock_subprocess.run.side_effect = run_side_effect
shac_runner.run_shac(
subcommand,
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
only_checks=only_checks,
skip_checks=skip_checks,
extra_args=extra_args,
)
return mock_subprocess.run
def test_run_shac_rebuilds_compiled_tool_and_retries_on_sarif_failure(
self,
) -> None:
self._populate_static_check_tools(
labels={
"doc-checker": "//tools/doc_checker:doc-checker(//build/toolchain:host_x64)"
}
)
calls = 0
def fake_run(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal calls
calls += 1
if calls == 1:
_fail_with_sarif(cmd, (("doc_checker", "error"),))
if calls == 2:
self._bump_tool_binary("doc-checker")
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_run = self._run_shac_with_mocked_subprocess(side_effect=fake_run)
self.assertEqual(mock_run.call_count, 3)
self.assertEqual(
mock_run.call_args_list[0].args[0][0], str(self.shac_binary)
)
self.assertEqual(
mock_run.call_args_list[0].kwargs["stdin"], subprocess.DEVNULL
)
self.assertSequenceEqual(
mock_run.call_args_list[1].args[0],
(
str(self.fuchsia_dir / "scripts" / "fx"),
"build",
"--host",
"//tools/doc_checker:doc-checker",
),
)
self.assertIs(mock_run.call_args_list[1].kwargs["stdout"], sys.stderr)
self.assertNotIn("stdin", mock_run.call_args_list[1].kwargs)
self.assertEqual(
mock_run.call_args_list[2].args[0][0], str(self.shac_binary)
)
self.assertEqual(
mock_run.call_args_list[2].kwargs["stdin"], subprocess.DEVNULL
)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_fmt_emit_does_not_block_on_open_stdin(
self, mock_scm: mock.MagicMock
) -> None:
self._populate_static_check_tools()
self.shac_binary.write_text(
"#!/bin/sh\n"
f"exec {shlex.quote(sys.executable)} -c "
"\"import signal, sys; signal.alarm(5); assert sys.stdin.read() == ''\"\n"
)
self.shac_binary.chmod(0o755)
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
)
read_fd, write_fd = os.pipe()
saved_stdin_fd = os.dup(0)
try:
os.dup2(read_fd, 0)
shac_runner.run_shac(
"fmt",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
extra_args=("--emit",),
)
finally:
os.dup2(saved_stdin_fd, 0)
os.close(saved_stdin_fd)
os.close(read_fd)
os.close(write_fd)
def test_run_shac_sarif_multiple_failures_deduplicates_and_filters_targets(
self,
) -> None:
self._populate_static_check_tools(
labels={
"cmc": "//tools/cmc:cmc(//build/toolchain:host_x64)",
"doc-checker": "//tools/doc_checker:doc-checker(//build/toolchain:host_x64)",
"fidl-lint": "//tools/fidl/fidlc:fidl-lint(//build/toolchain:host_x64)",
}
)
for sarif_failures, bumped_tools, expected_targets in (
(
(("cml_format", "error"), ("dml_format", "error")),
("cmc",),
("//tools/cmc:cmc",),
),
(
(("doc_checker", "error"), ("py_shebangs", "error")),
("doc-checker",),
("//tools/doc_checker:doc-checker",),
),
(
(("doc_checker", "error"), ("fidl_lint", "error")),
("doc-checker", "fidl-lint"),
(
"//tools/doc_checker:doc-checker",
"//tools/fidl/fidlc:fidl-lint",
),
),
):
with self.subTest(
sarif_failures=sarif_failures,
expected_targets=expected_targets,
):
calls = 0
def fake_run(
cmd: Sequence[str],
failures: Sequence[tuple[str, str]] = sarif_failures,
tools_to_bump: Collection[str] = bumped_tools,
**_kwargs: object,
) -> subprocess.CompletedProcess[bytes]:
nonlocal calls
calls += 1
if calls == 1:
_fail_with_sarif(cmd, failures)
if calls == 2:
for tool_name in tools_to_bump:
self._bump_tool_binary(tool_name)
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_run = self._run_shac_with_mocked_subprocess(
side_effect=fake_run
)
self.assertEqual(mock_run.call_count, 3)
self.assertSequenceEqual(
mock_run.call_args_list[1].args[0],
(
str(self.fuchsia_dir / "scripts" / "fx"),
"build",
"--host",
*expected_targets,
),
)
def test_run_shac_falls_back_to_static_checks_when_tool_label_missing(
self,
) -> None:
self._populate_static_check_tools(labels={"doc-checker": None})
calls = 0
def fake_run(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal calls
calls += 1
if calls == 1:
_fail_with_sarif(cmd, (("doc_checker", "error"),))
if calls == 2:
self._bump_tool_binary("doc-checker")
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_run = self._run_shac_with_mocked_subprocess(side_effect=fake_run)
self.assertEqual(mock_run.call_count, 3)
self.assertSequenceEqual(
mock_run.call_args_list[1].args[0],
(
str(self.fuchsia_dir / "scripts" / "fx"),
"build",
"--host",
"//bundles/buildbot/static_checks",
),
)
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_skips_retry_when_rebuilt_binary_unchanged(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
self._populate_static_check_tools(
labels={
"doc-checker": "//tools/doc_checker:doc-checker(//build/toolchain:host_x64)"
}
)
calls = 0
def fake_run(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal calls
calls += 1
if calls == 1:
_fail_with_sarif(cmd, (("doc_checker", "error"),))
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
)
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
mock_subprocess.run.side_effect = fake_run
with self.assertRaises(subprocess.CalledProcessError):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
# Runs initial shac + fx build, then skips duplicate shac retry when
# the binary did not change.
self.assertEqual(mock_subprocess.run.call_count, 2)
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_skips_rebuild_for_non_compiled_sarif_failures(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
self._populate_static_check_tools()
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
)
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
for check_name in ("py_shebangs", "keep_sorted", "owners"):
with self.subTest(check_name=check_name):
mock_subprocess.run.reset_mock()
mock_subprocess.run.side_effect = (
lambda cmd, name=check_name, **_kw: _fail_with_sarif(
cmd, ((name, "error"),)
)
)
with self.assertRaises(subprocess.CalledProcessError):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
self.assertEqual(mock_subprocess.run.call_count, 1)
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_sarif_fail_level_and_empty_sarif_handling(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
self._populate_static_check_tools(
labels={
"doc-checker": "//tools/doc_checker:doc-checker(//build/toolchain:host_x64)"
}
)
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
)
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
# Non-failing warning/note results or valid empty SARIF must not
# trigger a rebuild under the default --fail-level=error.
for label, payload in (
(
"warning_only",
{
"version": "2.1.0",
"runs": (
{
"tool": {"driver": {"name": "doc_checker"}},
"results": ({"level": "warning"},),
},
),
},
),
(
"note_only",
{
"version": "2.1.0",
"runs": (
{
"tool": {"driver": {"name": "doc_checker"}},
"results": ({"level": "note"},),
},
),
},
),
("empty_sarif_no_runs", {"version": "2.1.0"}),
("empty_sarif_empty_runs", {"version": "2.1.0", "runs": ()}),
):
with self.subTest(case=label):
def _fail_payload(
cmd: Sequence[str],
expected_payload: Mapping[str, object] = payload,
**_kwargs: object,
) -> NoReturn:
for arg in cmd:
if arg.startswith("--json-output="):
pathlib.Path(arg.split("=", 1)[1]).write_text(
json.dumps(expected_payload)
)
raise subprocess.CalledProcessError(returncode=1, cmd=cmd)
mock_subprocess.run.reset_mock()
mock_subprocess.run.side_effect = _fail_payload
with self.assertRaises(subprocess.CalledProcessError):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
self.assertEqual(mock_subprocess.run.call_count, 1)
# With --fail-level=warning, a warning-level compiled check DOES
# trigger a targeted rebuild and retry.
calls = 0
def fake_warning_run(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal calls
calls += 1
if calls == 1:
_fail_with_sarif(cmd, (("doc_checker", "warning"),))
if calls == 2:
self._bump_tool_binary("doc-checker")
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_subprocess.run.reset_mock()
mock_subprocess.run.side_effect = fake_warning_run
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
extra_args=("--fail-level=warning",),
)
self.assertEqual(mock_subprocess.run.call_count, 3)
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_skips_rebuild_when_no_compiled_check_eligible(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
self._populate_static_check_tools()
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
for subcommand, only_checks, skip_checks, files, extra_args in (
("check", ("py_shebangs",), (), ("docs/foo.md",), ()),
("fmt", ("rustfmt",), (), ("src/main.rs",), ()),
("fmt", (), (), ("src/main.py", "src/lib.rs", "src/foo.cc"), ()),
("fmt", (), (), (), ()),
("fmt", (), (), ("fidl/foo.fidl",), ("--emit",)),
("fmt", (), (), ("fidl/foo.fidl",), ("--emit=true",)),
("fmt", (), (), ("fidl/foo.fidl",), ("--emit=1",)),
("fmt", (), (), ("a.fidl", "b.fidl"), ("--emit",)),
("fmt", (), ("fidl_format",), ("fidl/foo.fidl",), ()),
(
"fmt",
(),
("*_format",),
("fidl/foo.fidl", "config/foo.json5"),
(),
),
("fmt", ("*_format",), ("*_format",), (), ()),
):
with self.subTest(
subcommand=subcommand,
only_checks=only_checks,
skip_checks=skip_checks,
files=files,
extra_args=extra_args,
):
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=files,
),
)
mock_subprocess.run.reset_mock()
mock_subprocess.run.side_effect = subprocess.CalledProcessError(
returncode=1, cmd=("shac", subcommand)
)
with self.assertRaises(subprocess.CalledProcessError):
shac_runner.run_shac(
subcommand,
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
only_checks=only_checks,
skip_checks=skip_checks,
extra_args=extra_args,
)
self.assertEqual(mock_subprocess.run.call_count, 1)
def test_run_shac_fmt_rebuilds_eligible_formatter_on_failure(self) -> None:
self._populate_static_check_tools(
labels={
"fidl-format": "//tools/fidl/fidlc:fidl-format(//build/toolchain:host_x64)",
"formatjson5": "//tools/formatjson5:formatjson5(//build/toolchain:host_x64)",
}
)
for (
files,
only_checks,
skip_checks,
extra_args,
tool_name,
expected_target,
) in (
(
("fidl/foo.fidl",),
(),
(),
(),
"fidl-format",
"//tools/fidl/fidlc:fidl-format",
),
(
("config/foo.json5",),
(),
(),
(),
"formatjson5",
"//tools/formatjson5:formatjson5",
),
(
("config/foo.persist",),
(),
(),
(),
"formatjson5",
"//tools/formatjson5:formatjson5",
),
(
("config/foo.triage",),
(),
(),
(),
"formatjson5",
"//tools/formatjson5:formatjson5",
),
(
(),
("fidl_format",),
(),
(),
"fidl-format",
"//tools/fidl/fidlc:fidl-format",
),
(
("fidl/foo.fidl",),
("*_format",),
(),
(),
"fidl-format",
"//tools/fidl/fidlc:fidl-format",
),
(
("fidl/foo.fidl", "config/foo.json5"),
("*_format",),
("fidl_format",),
(),
"formatjson5",
"//tools/formatjson5:formatjson5",
),
(
("fidl/foo.fidl",),
(),
(),
("--emit=false",),
"fidl-format",
"//tools/fidl/fidlc:fidl-format",
),
):
with self.subTest(
files=files,
only_checks=only_checks,
skip_checks=skip_checks,
extra_args=extra_args,
expected_target=expected_target,
):
calls = 0
def fake_run(
cmd: Sequence[str],
bumped_tool: str = tool_name,
**_kwargs: object,
) -> subprocess.CompletedProcess[bytes]:
nonlocal calls
calls += 1
if calls == 1:
raise subprocess.CalledProcessError(
returncode=1, cmd=cmd
)
if calls == 2:
self._bump_tool_binary(bumped_tool)
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_run = self._run_shac_with_mocked_subprocess(
subcommand="fmt",
files=files,
only_checks=only_checks,
skip_checks=skip_checks,
extra_args=extra_args,
side_effect=fake_run,
)
self.assertEqual(mock_run.call_count, 3)
self.assertSequenceEqual(
mock_run.call_args_list[1].args[0],
(
str(self.fuchsia_dir / "scripts" / "fx"),
"build",
"--host",
expected_target,
),
)
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_skips_reactive_rebuild_when_build_lock_held(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
self._populate_static_check_tools()
lock_file = self.build_dir.parent / f"{self.build_dir.name}.build_lock"
lock_file.write_text(f"{os.getpid()}\n")
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
)
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
mock_subprocess.run.side_effect = lambda cmd, **_kw: _fail_with_sarif(
cmd, (("doc_checker", "error"),)
)
with self.assertRaises(subprocess.CalledProcessError) as cm:
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
only_checks=("doc_checker",),
)
self.assertEqual(mock_subprocess.run.call_count, 1)
notes = getattr(cm.exception, "__notes__", ())
self.assertTrue(
any("build_lock" in note for note in notes),
f"Expected .build_lock note, got {notes!r}",
)
@mock.patch.object(shac_runner, "os", new_callable=_make_shac_os_namespace)
def test_run_shac_rebuilds_when_build_lock_pid_is_stale(
self, mock_os: types.SimpleNamespace
) -> None:
self._populate_static_check_tools()
lock_file = self.build_dir.parent / f"{self.build_dir.name}.build_lock"
for lock_pid in ("999999", "0", "-1"):
with self.subTest(lock_pid=lock_pid):
mock_os.kill.reset_mock()
lock_file.write_text(f"{lock_pid}\n")
calls = 0
def fake_run(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal calls
calls += 1
if calls == 1:
_fail_with_sarif(cmd, (("doc_checker", "error"),))
if calls == 2:
self._bump_tool_binary("doc-checker")
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_run = self._run_shac_with_mocked_subprocess(
only_checks=("doc_checker",),
side_effect=fake_run,
)
self.assertEqual(mock_run.call_count, 3)
if int(lock_pid) <= 0:
mock_os.kill.assert_not_called()
else:
mock_os.kill.assert_called_once_with(int(lock_pid), 0)
@mock.patch.object(shac_runner, "os", autospec=True, spec_set=True)
def test_is_build_lock_held_edge_cases(
self, mock_os: mock.MagicMock
) -> None:
lock_file = self.build_dir.parent / f"{self.build_dir.name}.build_lock"
self.assertFalse(shac_runner._is_build_lock_held(self.build_dir))
for content in ("", "\n", " \n"):
with self.subTest(empty_content=repr(content)):
mock_os.kill.reset_mock()
lock_file.write_text(content)
self.assertFalse(
shac_runner._is_build_lock_held(self.build_dir)
)
mock_os.kill.assert_not_called()
mock_os.kill.reset_mock()
lock_file.write_text("not-a-pid\n")
self.assertTrue(shac_runner._is_build_lock_held(self.build_dir))
mock_os.kill.assert_not_called()
mock_os.kill.reset_mock()
mock_os.kill.side_effect = PermissionError
lock_file.write_text("12345\n")
self.assertTrue(shac_runner._is_build_lock_held(self.build_dir))
mock_os.kill.assert_called_once_with(12345, 0)
mock_os.kill.reset_mock()
lock_file.write_bytes(b"\xff\xfe\n")
self.assertTrue(shac_runner._is_build_lock_held(self.build_dir))
mock_os.kill.assert_not_called()
mock_os.kill.reset_mock()
lock_file.unlink()
lock_file.mkdir()
try:
with self.assertRaises(IsADirectoryError):
shac_runner._is_build_lock_held(self.build_dir)
finally:
lock_file.rmdir()
mock_os.kill.assert_not_called()
lock_file.write_text("not-a-pid\n")
self.assertTrue(
shac_runner._is_build_lock_held(
_PermissionErrorPath(self.build_dir)
)
)
mock_os.kill.assert_not_called()
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_rebuilds_only_once_when_retry_also_fails(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
self._populate_static_check_tools()
calls = 0
def fake_run(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal calls
calls += 1
if calls == 2:
self._bump_tool_binary("doc-checker")
return subprocess.CompletedProcess(args=cmd, returncode=0)
_fail_with_sarif(cmd, (("doc_checker", "error"),))
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
)
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
mock_subprocess.run.side_effect = fake_run
with self.assertRaises(subprocess.CalledProcessError) as cm:
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
only_checks=("doc_checker",),
)
self.assertEqual(mock_subprocess.run.call_count, 3)
self.assertIsNone(cm.exception.__context__)
self.assertIsNone(cm.exception.__cause__)
def test_run_shac_preserves_user_json_output_flag(self) -> None:
self._populate_static_check_tools()
for extra_args in (
("--json-output=/tmp/custom.sarif.json",),
("--json-output", "/tmp/custom.sarif.json"),
):
with self.subTest(extra_args=extra_args):
mock_run = self._run_shac_with_mocked_subprocess(
extra_args=extra_args,
)
self.assertEqual(mock_run.call_count, 1)
cmd = mock_run.call_args.args[0]
json_output_flags = tuple(
arg for arg in cmd if arg.startswith("--json-output")
)
self.assertSequenceEqual(json_output_flags, (extra_args[0],))
if len(extra_args) > 1:
self.assertIn(extra_args[1], cmd)
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_skips_rebuild_on_failure_with_user_json_output_flag(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
self._populate_static_check_tools()
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
)
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
for extra_args in (
("--json-output=/tmp/custom.sarif.json",),
("--json-output", "-"),
):
with self.subTest(extra_args=extra_args):
mock_subprocess.run.reset_mock()
mock_subprocess.run.side_effect = subprocess.CalledProcessError(
returncode=1, cmd=("shac", "check")
)
with self.assertRaises(subprocess.CalledProcessError):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
extra_args=extra_args,
)
self.assertEqual(mock_subprocess.run.call_count, 1)
def test_run_shac_fix_rebuilds_compiled_tool_and_retries_on_sarif_failure(
self,
) -> None:
self._populate_static_check_tools(
labels={
"doc-checker": "//tools/doc_checker:doc-checker(//build/toolchain:host_x64)"
}
)
calls = 0
def fake_run(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal calls
calls += 1
if calls == 1:
_fail_with_sarif(cmd, (("doc_checker", "error"),))
if calls == 2:
self._bump_tool_binary("doc-checker")
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_run = self._run_shac_with_mocked_subprocess(
subcommand="fix",
side_effect=fake_run,
)
self.assertEqual(mock_run.call_count, 3)
self.assertEqual(mock_run.call_args_list[0].args[0][1], "fix")
self.assertSequenceEqual(
mock_run.call_args_list[1].args[0],
(
str(self.fuchsia_dir / "scripts" / "fx"),
"build",
"--host",
"//tools/doc_checker:doc-checker",
),
)
def test_run_shac_sarif_fail_level_space_separated_and_notice(self) -> None:
self._populate_static_check_tools(
labels={
"doc-checker": "//tools/doc_checker:doc-checker(//build/toolchain:host_x64)"
}
)
for extra_args, result_level in (
(("--fail-level", "warning"), "warning"),
(("--fail-level=notice",), "note"),
):
with self.subTest(extra_args=extra_args, result_level=result_level):
calls = 0
def fake_run(
cmd: Sequence[str],
level: str = result_level,
**_kwargs: object,
) -> subprocess.CompletedProcess[bytes]:
nonlocal calls
calls += 1
if calls == 1:
_fail_with_sarif(cmd, (("doc_checker", level),))
if calls == 2:
self._bump_tool_binary("doc-checker")
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_run = self._run_shac_with_mocked_subprocess(
extra_args=extra_args,
side_effect=fake_run,
)
self.assertEqual(mock_run.call_count, 3)
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_skips_rebuild_on_missing_or_malformed_sarif(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
self._populate_static_check_tools()
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
)
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
for label, sarif_body in (
("missing_sarif", None),
("invalid_json", "{not valid json"),
("invalid_utf8", b"\xff\xfe"),
("non_dict_json", "[]"),
("missing_version_and_runs", "{}"),
("non_list_runs", '{"version": "2.1.0", "runs": {}}'),
):
with self.subTest(case=label):
def _fail_without_valid_sarif(
cmd: Sequence[str],
body: str | bytes | None = sarif_body,
**_kwargs: object,
) -> NoReturn:
if body is not None:
for arg in cmd:
if arg.startswith("--json-output="):
sarif_path = pathlib.Path(arg.split("=", 1)[1])
if isinstance(body, bytes):
sarif_path.write_bytes(body)
else:
sarif_path.write_text(body)
raise subprocess.CalledProcessError(returncode=1, cmd=cmd)
mock_subprocess.run.reset_mock()
mock_subprocess.run.side_effect = _fail_without_valid_sarif
with self.assertRaises(subprocess.CalledProcessError):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
only_checks=("doc_checker",),
)
self.assertEqual(mock_subprocess.run.call_count, 1)
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_rebuilds_distinct_tools_across_multiple_repos(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
self._populate_static_check_tools(
labels={
"doc-checker": "//tools/doc_checker:doc-checker(//build/toolchain:host_x64)",
"fidl-lint": "//tools/fidl/fidlc:fidl-lint(//build/toolchain:host_x64)",
}
)
subrepo = self.fuchsia_dir / "vendor" / "google"
subrepo.mkdir(parents=True)
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
scm.RepoGroup(
repo_root=subrepo,
has_shac=True,
files=("fidl/foo.fidl",),
),
)
shac_calls = 0
def fake_run(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal shac_calls
if cmd[0] == str(self.shac_binary):
shac_calls += 1
if shac_calls == 1:
_fail_with_sarif(cmd, (("doc_checker", "error"),))
if shac_calls == 3:
_fail_with_sarif(cmd, (("fidl_lint", "error"),))
elif "//tools/doc_checker:doc-checker" in cmd:
self._bump_tool_binary("doc-checker")
elif "//tools/fidl/fidlc:fidl-lint" in cmd:
self._bump_tool_binary("fidl-lint")
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
mock_subprocess.run.side_effect = fake_run
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
all_repos=True,
)
self.assertEqual(mock_subprocess.run.call_count, 6)
self.assertSequenceEqual(
mock_subprocess.run.call_args_list[1].args[0],
(
str(self.fuchsia_dir / "scripts" / "fx"),
"build",
"--host",
"//tools/doc_checker:doc-checker",
),
)
self.assertSequenceEqual(
mock_subprocess.run.call_args_list[4].args[0],
(
str(self.fuchsia_dir / "scripts" / "fx"),
"build",
"--host",
"//tools/fidl/fidlc:fidl-lint",
),
)
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_skips_rebuilding_same_target_across_multiple_repos(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
self._populate_static_check_tools(
labels={
"doc-checker": "//tools/doc_checker:doc-checker(//build/toolchain:host_x64)"
}
)
subrepo = self.fuchsia_dir / "vendor" / "google"
subrepo.mkdir(parents=True)
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
scm.RepoGroup(
repo_root=subrepo,
has_shac=True,
files=("docs/bar.md",),
),
)
shac_calls = 0
def fake_run(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal shac_calls
if cmd[0] == str(self.shac_binary):
shac_calls += 1
if shac_calls in (1, 3):
_fail_with_sarif(cmd, (("doc_checker", "error"),))
elif "//tools/doc_checker:doc-checker" in cmd:
self._bump_tool_binary("doc-checker")
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
mock_subprocess.run.side_effect = fake_run
with self.assertRaises(subprocess.CalledProcessError):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
all_repos=True,
)
# Runs shac(repo1) -> fx build -> shac(repo1) -> shac(repo2) without
# rebuilding //tools/doc_checker:doc-checker a second time.
self.assertEqual(mock_subprocess.run.call_count, 4)
def test_load_host_tool_entries_and_stat_degrade_gracefully_on_errors(
self,
) -> None:
tool_paths_file = self.build_dir / "tool_paths.json"
tool_paths_file.write_bytes(b"\xff\xfe")
self.assertIsNone(shac_runner._load_host_tool_entries(self.build_dir))
tool_paths_file.unlink()
tool_paths_file.mkdir()
try:
with self.assertRaises(IsADirectoryError):
shac_runner._load_host_tool_entries(self.build_dir)
finally:
tool_paths_file.rmdir()
self._populate_static_check_tools()
with self.assertRaises(PermissionError):
shac_runner._load_host_tool_entries(
_PermissionErrorPath(self.build_dir)
)
not_a_dir = self.fuchsia_dir / "regular_file"
not_a_dir.touch()
self.assertIsNone(shac_runner._stat_tool_binary(not_a_dir / "tool"))
tool_path = self.fuchsia_dir / "tool"
tool_path.touch()
with self.assertRaises(PermissionError):
shac_runner._stat_tool_binary(_PermissionErrorPath(tool_path))
sarif_dir = self.fuchsia_dir / "sarif_dir"
sarif_dir.mkdir()
try:
with self.assertRaises(IsADirectoryError):
shac_runner._sarif_failed_checks(
sarif_dir, frozenset(("error",))
)
finally:
sarif_dir.rmdir()
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_propagates_called_process_error_when_fallbacks_hit_errors(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
self._populate_static_check_tools()
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
)
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
# If reading tool_paths.json fails decoding during recovery, fall back
# cleanly to rebuilding static_checks rather than raising UnicodeDecodeError.
calls = 0
def fake_corrupt_tool_paths(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal calls
calls += 1
if calls == 1:
(self.build_dir / "tool_paths.json").write_bytes(b"\xff\xfe")
_fail_with_sarif(cmd, (("doc_checker", "error"),))
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_subprocess.run.side_effect = fake_corrupt_tool_paths
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
self.assertEqual(mock_subprocess.run.call_count, 3)
self.assertSequenceEqual(
mock_subprocess.run.call_args_list[1].args[0],
(
str(self.fuchsia_dir / "scripts" / "fx"),
"build",
"--host",
"//bundles/buildbot/static_checks",
),
)
# If `.build_lock` is unreadable/binary, `_is_build_lock_held` fails
# closed so SHAC's CalledProcessError is raised without running fx build.
self._populate_static_check_tools(
labels={
"doc-checker": "//tools/doc_checker:doc-checker(//build/toolchain:host_x64)"
}
)
lock_file = self.build_dir.parent / f"{self.build_dir.name}.build_lock"
lock_file.write_bytes(b"\xff\xfe")
mock_subprocess.run.reset_mock()
mock_subprocess.run.side_effect = (
lambda cmd, **_kwargs: _fail_with_sarif(
cmd, (("doc_checker", "error"),)
)
)
with self.assertRaises(subprocess.CalledProcessError):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
self.assertEqual(mock_subprocess.run.call_count, 1)
lock_file.unlink()
# If `_stat_tool_binary` hits NotADirectoryError before and after rebuild,
# snapshots stay equal so SHAC's CalledProcessError is raised directly.
not_a_dir = self.build_dir / "not_a_dir"
not_a_dir.touch()
host_os, host_cpu = shac_runner._host_platform_and_cpu()
bad_tool_paths = (
{
"name": "doc-checker",
"path": "not_a_dir/doc-checker",
"label": "//tools/doc_checker:doc-checker(//build/toolchain:host_x64)",
"os": host_os,
"cpu": host_cpu,
},
)
stat_calls = 0
def fake_stat_error(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal stat_calls
stat_calls += 1
if stat_calls == 1:
(self.build_dir / "tool_paths.json").write_text(
json.dumps(bad_tool_paths)
)
_fail_with_sarif(cmd, (("doc_checker", "error"),))
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_subprocess.run.reset_mock()
mock_subprocess.run.side_effect = fake_stat_error
with self.assertRaises(subprocess.CalledProcessError):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
self.assertEqual(mock_subprocess.run.call_count, 2)
@mock.patch.object(shac_runner, "subprocess", autospec=True, spec_set=True)
@mock.patch.object(shac_runner, "scm", autospec=True, spec_set=True)
def test_run_shac_skips_reactive_rebuild_after_static_checks_build(
self, mock_scm: mock.MagicMock, mock_subprocess: mock.MagicMock
) -> None:
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
)
mock_subprocess.CalledProcessError = subprocess.CalledProcessError
def fake_preflight_then_sarif_failure(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
if "//bundles/buildbot/static_checks" in cmd:
self._populate_static_check_tools(
labels={
"doc-checker": "//tools/doc_checker:doc-checker(//build/toolchain:host_x64)"
}
)
return subprocess.CompletedProcess(args=cmd, returncode=0)
_fail_with_sarif(cmd, (("doc_checker", "error"),))
mock_subprocess.run.side_effect = fake_preflight_then_sarif_failure
with self.assertRaises(subprocess.CalledProcessError):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
)
# Pre-flight `fx build //bundles/buildbot/static_checks` + `shac`,
# without triggering a second per-tool `fx build`.
self.assertEqual(mock_subprocess.run.call_count, 2)
# If repo 1 falls back to rebuilding //bundles/buildbot/static_checks,
# repo 2 must not rebuild a different compiled tool target either.
self._populate_static_check_tools(
labels={
"doc-checker": None,
"fidl-lint": "//tools/fidl/fidlc:fidl-lint(//build/toolchain:host_x64)",
}
)
subrepo = self.fuchsia_dir / "vendor" / "google"
subrepo.mkdir(parents=True)
mock_scm.get_repo_groups.return_value = (
scm.RepoGroup(
repo_root=self.fuchsia_dir,
has_shac=True,
files=("docs/foo.md",),
),
scm.RepoGroup(
repo_root=subrepo,
has_shac=True,
files=("fidl/foo.fidl",),
),
)
shac_calls = 0
def fake_cross_repo_static_checks_fallback(
cmd: Sequence[str], **_kwargs: object
) -> subprocess.CompletedProcess[bytes]:
nonlocal shac_calls
if cmd[0] == str(self.shac_binary):
shac_calls += 1
if shac_calls == 1:
_fail_with_sarif(cmd, (("doc_checker", "error"),))
if shac_calls == 3:
_fail_with_sarif(cmd, (("fidl_lint", "error"),))
elif "//bundles/buildbot/static_checks" in cmd:
self._bump_tool_binary("doc-checker")
return subprocess.CompletedProcess(args=cmd, returncode=0)
mock_subprocess.run.reset_mock()
mock_subprocess.run.side_effect = fake_cross_repo_static_checks_fallback
with self.assertRaises(subprocess.CalledProcessError):
shac_runner.run_shac(
"check",
self.fuchsia_dir,
self.build_dir,
self.fuchsia_dir,
all_repos=True,
)
self.assertEqual(mock_subprocess.run.call_count, 4)
def test_cli_exit_status_returns_zero_on_success(self) -> None:
action = mock.MagicMock()
exit_code = shac_runner.cli_exit_status(action)
self.assertEqual(exit_code, 0)
action.assert_called_once_with()
def test_cli_exit_status_returns_subprocess_exit_code(self) -> None:
action = mock.MagicMock(
side_effect=subprocess.CalledProcessError(
returncode=2, cmd=("shac", "fmt")
)
)
with mock.patch.object(
sys, "stderr", new_callable=io.StringIO
) as mock_stderr:
exit_code = shac_runner.cli_exit_status(action)
self.assertEqual(exit_code, 2)
self.assertEqual(mock_stderr.getvalue(), "")
def test_cli_exit_status_forwards_captured_stderr(self) -> None:
for captured_stderr, expected in (
("fatal: not a git repository\n", "fatal: not a git repository\n"),
("fatal: no trailing newline", "fatal: no trailing newline\n"),
(b"fatal: bytes stderr", "fatal: bytes stderr\n"),
(b"bad\xffutf8", "bad\ufffdutf8\n"),
("", ""),
(b"", ""),
):
with self.subTest(captured_stderr=captured_stderr):
action = mock.MagicMock(
side_effect=subprocess.CalledProcessError(
returncode=128,
cmd=("git", "rev-parse", "--show-toplevel"),
stderr=captured_stderr,
)
)
with mock.patch.object(
sys, "stderr", new_callable=io.StringIO
) as mock_stderr:
exit_code = shac_runner.cli_exit_status(action)
self.assertEqual(exit_code, 128)
self.assertEqual(mock_stderr.getvalue(), expected)
def test_cli_exit_status_translates_non_sigint_signals_and_zero_code(
self,
) -> None:
for returncode, expected_exit_code in (
(-signal.SIGTERM, 128 + signal.SIGTERM),
(0, 1),
):
with self.subTest(returncode=returncode):
action = mock.MagicMock(
side_effect=subprocess.CalledProcessError(
returncode=returncode, cmd=("shac", "fmt")
)
)
exit_code = shac_runner.cli_exit_status(action)
self.assertEqual(exit_code, expected_exit_code)
def test_cli_exit_status_handles_os_error(self) -> None:
for error, expected_message in (
(
FileNotFoundError("shac binary not found."),
"ERROR: shac binary not found.\n",
),
(
PermissionError("permission denied"),
"ERROR: permission denied\n",
),
):
with self.subTest(error=error):
action = mock.MagicMock(side_effect=error)
with mock.patch.object(
sys, "stderr", new_callable=io.StringIO
) as mock_stderr:
exit_code = shac_runner.cli_exit_status(action)
self.assertEqual(exit_code, 1)
self.assertEqual(mock_stderr.getvalue(), expected_message)
def test_cli_exit_status_reraises_sigint_for_cooperative_exit(self) -> None:
for side_effect in (
KeyboardInterrupt(),
subprocess.CalledProcessError(
returncode=-signal.SIGINT, cmd=("shac", "fmt")
),
):
with self.subTest(side_effect=type(side_effect).__name__):
action = mock.MagicMock(side_effect=side_effect)
with (
mock.patch.object(
signal, "signal", autospec=True
) as mock_signal,
mock.patch.object(os, "kill", autospec=True) as mock_kill,
):
exit_code = shac_runner.cli_exit_status(action)
mock_signal.assert_called_once_with(
signal.SIGINT, signal.SIG_DFL
)
mock_kill.assert_called_once_with(os.getpid(), signal.SIGINT)
self.assertEqual(exit_code, 130)
def test_cli_exit_status_sigint_suppresses_broken_pipe_on_flush(
self,
) -> None:
action = mock.MagicMock(side_effect=KeyboardInterrupt)
mock_stdout = mock.create_autospec(io.TextIOBase, instance=True)
mock_stdout.flush.side_effect = BrokenPipeError("broken pipe")
mock_stderr = mock.create_autospec(io.TextIOBase, instance=True)
with (
mock.patch.object(sys, "stdout", mock_stdout),
mock.patch.object(sys, "stderr", mock_stderr),
mock.patch.object(signal, "signal", autospec=True) as mock_signal,
mock.patch.object(os, "kill", autospec=True) as mock_kill,
):
exit_code = shac_runner.cli_exit_status(action)
mock_stdout.flush.assert_called_once_with()
mock_stderr.flush.assert_called_once_with()
mock_signal.assert_called_once_with(signal.SIGINT, signal.SIG_DFL)
mock_kill.assert_called_once_with(os.getpid(), signal.SIGINT)
self.assertEqual(exit_code, 130)
def test_cli_exit_status_forwards_exception_notes(self) -> None:
error = subprocess.CalledProcessError(returncode=1, cmd=("shac", "fmt"))
error.add_note("Note: skipped rebuilding tools because build lock held")
action = mock.MagicMock(side_effect=error)
with mock.patch.object(
sys, "stderr", new_callable=io.StringIO
) as mock_stderr:
exit_code = shac_runner.cli_exit_status(action)
self.assertEqual(exit_code, 1)
self.assertEqual(
mock_stderr.getvalue(),
"Note: skipped rebuilding tools because build lock held\n",
)
if __name__ == "__main__":
unittest.main()