diff --git a/.github/actions/repo-gate/repo_gate.py b/.github/actions/repo-gate/repo_gate.py index 845c01a6f..959079ac7 100755 --- a/.github/actions/repo-gate/repo_gate.py +++ b/.github/actions/repo-gate/repo_gate.py @@ -429,35 +429,103 @@ def single_document(documents: list[object]) -> object: return documents[0] +UVX_READER = ( + "import json, sys, yaml\n" + "def step(item):\n" + " if not isinstance(item, dict):\n" + " return None\n" + " out = {'run': item['run']} if isinstance(item.get('run'), str) else {}\n" + " if item.get('name') and not isinstance(item['name'], (dict, list)):\n" + " out['name'] = str(item['name'])\n" + " if item.get('shell') is not None:\n" + " out['shell'] = item['shell'] if isinstance(item['shell'], str) else ''\n" + " return out\n" + "def project(document):\n" + " if not isinstance(document, dict):\n" + " return None\n" + " runs = document.get('runs')\n" + " steps = runs.get('steps') if isinstance(runs, dict) else None\n" + " if not isinstance(steps, list):\n" + " return {}\n" + " return {'runs': {'steps': [step(item) for item in steps]}}\n" + "try:\n" + " with open(sys.argv[1], encoding='utf-8') as handle:\n" + " text = json.dumps([project(document) for document in yaml.safe_load_all(handle)])\n" + "except Exception as error:\n" + " if isinstance(error, yaml.YAMLError):\n" + " line = f'invalid YAML: {error}'\n" + " else:\n" + " line = f'unreadable: {type(error).__name__}: {error}'\n" + " sys.exit(' '.join(line.split()))\n" + "sys.stdout.write(text)\n" +) +PYYAML_PYTHON: list[str] = [] +ISOLATED = ("-I", "-X", "utf8") + + +class UvxUnavailable(Exception): + """uvx could not provide an interpreter with PyYAML, so no action can be read through it.""" + + +def run_utf8(command: list[str]) -> subprocess.CompletedProcess[str]: + return subprocess.run( + command, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + timeout=YAML_TIMEOUT, + ) + + +def pyyaml_python() -> str: + """An interpreter that imports PyYAML, resolved through uvx once per run.""" + if PYYAML_PYTHON: + return PYYAML_PYTHON[0] + uvx = shutil.which("uvx") + if uvx is None: + raise UvxUnavailable("neither PyYAML nor uvx is available to read the action") + probe = "import sys, yaml; print(sys.executable)" + try: + result = run_utf8([uvx, "--with", "pyyaml", "python", *ISOLATED, "-c", probe]) + except subprocess.TimeoutExpired: + raise UvxUnavailable(f"uvx timed out after {YAML_TIMEOUT}s providing PyYAML") from None + except OSError as error: + raise UvxUnavailable(f"uvx could not start: {error}") from None + if result.returncode != 0 or not result.stdout.strip(): + lines = [line for line in result.stderr.splitlines() if line.strip()] + first = f": {lines[0]}" if lines else "" + raise UvxUnavailable(f"uvx exited {result.returncode} providing PyYAML{first}") + PYYAML_PYTHON.append(result.stdout.strip()) + return PYYAML_PYTHON[0] + + +def load_through_uvx(path: Path) -> list[object]: + """The fields the check reads from each document, parsed by PyYAML in the uvx interpreter.""" + python = pyyaml_python() + try: + result = run_utf8([python, *ISOLATED, "-c", UVX_READER, str(path)]) + except subprocess.TimeoutExpired: + raise ValueError(f"reading timed out after {YAML_TIMEOUT}s") from None + except OSError as error: + raise UvxUnavailable(f"the interpreter uvx provided could not start: {error}") from None + if result.returncode != 0: + lines = [line for line in result.stderr.splitlines() if line.strip()] + raise ValueError(lines[-1] if lines else f"the reader exited {result.returncode}") + documents: list[object] = json.loads(result.stdout) + return documents + + def load_action(path: Path) -> object: - """The one parsed document of an action file, through PyYAML where importable, else yq.""" + """The one parsed document of an action file, through PyYAML on every host. + + PyYAML is used in process where it is importable, and otherwise under uvx, a declared host tool. + """ try: import yaml # type: ignore[import-untyped] except ImportError: - yq = shutil.which("yq") - if yq is None: - raise RuntimeError("neither PyYAML nor yq is available to read the action") from None - result = subprocess.run( - [yq, "-o=json", ".", str(path)], - capture_output=True, - text=True, - encoding="utf-8", - check=False, - timeout=YAML_TIMEOUT, - ) - if result.returncode != 0: - raise ValueError(f"yq could not read the action: {result.stderr.strip()}") - decoder = json.JSONDecoder() - documents: list[object] = [] - text, at = result.stdout, 0 - while True: - while at < len(text) and text[at].isspace(): - at += 1 - if at >= len(text): - break - document, at = decoder.raw_decode(text, at) - documents.append(document) - return single_document(documents) + return single_document(load_through_uvx(path)) try: with path.open(encoding="utf-8") as handle: return single_document(list(yaml.safe_load_all(handle))) @@ -684,8 +752,13 @@ def check_composite_actions(root: Path, files: list[str]) -> list[str]: if unreachable is not None: hits.append(f"{unreachable}, so no run body was shellchecked") else: + PYYAML_PYTHON.clear() for path in actions: - hits.extend(check_composite_shell(root, path)) + try: + hits.extend(check_composite_shell(root, path)) + except UvxUnavailable as error: + hits.append(f"{error}, so no run body was shellchecked") + break hits.extend(check_composite_schema(root, actions)) NOTES.append(f"checked {len(actions)} action file(s).") return hits diff --git a/scripts/README.md b/scripts/README.md index abb6c064e..fc2e06719 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -1,6 +1,6 @@ # Repo Scripts -The fleet's checks and review tooling, run by hand, with the deterministic ones also gating CI. Each one exists because the CI linters pass on the failure it catches: `markdownlint`, `cspell`, `actionlint`, and `editorconfig-checker` all report clean on prose that breaks a documented [`GOVERNANCE.md`][governance] rule. The pre-commit hook runs two deterministic doc gates, each at the scope that fits it. `python3 scripts/prose_lint.py . --diff HEAD` is diff-scoped, at about 0.13 seconds where its whole-tree sweep costs about 2.2. `python3 scripts/repo_gate.py --check eol` is repo-wide, since it reads `.gitattributes` against `.editorconfig` and takes no file list, and at about 0.04 seconds there is nothing to scope. The earlier decision to keep doc linters out was made when a sweep was the only mode, and what reversed it is the diff scope rather than a change of preference. The gates needing Docker, and `sha-pin` which resolves a pin against the GitHub API, stay in CI. A plain `repo_gate.py` run also includes `composite-actions`, which needs Docker and `uvx` or `pipx`. The hook reads the working tree rather than the index, so a partially staged file is judged on all of its edits. The pull request gate reads every line the branch changes against its base. A merge commit is diffed against `MERGE_HEAD` rather than `HEAD`, so the lines the merged-in parent brought are not read as added. +The fleet's checks and review tooling, run by hand, with the deterministic ones also gating CI. Each one exists because the CI linters pass on the failure it catches: `markdownlint`, `cspell`, `actionlint`, and `editorconfig-checker` all report clean on prose that breaks a documented [`GOVERNANCE.md`][governance] rule. The pre-commit hook runs two deterministic doc gates, each at the scope that fits it. `python3 scripts/prose_lint.py . --diff HEAD` is diff-scoped, at about 0.13 seconds where its whole-tree sweep costs about 2.2. `python3 scripts/repo_gate.py --check eol` is repo-wide, since it reads `.gitattributes` against `.editorconfig` and takes no file list, and at about 0.04 seconds there is nothing to scope. The earlier decision to keep doc linters out was made when a sweep was the only mode, and what reversed it is the diff scope rather than a change of preference. The gates needing Docker, and `sha-pin` which resolves a pin against the GitHub API, stay in CI. A plain `repo_gate.py` run also includes `composite-actions`, whose shell half needs Docker and either PyYAML or `uvx`, and whose schema half needs `uvx` or `pipx`. The hook reads the working tree rather than the index, so a partially staged file is judged on all of its edits. The pull request gate reads every line the branch changes against its base. A merge commit is diffed against `MERGE_HEAD` rather than `HEAD`, so the lines the merged-in parent brought are not read as added. **Hosted here and reached, never carried.** These are not declared in [`spec/files.json`][files], so the audit does not expect a downstream repo to ship them, the same footing as `spec/audit.py`. That is the fleet model rather than an omission: a gate holding no per-repo content has one canonical implementation for the fleet. The prose and repository gate implementations live beside their composite actions under `.github/actions/`, which lets reusable workflows reach the implementation at their pinned hub commit through `$/.github/actions/` without checking out the hub. The same-named files in `scripts/` are thin local entry points that call those action-owned implementations, so maintainers and hooks retain the established commands from a hub checkout without creating a second copy of either gate. A repository that cannot reach the hub reports a local check as not run rather than reconstructing it, since a rebuilt gate encodes its author's reading of the rule and agrees with no other repository. @@ -114,7 +114,7 @@ Deterministic checks: - `sha-pin`: every external action or reusable-workflow `uses:` reference is a 40-hex commit SHA, with the documented `dotnet/nbgv@master` exception. References under the scanned repository's owner are also resolved through GitHub. References under another owner are shape-checked only. Local (`./`) and self-repository (`$/`) references name no ref, so they take no pin, and a quoted one is recognized once its quotes are stripped. They resolve differently, though. A `$/` reference and a job-level `./` reusable-workflow call resolve at the calling workflow file's commit, while a `./` action reference resolves against whatever the job checked out, which is the caller's tree where a reusable workflow called from another repository checks out its caller. A reference starting with a bare `.github/` is reported, since GitHub reads it as `owner/repo` rather than as a path. - `eol`: every path pinned LF in [`.gitattributes`][gitattributes] has the matching [`.editorconfig`][editorconfig] override the line-ending rule requires, with EditorConfig brace syntax expanded. One direction only: an `.editorconfig` LF glob with no git pin is legitimate, since `.editorconfig` governs what the editor writes where git enforces a class it must not guess at. - `eol-coverage`: the same pins read against the tree instead. A tracked file opening `#!` that git does not resolve to `eol=lf` is an interpreter line a CRLF checkout breaks, and a pin matching no tracked file is dead unless its block is marked `forward-declared`. -- `composite-actions`: every tracked `action.yml` or `action.yaml` under `.github/actions/`, at any depth, is shellchecked and schema-checked, because actionlint reads workflows only. Each non-empty `run:` body of a bash, sh, or unset-shell step goes to shellcheck. Every `${{ }}` expression is replaced by a placeholder first. A finding names the action file and the step. A pwsh or python step is skipped. The file set goes to `check-jsonschema`'s `vendor.github-actions` builtin through `uvx check-jsonschema@latest`, or `pipx run` where `uvx` is absent. Shellcheck runs from the `koalaman/shellcheck:stable` image, so the check needs Docker. It reads the action through PyYAML or `yq`. Each half reports its own missing tool. Bodies run at warning severity without SC2154, so this is weaker than shellcheck over a `.sh` file. A tree with no action file is skipped with a note. +- `composite-actions`: every tracked `action.yml` or `action.yaml` under `.github/actions/`, at any depth, is shellchecked and schema-checked, because actionlint reads workflows only. Each non-empty `run:` body of a bash, sh, or unset-shell step goes to shellcheck. Every `${{ }}` expression is replaced by a placeholder first. A finding names the action file and the step. A pwsh or python step is skipped. The file set goes to `check-jsonschema`'s `vendor.github-actions` builtin through `uvx check-jsonschema@latest`, or `pipx run` where `uvx` is absent. Shellcheck runs from the `koalaman/shellcheck:stable` image, so the check needs Docker. It reads the action through PyYAML, in process where it is importable and through `uvx --with pyyaml` otherwise. Each half reports its own missing tool. Bodies run at warning severity without SC2154, so this is weaker than shellcheck over a `.sh` file. A tree with no action file is skipped with a note. ```sh python3 scripts/repo_gate.py diff --git a/tests/test_repo_gate.py b/tests/test_repo_gate.py index 94d39b6ef..966afcbc7 100755 --- a/tests/test_repo_gate.py +++ b/tests/test_repo_gate.py @@ -690,9 +690,14 @@ def wrapper(self: unittest.TestCase, *args: object) -> None: NEEDS_SCHEMA = unittest.skipUnless(schema_ready(), "neither uvx nor pipx present") +NEEDS_UVX = unittest.skipUnless(shutil.which("uvx"), "uvx not present") class TestCompositeActions(TreeCase): + def setUp(self) -> None: + super().setUp() + repo_gate.PYYAML_PYTHON.clear() + def action(self, steps: str, name: str = "hook") -> list[str]: folder = self.tmp / ".github" / "actions" / name folder.mkdir(parents=True, exist_ok=True) @@ -1009,48 +1014,220 @@ def test_a_multi_document_file_is_a_finding(self) -> None: hits = self.shell_hits(self.raw("name: a\n---\nname: b\n")) self.assertIn("expected one YAML document, found 2", hits[0]) - def yq_run(self, stdout: str, code: int = 0) -> mock._patch: # type: ignore[type-arg] + def reader_run(self, stdout: str, code: int = 0) -> mock._patch: # type: ignore[type-arg] proc = self.completed(code, stdout, "bad") return mock.patch.object(repo_gate.subprocess, "run", return_value=proc) - def test_yq_reads_the_action_where_pyyaml_is_absent(self) -> None: - payload = '{"runs": {"steps": [{"shell": "bash", "run": "echo $x"}]}}' + def test_the_resolved_interpreter_reads_the_action_where_pyyaml_is_absent(self) -> None: + payload = '[{"runs": {"steps": [{"shell": "bash", "run": "echo $x"}]}}]' with ( mock.patch.dict(sys.modules, {"yaml": None}), - mock.patch.object(repo_gate.shutil, "which", return_value="/usr/bin/yq"), - self.yq_run(payload), + mock.patch.object(repo_gate, "PYYAML_PYTHON", ["/py"]), + self.reader_run(payload) as run, mock.patch.object(repo_gate, "shellcheck_body", return_value=["seen"]) as body, ): hits = repo_gate.check_composite_shell(self.tmp, "a/action.yml") self.assertEqual(["seen"], hits) self.assertEqual("echo $x", body.call_args.args[2]) + self.assertEqual(["/py", "-I", "-X", "utf8", "-c"], run.call_args.args[0][:5]) - def test_yq_and_pyyaml_agree_on_a_multi_document_file(self) -> None: + def test_a_reader_failure_is_a_finding_for_that_file(self) -> None: with ( mock.patch.dict(sys.modules, {"yaml": None}), - mock.patch.object(repo_gate.shutil, "which", return_value="/usr/bin/yq"), - self.yq_run('{"a": 1}\n{"b": 2}\n'), + mock.patch.object(repo_gate, "PYYAML_PYTHON", ["/py"]), + self.reader_run("", 1), ): hits = repo_gate.check_composite_shell(self.tmp, "a/action.yml") - self.assertIn("expected one YAML document, found 2", hits[0]) + self.assertEqual(["a/action.yml: could not read the action: bad"], hits) - def test_a_yq_failure_is_a_finding(self) -> None: + def uvx_hits(self, run: mock.Mock, which: dict[str, str]) -> list[str]: + files = [f for name in "abc" for f in self.action(" - run: echo ok\n", name)] with ( mock.patch.dict(sys.modules, {"yaml": None}), - mock.patch.object(repo_gate.shutil, "which", return_value="/usr/bin/yq"), - self.yq_run("", 1), + mock.patch.object(repo_gate.shutil, "which", side_effect=which.get), + mock.patch.object(repo_gate, "docker_unreachable", return_value=None), + mock.patch.object(repo_gate, "check_composite_schema", return_value=["schema ran"]), + mock.patch.object(repo_gate.subprocess, "run", run), + ): + return repo_gate.check_composite_actions(self.tmp, files) + + def test_uvx_is_probed_once_across_several_files(self) -> None: + run = mock.Mock(side_effect=[self.completed(0, "/py\n")] + [self.completed(0, "[{}]")] * 3) + hits = self.uvx_hits(run, {"docker": "/d", "uvx": "/u"}) + self.assertEqual(["schema ran"], hits) + commands = [call.args[0] for call in run.call_args_list] + self.assertEqual(["/u", "--with", "pyyaml", "python"], commands[0][:4]) + self.assertEqual(["/py"] * 3, [command[0] for command in commands[1:]]) + + def test_no_pyyaml_and_no_uvx_is_one_finding_and_the_schema_still_runs(self) -> None: + hits = self.uvx_hits(mock.Mock(), {"docker": "/d"}) + self.assertEqual(2, len(hits)) + self.assertIn("neither PyYAML nor uvx", hits[0]) + self.assertEqual("schema ran", hits[1]) + + def test_a_probe_timeout_is_one_finding_and_the_schema_still_runs(self) -> None: + run = mock.Mock(side_effect=subprocess.TimeoutExpired(["uvx", "probe"], 60)) + hits = self.uvx_hits(run, {"docker": "/d", "uvx": "/u"}) + self.assertEqual(1, run.call_count) + self.assertEqual(2, len(hits)) + self.assertIn("uvx timed out after", hits[0]) + self.assertEqual("schema ran", hits[1]) + + def test_a_probe_exit_is_one_finding_naming_its_first_line(self) -> None: + run = mock.Mock(return_value=self.completed(2, "", "error: no network\nsecond line\n")) + hits = self.uvx_hits(run, {"docker": "/d", "uvx": "/u"}) + self.assertEqual(1, run.call_count) + self.assertEqual(2, len(hits)) + self.assertIn("uvx exited 2 providing PyYAML: error: no network", hits[0]) + self.assertNotIn("second line", hits[0]) + self.assertEqual("schema ran", hits[1]) + + def test_a_vanished_interpreter_is_one_finding_and_the_schema_still_runs(self) -> None: + gone = FileNotFoundError(2, "No such file or directory", "/gone") + run = mock.Mock(side_effect=[self.completed(0, "/gone\n"), gone]) + hits = self.uvx_hits(run, {"docker": "/d", "uvx": "/u"}) + self.assertEqual(2, run.call_count) + self.assertEqual(2, len(hits)) + self.assertIn("the interpreter uvx provided could not start", hits[0]) + self.assertIn("/gone", hits[0]) + self.assertEqual("schema ran", hits[1]) + + def stub_python(self, body: str) -> str: + stub = self.tmp / "python" + stub.write_text(f"#!/bin/sh\n{body}\n", encoding="utf-8") + stub.chmod(0o755) + return str(stub) + + @unittest.skipUnless(os.name == "posix", "the stub interpreter is a shell script") + def test_child_stderr_is_utf8_and_decoded_leniently(self) -> None: + stub = self.stub_python( + 'printf \'invalid YAML: %s %s %s \\377\\n\' "$1" "$2" "$3" >&2\nexit 1' + ) + with ( + mock.patch.dict(sys.modules, {"yaml": None}), + mock.patch.object(repo_gate, "PYYAML_PYTHON", [stub]), ): hits = repo_gate.check_composite_shell(self.tmp, "a/action.yml") - self.assertIn("yq could not read the action: bad", hits[0]) + self.assertEqual( + ["a/action.yml: could not read the action: invalid YAML: -I -X utf8 \ufffd"], hits + ) - def test_no_pyyaml_and_no_yq_is_a_finding(self) -> None: - files = self.action(" - shell: bash\n run: echo ok\n") + @unittest.skipUnless(os.name == "posix", "the stub interpreter is a shell script") + def test_a_reader_timeout_kills_its_direct_child(self) -> None: + pid_file = self.tmp / "pid" + stub = self.stub_python(f"echo $$ > '{pid_file}'\nexec sleep 30") + with ( + mock.patch.dict(sys.modules, {"yaml": None}), + mock.patch.object(repo_gate, "PYYAML_PYTHON", [stub]), + mock.patch.object(repo_gate, "YAML_TIMEOUT", 1), + ): + hits = repo_gate.check_composite_shell(self.tmp, "a/action.yml") + self.assertEqual( + ["a/action.yml: could not read the action: reading timed out after 1s"], hits + ) + with self.assertRaises(ProcessLookupError): + os.kill(int(pid_file.read_text(encoding="utf-8")), 0) + + def read_from(self, cwd: Path) -> None: + cwd.mkdir(exist_ok=True) + for module in ("yaml", "json", "linecache"): + (cwd / f"{module}.py").write_text("raise SystemExit('shadowed')\n", encoding="utf-8") + files = self.action(" - shell: bash\n run: echo $x\n") + self.addCleanup(os.chdir, os.getcwd()) + os.chdir(cwd) with ( mock.patch.dict(sys.modules, {"yaml": None}), - mock.patch.object(repo_gate.shutil, "which", return_value=None), + mock.patch.object(repo_gate, "shellcheck_body", return_value=[]) as body, ): + self.assertEqual([], self.shell_hits(files)) + self.assertEqual("echo $x", body.call_args.args[2]) + + @NEEDS_UVX + def test_a_module_in_the_checkout_cannot_shadow_the_reader(self) -> None: + self.read_from(self.tmp) + + @NEEDS_UVX + def test_a_module_in_a_shared_working_directory_cannot_shadow_the_reader(self) -> None: + self.read_from(self.tmp / "shared") + + @NEEDS_UVX + def test_a_pythonpath_naming_the_working_directory_cannot_shadow_the_reader(self) -> None: + cwd = self.tmp / "shared" + pythonpath = os.pathsep.join(["", ".", str(cwd)]) + with mock.patch.dict(os.environ, {"PYTHONPATH": pythonpath}): + self.read_from(cwd) + + @NEEDS_UVX + def test_the_real_reader_skips_a_non_string_shell(self) -> None: + files = self.action(" - shell: 5\n run: echo $x\n") + with ( + mock.patch.dict(sys.modules, {"yaml": None}), + mock.patch.object(repo_gate, "shellcheck_body", return_value=[]) as body, + ): + self.assertEqual([], self.shell_hits(files)) + body.assert_not_called() + + @NEEDS_UVX + def test_the_real_reader_labels_a_numeric_name(self) -> None: + files = self.action(" - name: 2024\n shell: bash\n run: echo $x\n") + with ( + mock.patch.dict(sys.modules, {"yaml": None}), + mock.patch.object(repo_gate, "shellcheck_body", return_value=[]) as body, + ): + self.assertEqual([], self.shell_hits(files)) + self.assertEqual(f"{files[0]} step 1 (2024)", body.call_args.args[0]) + + @NEEDS_UVX + def test_the_real_reader_counts_documents_like_pyyaml(self) -> None: + with mock.patch.dict(sys.modules, {"yaml": None}): + hits = self.shell_hits(self.raw("name: a\n---\nname: b\n")) + self.assertEqual(1, len(hits)) + self.assertIn("expected one YAML document, found 2", hits[0]) + + @NEEDS_UVX + def test_uvx_provisions_pyyaml_for_a_real_action(self) -> None: + files = self.action(" - name: Greet\n shell: bash\n run: echo $x\n") + with ( + mock.patch.dict(sys.modules, {"yaml": None}), + mock.patch.object(repo_gate, "shellcheck_body", return_value=[]) as body, + ): + self.assertEqual([], self.shell_hits(files)) + self.assertEqual("echo $x", body.call_args.args[2]) + + @NEEDS_UVX + def test_uvx_reports_invalid_yaml_for_a_real_action(self) -> None: + with mock.patch.dict(sys.modules, {"yaml": None}): + hits = self.shell_hits(self.raw("runs: [unclosed\n")) + self.assertEqual(1, len(hits)) + self.assertIn("could not read the action: invalid YAML:", hits[0]) + self.assertNotIn("\n", hits[0]) + + @NEEDS_UVX + def test_uvx_reads_past_keys_and_aliases_the_check_does_not_use(self) -> None: + nested = "".join( + f"{name}: &{name} [{', '.join([f'*{prior}'] * 9)}]\n" + for prior, name in zip("abcdefgh", "bcdefghi") + ) + files = self.raw( + f"2024-01-01: x\nr: &r [*r]\na: &a [{', '.join(['x'] * 9)}]\n{nested}" + "runs:\n steps:\n - name: *i\n shell: bash\n run: echo $x\n" + ) + with ( + mock.patch.dict(sys.modules, {"yaml": None}), + mock.patch.object(repo_gate, "shellcheck_body", return_value=[]) as body, + ): + self.assertEqual([], self.shell_hits(files)) + self.assertEqual("echo $x", body.call_args.args[2]) + + @NEEDS_UVX + def test_uvx_reports_a_non_utf8_file_in_one_line(self) -> None: + files = self.raw("") + (self.tmp / files[0]).write_bytes(b"name: \xff\n") + with mock.patch.dict(sys.modules, {"yaml": None}): hits = self.shell_hits(files) - self.assertIn("neither PyYAML nor yq", hits[0]) + self.assertEqual(1, len(hits)) + self.assertIn("could not read the action: unreadable: UnicodeDecodeError", hits[0]) + self.assertNotIn("\n", hits[0]) @NEEDS_SCHEMA def test_a_valid_action_passes_the_schema(self) -> None: