From 5eefcdd4e1c6ac8bc3d4cc348ee3c712ae0bc3cf Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 15:24:01 -0500 Subject: [PATCH 01/14] ci: run the bats suites on pull requests and pushes to main Add .github/workflows/tests.yml. The pull_request trigger has no branch filter, so pull requests into any base branch run the suites; pushes to main run them too. One matrix job per suite installs Nix and runs `nix develop -c bats ` through the repository flake, with fail-fast off so each suite reports on its own. Actions are pinned to full commit SHAs with the release tag in a trailing comment. Add tests/ci-workflow.bats, which checks the triggers, the SHA pins and that the workflow matrix matches the suites under "Running Tests" in docs/development.md, and list it there. Refs #40 --- .github/workflows/tests.yml | 45 ++++++++++++++++ docs/development.md | 1 + tests/ci-workflow.bats | 103 ++++++++++++++++++++++++++++++++++++ 3 files changed, 149 insertions(+) create mode 100644 .github/workflows/tests.yml create mode 100644 tests/ci-workflow.bats diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..8bfe8c5 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,45 @@ +name: Tests + +# Runs every bats suite listed under "Running Tests" in docs/development.md. +# Adding a suite means adding it to both that list and the matrix below; +# tests/ci-workflow.bats fails when they differ. + +on: + # No branch filter: pull requests into any base branch run the suites. + pull_request: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + bats: + name: bats ${{ matrix.suite }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + suite: + - tests/marketplace-package.bats + - tests/ci-workflow.bats + - plugins/product-development/tests/plugin-package.bats + - plugins/product-development/skills/product-development/tests/init.bats + - plugins/delivery-engineering/tests/plugin-package.bats + - plugins/okf-bundle/tests/plugin-package.bats + - plugins/branch-guard/tests + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: cachix/install-nix-action@382a9ed9481c7c1f94f68b72ef105b3417c73877 # v32.1.0 + with: + github_access_token: ${{ secrets.GITHUB_TOKEN }} + - name: Run suite + env: + SUITE: ${{ matrix.suite }} + run: nix develop -c bats "$SUITE" diff --git a/docs/development.md b/docs/development.md index 7414e4a..0c96c7f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -128,6 +128,7 @@ should reflect the target project's domain. ```bash nix develop -c bats tests/marketplace-package.bats +nix develop -c bats tests/ci-workflow.bats nix develop -c bats plugins/product-development/tests/plugin-package.bats nix develop -c bats plugins/product-development/skills/product-development/tests/init.bats nix develop -c bats plugins/delivery-engineering/tests/plugin-package.bats diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats new file mode 100644 index 0000000..73261d6 --- /dev/null +++ b/tests/ci-workflow.bats @@ -0,0 +1,103 @@ +#!/usr/bin/env bats + +REPO_ROOT="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)" +WORKFLOW="$REPO_ROOT/.github/workflows/tests.yml" +DEV_DOC="$REPO_ROOT/docs/development.md" + +# Runs a Python snippet against the parsed workflow, bound to `workflow`. +# PyYAML reads the bare `on` key as boolean true, so `triggers` is provided. +workflow_py() { + python3 - "$WORKFLOW" "$1" <<'PY' +import sys +import yaml + +with open(sys.argv[1], encoding="utf-8") as handle: + workflow = yaml.safe_load(handle) +triggers = workflow.get("on", workflow.get(True)) +exec(sys.argv[2]) +PY +} + +# Prints the bats suite paths from the "Running Tests" block of +# docs/development.md, one per line, sorted. +documented_suites() { + awk ' + /^## Running Tests/ { in_section = 1; next } + in_section && /^## / { exit } + in_section && /^```/ { in_block = !in_block; next } + in_section && in_block && /^nix develop -c bats / { print $5 } + ' "$DEV_DOC" | sort +} + +# Prints the suite paths from the workflow matrix, one per line, sorted. +workflow_suites() { + workflow_py ' +for job in workflow["jobs"].values(): + for suite in job.get("strategy", {}).get("matrix", {}).get("suite", []): + print(suite) +' | sort +} + +@test "workflow file exists" { + [ -f "$WORKFLOW" ] +} + +@test "pull_request trigger has no branch or path filter" { + run workflow_py ' +pr = triggers["pull_request"] if "pull_request" in triggers else sys.exit("no pull_request trigger") +filters = sorted(set(pr or {}) & {"branches", "branches-ignore", "paths", "paths-ignore"}) +if filters: + sys.exit("pull_request has filters: " + ", ".join(filters)) +' + [ "$status" -eq 0 ] || { echo "$output" >&2; return 1; } +} + +@test "push trigger runs on main" { + run workflow_py ' +push = triggers.get("push") or sys.exit("no push trigger") +if push.get("branches") != ["main"]: + sys.exit("push branches are %r, expected [main]" % push.get("branches")) +' + [ "$status" -eq 0 ] || { echo "$output" >&2; return 1; } +} + +@test "documented suites are found" { + run documented_suites + [ "$status" -eq 0 ] + [ -n "$output" ] || { echo "no suites found under Running Tests" >&2; return 1; } +} + +@test "workflow runs exactly the suites listed in docs/development.md" { + run diff <(documented_suites) <(workflow_suites) + [ "$status" -eq 0 ] || { + echo "suites differ (< docs, > workflow):" >&2 + echo "$output" >&2 + return 1 + } +} + +@test "each suite job runs bats through the flake dev shell" { + run workflow_py ' +for name, job in workflow["jobs"].items(): + if "suite" not in job.get("strategy", {}).get("matrix", {}): + continue + commands = " ".join(step.get("run", "") for step in job["steps"]) + if "nix develop -c bats" not in commands: + sys.exit("job %s does not run nix develop -c bats" % name) + if job["strategy"].get("fail-fast", True): + sys.exit("job %s must set fail-fast: false so every suite reports" % name) +' + [ "$status" -eq 0 ] || { echo "$output" >&2; return 1; } +} + +@test "third-party actions are pinned to full commit SHAs with a version comment" { + run grep -nE '^[[:space:]]*-?[[:space:]]*uses:' "$WORKFLOW" + [ "$status" -eq 0 ] || { echo "no uses: lines found" >&2; return 1; } + local unpinned + unpinned="$(printf '%s\n' "$output" | grep -vE 'uses: [^@[:space:]]+@[0-9a-f]{40} # v[0-9][^[:space:]]*$' || true)" + [ -z "$unpinned" ] || { + echo "actions not pinned to a SHA with a # vX comment:" >&2 + echo "$unpinned" >&2 + return 1 + } +} From a36ba40aaef17dae878dccf8098d59360e9ee319 Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 15:25:20 -0500 Subject: [PATCH 02/14] docs: describe the CI workflow and the rule for adding suites Add a "Continuous Integration" subsection under "Running Tests" in docs/development.md. It names .github/workflows/tests.yml, says when it runs and how each suite runs through the flake, and states that a new suite is added to both the documented list and the workflow matrix, which tests/ci-workflow.bats enforces. It also covers updating the SHA-pinned actions. Add the workflow and the new suite to the repository structure tree. Refs #40 --- docs/development.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/docs/development.md b/docs/development.md index 0c96c7f..5eb65d3 100644 --- a/docs/development.md +++ b/docs/development.md @@ -137,6 +137,21 @@ nix develop -c bats plugins/branch-guard/tests git diff --check ``` +### Continuous Integration + +`.github/workflows/tests.yml` runs every bats suite above on each pull request, +whatever its base branch, and on each push to `main`. It installs Nix and runs +each suite in its own job with the same `nix develop -c bats ` command, +so CI uses the flake's pinned tool versions and a failing job names its suite. +`git diff --check` runs locally only. + +When you add a suite, add it to both the list above and the `suite` matrix in +the workflow. `tests/ci-workflow.bats` fails when the two differ. + +Third-party actions in the workflow are pinned to full commit SHAs, with the +release tag in a trailing comment. To update one, look up the new release's +commit with `gh api repos///commits/ --jq .sha`. + ## Repository Structure ```text @@ -145,8 +160,11 @@ agent-plugins/ ├── .agents/plugins/marketplace.json ├── .claude-plugin/marketplace.json ├── .github/plugin/marketplace.json +├── .github/workflows/tests.yml ├── docs/ -├── tests/marketplace-package.bats +├── tests/ +│ ├── ci-workflow.bats +│ └── marketplace-package.bats └── plugins/ ├── product-development/ │ ├── plugin.json From 4451871f5877e1c1e65d83e9dac1f5bad78dbf9f Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 15:33:09 -0500 Subject: [PATCH 03/14] test(ci): parse the Running Tests block strictly in the workflow guard The guard read documented suites with a column-one awk pattern, so an indented `nix develop -c bats` line in the docs block was skipped and a suite missing from the workflow matrix went unnoticed. It also compared the lists with diff over process substitution, which hid a parser failure. Add tests/ci-workflow-check.py, a PyYAML checker run by tests/ci-workflow.bats. Its suites check reads the single code block under "Running Tests", strips indentation, accepts only `nix develop -c bats ` lines and `git diff --check`, and rejects any other command by name. It compares the documented and matrix lists in Python, reports missing, extra, duplicate and nonexistent suites, and exits 1 on any problem, including a missing section or block. New bats tests run the check on broken copies of the docs and workflow and assert each one is rejected with the expected message. Refs #40 --- docs/development.md | 5 +- tests/ci-workflow-check.py | 154 +++++++++++++++++++++++++++++++++++++ tests/ci-workflow.bats | 112 ++++++++++++++++++++------- 3 files changed, 243 insertions(+), 28 deletions(-) create mode 100755 tests/ci-workflow-check.py diff --git a/docs/development.md b/docs/development.md index 5eb65d3..07ad34b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -146,7 +146,9 @@ so CI uses the flake's pinned tool versions and a failing job names its suite. `git diff --check` runs locally only. When you add a suite, add it to both the list above and the `suite` matrix in -the workflow. `tests/ci-workflow.bats` fails when the two differ. +the workflow. `tests/ci-workflow.bats` fails when the two differ, and when the +block holds a command other than `nix develop -c bats ` or +`git diff --check`. Its checks live in `tests/ci-workflow-check.py`. Third-party actions in the workflow are pinned to full commit SHAs, with the release tag in a trailing comment. To update one, look up the new release's @@ -163,6 +165,7 @@ agent-plugins/ ├── .github/workflows/tests.yml ├── docs/ ├── tests/ +│ ├── ci-workflow-check.py │ ├── ci-workflow.bats │ └── marketplace-package.bats └── plugins/ diff --git a/tests/ci-workflow-check.py b/tests/ci-workflow-check.py new file mode 100755 index 0000000..65c412f --- /dev/null +++ b/tests/ci-workflow-check.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Checks .github/workflows/tests.yml against docs/development.md. + +Usage: ci-workflow-check.py [--workflow PATH] [--doc PATH] + +Each check prints one line per problem and exits 1 when it finds any. +A check function takes the parsed workflow and the parsed arguments. +tests/ci-workflow.bats runs every check against the real files and +against broken copies. +""" + +import argparse +import pathlib +import re +import sys + +import yaml + +REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent + +# Commands allowed in the "Running Tests" block that are not bats suites. +NON_SUITE_COMMANDS = {"git diff --check"} + +SUITE_COMMAND = re.compile(r"nix develop -c bats (\S+)") + + +class CheckFailed(Exception): + pass + + +def load_workflow(path): + with open(path, encoding="utf-8") as handle: + return yaml.safe_load(handle) + + +def suite_jobs(workflow): + """Returns (name, job) for each job with a `suite` matrix.""" + jobs = [ + (name, job) + for name, job in (workflow.get("jobs") or {}).items() + if "suite" in ((job.get("strategy") or {}).get("matrix") or {}) + ] + if not jobs: + raise CheckFailed("no job has a strategy.matrix.suite list") + return jobs + + +def documented_suites(doc_path): + """Returns the suite paths in the "Running Tests" block, in order. + + The section runs from "## Running Tests" to the next level-2 heading + and must hold exactly one fenced block. Every command in it must be a + `nix develop -c bats ` line or one of NON_SUITE_COMMANDS. + """ + lines = pathlib.Path(doc_path).read_text(encoding="utf-8").splitlines() + try: + start = next(i for i, line in enumerate(lines) if line.strip() == "## Running Tests") + except StopIteration: + raise CheckFailed("%s has no '## Running Tests' section" % doc_path) + + section = [] + for line in lines[start + 1 :]: + if re.match(r"##\s", line): + break + section.append(line) + + blocks, block = [], None + for line in section: + if line.strip().startswith("```"): + if block is None: + block = [] + else: + blocks.append(block) + block = None + elif block is not None: + block.append(line) + if block is not None: + raise CheckFailed("Running Tests has an unclosed code fence") + if len(blocks) != 1: + raise CheckFailed("Running Tests must hold exactly one code block, found %d" % len(blocks)) + + suites, problems = [], [] + for raw in blocks[0]: + command = raw.strip() + if not command or command.startswith("#"): + continue + match = SUITE_COMMAND.fullmatch(command) + if match: + suites.append(match.group(1)) + elif command not in NON_SUITE_COMMANDS: + problems.append( + "unrecognized command in Running Tests: %r (list a suite as " + "'nix develop -c bats ', or add the command to " + "NON_SUITE_COMMANDS in tests/ci-workflow-check.py)" % command + ) + if problems: + raise CheckFailed("\n".join(problems)) + if not suites: + raise CheckFailed("Running Tests lists no suites") + return suites + + +def duplicates(items): + return sorted({item for item in items if items.count(item) > 1}) + + +def check_suites(workflow, args): + documented = documented_suites(args.doc) + matrix = [] + for name, job in suite_jobs(workflow): + suites = job["strategy"]["matrix"]["suite"] + if not isinstance(suites, list) or not all(isinstance(s, str) for s in suites): + raise CheckFailed("job %s: matrix.suite must be a list of paths" % name) + matrix.extend(suites) + + problems = [] + for suite in duplicates(documented): + problems.append("listed twice in docs: %s" % suite) + for suite in duplicates(matrix): + problems.append("listed twice in the workflow matrix: %s" % suite) + for suite in documented: + if suite not in matrix: + problems.append("in docs but not in the workflow matrix: %s" % suite) + if not (REPO_ROOT / suite).exists(): + problems.append("documented suite does not exist: %s" % suite) + for suite in matrix: + if suite not in documented: + problems.append("in the workflow matrix but not in docs: %s" % suite) + return problems + + +CHECKS = { + "suites": check_suites, +} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("check", choices=sorted(CHECKS)) + parser.add_argument("--workflow", default=REPO_ROOT / ".github/workflows/tests.yml") + parser.add_argument("--doc", default=REPO_ROOT / "docs/development.md") + args = parser.parse_args() + + try: + problems = CHECKS[args.check](load_workflow(args.workflow), args) + except CheckFailed as failure: + problems = [str(failure)] + for problem in problems: + print(problem) + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats index 73261d6..95a45e9 100644 --- a/tests/ci-workflow.bats +++ b/tests/ci-workflow.bats @@ -3,6 +3,7 @@ REPO_ROOT="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)" WORKFLOW="$REPO_ROOT/.github/workflows/tests.yml" DEV_DOC="$REPO_ROOT/docs/development.md" +CHECK="$REPO_ROOT/tests/ci-workflow-check.py" # Runs a Python snippet against the parsed workflow, bound to `workflow`. # PyYAML reads the bare `on` key as boolean true, so `triggers` is provided. @@ -18,24 +19,48 @@ exec(sys.argv[2]) PY } -# Prints the bats suite paths from the "Running Tests" block of -# docs/development.md, one per line, sorted. -documented_suites() { - awk ' - /^## Running Tests/ { in_section = 1; next } - in_section && /^## / { exit } - in_section && /^```/ { in_block = !in_block; next } - in_section && in_block && /^nix develop -c bats / { print $5 } - ' "$DEV_DOC" | sort +# Runs one check from tests/ci-workflow-check.py. Optional second and +# third arguments replace the workflow and docs paths. +check() { + python3 "$CHECK" "$1" --workflow "${2:-$WORKFLOW}" --doc "${3:-$DEV_DOC}" } -# Prints the suite paths from the workflow matrix, one per line, sorted. -workflow_suites() { - workflow_py ' -for job in workflow["jobs"].values(): - for suite in job.get("strategy", {}).get("matrix", {}).get("suite", []): - print(suite) -' | sort +# Copies to $BATS_TEST_TMPDIR/ with the first +# replaced by , and prints the copy's path. Fails when is +# absent, so a stale fixture cannot pass silently. +broken_copy() { + python3 - "$1" "$BATS_TEST_TMPDIR/$2" "$3" "$4" <<'PY' +import sys + +source, target, old, new = sys.argv[1:] +with open(source, encoding="utf-8") as handle: + text = handle.read() +if old not in text: + sys.exit("broken_copy: text not found in %s: %r" % (source, old)) +with open(target, "w", encoding="utf-8") as handle: + handle.write(text.replace(old, new, 1)) +print(target) +PY +} + +# Passes when the check passes; prints its output otherwise. +assert_check_passes() { + run check "$@" + [ "$status" -eq 0 ] || { echo "$output" >&2; return 1; } +} + +# Passes when the check exits 1 with output containing . +# Usage: assert_check_rejects [workflow] [doc] +assert_check_rejects() { + local expected="$1" + shift + run check "$@" + [ "$status" -eq 1 ] || { echo "check $1 exited $status, expected 1: $output" >&2; return 1; } + [[ "$output" == *"$expected"* ]] || { + echo "check $1 failed without mentioning '$expected':" >&2 + echo "$output" >&2 + return 1 + } } @test "workflow file exists" { @@ -61,19 +86,52 @@ if push.get("branches") != ["main"]: [ "$status" -eq 0 ] || { echo "$output" >&2; return 1; } } -@test "documented suites are found" { - run documented_suites - [ "$status" -eq 0 ] - [ -n "$output" ] || { echo "no suites found under Running Tests" >&2; return 1; } +@test "workflow runs exactly the suites listed in docs/development.md" { + assert_check_passes suites +} + +@test "suites check rejects a documented suite missing from the matrix" { + local doc + doc="$(broken_copy "$DEV_DOC" development.md \ + "nix develop -c bats tests/ci-workflow.bats" \ + "nix develop -c bats tests/ci-workflow.bats +nix develop -c bats tests/missing.bats")" + assert_check_rejects "in docs but not in the workflow matrix: tests/missing.bats" \ + suites "$WORKFLOW" "$doc" } -@test "workflow runs exactly the suites listed in docs/development.md" { - run diff <(documented_suites) <(workflow_suites) - [ "$status" -eq 0 ] || { - echo "suites differ (< docs, > workflow):" >&2 - echo "$output" >&2 - return 1 - } +@test "suites check reads indented suite lines in the docs block" { + local doc + doc="$(broken_copy "$DEV_DOC" development.md \ + "nix develop -c bats tests/ci-workflow.bats" \ + "nix develop -c bats tests/ci-workflow.bats + nix develop -c bats tests/indented.bats")" + assert_check_rejects "in docs but not in the workflow matrix: tests/indented.bats" \ + suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects an unrecognized command in the docs block" { + local doc + doc="$(broken_copy "$DEV_DOC" development.md \ + "nix develop -c bats tests/ci-workflow.bats" \ + "nix develop --command bats tests/ci-workflow.bats")" + assert_check_rejects "unrecognized command in Running Tests" suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects a matrix suite missing from docs" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml \ + " - tests/ci-workflow.bats" \ + " - tests/ci-workflow.bats + - tests/undocumented.bats")" + assert_check_rejects "in the workflow matrix but not in docs: tests/undocumented.bats" \ + suites "$workflow" +} + +@test "suites check fails when docs have no Running Tests section" { + local doc + doc="$(broken_copy "$DEV_DOC" development.md "## Running Tests" "## Tests")" + assert_check_rejects "no '## Running Tests' section" suites "$WORKFLOW" "$doc" } @test "each suite job runs bats through the flake dev shell" { From 6524e686b8ce8ca309bbbd5ea3d85f62b0690558 Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 15:34:23 -0500 Subject: [PATCH 04/14] ci: give each push to main its own concurrency group All runs for a ref shared one concurrency group. Push runs did not cancel in progress, but a group holds one pending run, so with push A running and push B queued, push C replaced B and B never ran. Key the group by github.run_id for pushes and by github.ref for pull requests, keeping cancel-in-progress for pull requests so a new commit cancels the superseded run. Add a concurrency check to tests/ci-workflow-check.py. It evaluates the group and cancel-in-progress expressions with a small GitHub Actions expression evaluator for simulated push and pull request runs, and fails when two pushes share a group, when commits on one pull request get different groups or do not cancel, or when pull requests share a group with each other or with pushes. Note the behaviour in docs/development.md. Refs #40 --- .github/workflows/tests.yml | 5 +- docs/development.md | 4 +- tests/ci-workflow-check.py | 134 ++++++++++++++++++++++++++++++++++++ tests/ci-workflow.bats | 28 ++++++++ 4 files changed, 169 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 8bfe8c5..caa8e18 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -13,8 +13,11 @@ on: permissions: contents: read +# Runs for one pull request share a group, so a new commit cancels the +# superseded run. Each push to main gets its own group, keyed by run ID: in a +# shared group, a later push would cancel a push run still waiting in the queue. concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: diff --git a/docs/development.md b/docs/development.md index 07ad34b..3c56ca2 100644 --- a/docs/development.md +++ b/docs/development.md @@ -143,7 +143,9 @@ git diff --check whatever its base branch, and on each push to `main`. It installs Nix and runs each suite in its own job with the same `nix develop -c bats ` command, so CI uses the flake's pinned tool versions and a failing job names its suite. -`git diff --check` runs locally only. +`git diff --check` runs locally only. A new commit on a pull request cancels +that pull request's running checks; runs for pushes to `main` never cancel or +replace each other. When you add a suite, add it to both the list above and the `suite` matrix in the workflow. `tests/ci-workflow.bats` fails when the two differ, and when the diff --git a/tests/ci-workflow-check.py b/tests/ci-workflow-check.py index 65c412f..dac92b5 100755 --- a/tests/ci-workflow-check.py +++ b/tests/ci-workflow-check.py @@ -129,7 +129,141 @@ def check_suites(workflow, args): return problems +# A minimal evaluator for GitHub Actions expressions: string literals, +# true/false/null, dotted context names, !, ==, !=, && and ||, and +# parentheses. Enough to evaluate the concurrency settings. +EXPRESSION_TOKEN = re.compile(r"\s*(?:(==|!=|&&|\|\||!|\(|\))|'((?:[^']|'')*)'|([A-Za-z_][\w.-]*))") + + +def evaluate(expression, context): + tokens, position = [], 0 + expression = expression.strip() + while position < len(expression): + match = EXPRESSION_TOKEN.match(expression, position) + if not match or match.end() == position: + raise CheckFailed("cannot parse expression: %r" % expression) + operator, string, name = match.groups() + if operator: + tokens.append(("op", operator)) + elif string is not None: + tokens.append(("value", string.replace("''", "'"))) + else: + literals = {"true": True, "false": False, "null": None} + if name in literals: + tokens.append(("value", literals[name])) + else: + value = context + for part in name.split("."): + value = value.get(part) if isinstance(value, dict) else None + tokens.append(("value", value)) + position = match.end() + + def peek(): + return tokens[0] if tokens else (None, None) + + def take(operator): + if peek() == ("op", operator): + tokens.pop(0) + return True + return False + + def parse_or(): + left = parse_and() + while take("||"): + right = parse_and() + left = left if left else right + return left + + def parse_and(): + left = parse_equality() + while take("&&"): + right = parse_equality() + left = right if left else left + return left + + def parse_equality(): + left = parse_unary() + if take("=="): + return left == parse_unary() + if take("!="): + return left != parse_unary() + return left + + def parse_unary(): + if take("!"): + return not parse_unary() + if take("("): + value = parse_or() + if not take(")"): + raise CheckFailed("unbalanced parentheses: %r" % expression) + return value + kind, value = tokens.pop(0) if tokens else (None, None) + if kind != "value": + raise CheckFailed("unexpected token in expression: %r" % expression) + return value + + value = parse_or() + if tokens: + raise CheckFailed("trailing tokens in expression: %r" % expression) + return value + + +def render(value, context): + """Evaluates a workflow value that may hold ${{ }} expressions.""" + if not isinstance(value, str): + return value + whole = re.fullmatch(r"\$\{\{(.*)\}\}", value.strip(), re.S) + if whole and "}}" not in whole.group(1): + return evaluate(whole.group(1), context) + + def text(match): + result = evaluate(match.group(1), context) + if result is None: + return "" + if isinstance(result, bool): + return "true" if result else "false" + return str(result) + + return re.sub(r"\$\{\{(.*?)\}\}", text, value) + + +def check_concurrency(workflow, args): + """Simulates runs to check which ones share a group and cancel. + + Each push to main must get its own group: in a shared group, a third + push cancels a queued second one. Commits on one pull request share a + group with cancel-in-progress, so a new commit replaces the old run. + """ + concurrency = workflow.get("concurrency") + if not isinstance(concurrency, dict) or "group" not in concurrency: + raise CheckFailed("workflow must set concurrency.group") + + def run(event, ref, run_id): + context = {"github": {"workflow": workflow.get("name", ""), "event_name": event, "ref": ref, "run_id": run_id}} + group = render(concurrency["group"], context) + cancel = render(concurrency.get("cancel-in-progress", False), context) + return str(group), cancel in (True, "true") + + push_a, push_b = run("push", "refs/heads/main", "101"), run("push", "refs/heads/main", "102") + pr_a, pr_b = run("pull_request", "refs/pull/7/merge", "103"), run("pull_request", "refs/pull/7/merge", "104") + other_pr = run("pull_request", "refs/pull/8/merge", "105") + + problems = [] + if push_a[0] == push_b[0]: + problems.append("two pushes to main share concurrency group %r; a queued push run can be canceled" % push_a[0]) + if pr_a[0] != pr_b[0]: + problems.append("commits on one pull request get different groups (%r, %r); superseded runs are not canceled" % (pr_a[0], pr_b[0])) + if not pr_a[1]: + problems.append("pull request runs must set cancel-in-progress") + if pr_a[0] == other_pr[0]: + problems.append("different pull requests share concurrency group %r" % pr_a[0]) + if pr_a[0] in (push_a[0], push_b[0]): + problems.append("a pull request run shares a group with a push run: %r" % pr_a[0]) + return problems + + CHECKS = { + "concurrency": check_concurrency, "suites": check_suites, } diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats index 95a45e9..2487191 100644 --- a/tests/ci-workflow.bats +++ b/tests/ci-workflow.bats @@ -86,6 +86,34 @@ if push.get("branches") != ["main"]: [ "$status" -eq 0 ] || { echo "$output" >&2; return 1; } } +@test "push runs never cancel each other; pull request runs cancel superseded ones" { + assert_check_passes concurrency +} + +@test "concurrency check rejects one group shared by all pushes to main" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml \ + "github.event_name == 'pull_request' && github.ref || github.run_id" \ + "github.ref")" + assert_check_rejects "two pushes to main share concurrency group" concurrency "$workflow" +} + +@test "concurrency check rejects pull request runs that do not cancel" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml \ + "cancel-in-progress: \${{ github.event_name == 'pull_request' }}" \ + "cancel-in-progress: false")" + assert_check_rejects "pull request runs must set cancel-in-progress" concurrency "$workflow" +} + +@test "concurrency check rejects a group per pull request commit" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml \ + "github.event_name == 'pull_request' && github.ref || github.run_id" \ + "github.run_id")" + assert_check_rejects "commits on one pull request get different groups" concurrency "$workflow" +} + @test "workflow runs exactly the suites listed in docs/development.md" { assert_check_passes suites } From 254194c16fb6323d90c2d2832b2eca01fba0d095 Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 15:35:08 -0500 Subject: [PATCH 05/14] test(ci): require every matrix suite to run and fail the job on failure The guard only checked that some step mentioned `nix develop -c bats`, so a suite dropped through matrix.exclude, a hardcoded suite path in the run step, `|| true`, or continue-on-error all passed while a documented suite never ran or never failed CI. Add a matrix check to tests/ci-workflow-check.py, replacing the inline bats check. The matrix may define only `suite`, fail-fast must be false, exactly one step may run bats, and its command must be `nix develop -c bats` with the matrix suite (directly or through an env variable bound to it) and nothing else. No job or step may set continue-on-error, and the job and bats step may not set `if`. Bats tests run the check on broken copies for each of those cases. Refs #40 --- tests/ci-workflow-check.py | 56 ++++++++++++++++++++++++++++++ tests/ci-workflow.bats | 70 +++++++++++++++++++++++++++++++------- 2 files changed, 114 insertions(+), 12 deletions(-) diff --git a/tests/ci-workflow-check.py b/tests/ci-workflow-check.py index dac92b5..7f4aa2e 100755 --- a/tests/ci-workflow-check.py +++ b/tests/ci-workflow-check.py @@ -262,8 +262,64 @@ def run(event, ref, run_id): return problems +MATRIX_SUITE = re.compile(r"\$\{\{\s*matrix\.suite\s*\}\}") + + +def check_matrix(workflow, args): + """Checks that every matrix suite runs and that its failure fails CI. + + The matrix may hold only the `suite` list (no include or exclude), the + job must not use fail-fast, and one step must run + `nix develop -c bats ` with nothing else on the line. No + job or step may set continue-on-error or an `if` condition. + """ + problems = [] + for name, job in suite_jobs(workflow): + strategy = job["strategy"] + extra = sorted(set(strategy["matrix"]) - {"suite"}) + if extra: + problems.append("job %s: matrix may only define suite, found %s" % (name, ", ".join(extra))) + if strategy.get("fail-fast", True) is not False: + problems.append("job %s must set fail-fast: false so every suite reports" % name) + if job.get("continue-on-error", False) is not False: + problems.append("job %s must not set continue-on-error" % name) + if "if" in job: + problems.append("job %s must not set an if condition" % name) + + # Environment variables bound to ${{ matrix.suite }}, step or job level. + def suite_vars(env): + return {key for key, value in (env or {}).items() if MATRIX_SUITE.fullmatch(str(value).strip())} + + job_vars = suite_vars(job.get("env")) + bats_steps = [] + for index, step in enumerate(job.get("steps") or []): + label = step.get("name") or step.get("uses") or "step %d" % (index + 1) + if step.get("continue-on-error", False) is not False: + problems.append("job %s, %s: must not set continue-on-error" % (name, label)) + if "bats" in str(step.get("run", "")): + bats_steps.append((label, step)) + if len(bats_steps) != 1: + problems.append("job %s must have exactly one step that runs bats, found %d" % (name, len(bats_steps))) + continue + + label, step = bats_steps[0] + if "if" in step: + problems.append("job %s, %s: must not set an if condition" % (name, label)) + variables = job_vars | suite_vars(step.get("env")) + suite_args = [r"\$\{\{\s*matrix\.suite\s*\}\}"] + [r"\$\{?%s\}?" % re.escape(var) for var in variables] + pattern = r'nix develop -c bats (?:"(?:%s)"|(?:%s))' % ("|".join(suite_args), "|".join(suite_args)) + command = str(step["run"]).strip() + if not re.fullmatch(pattern, command): + problems.append( + "job %s, %s: must run exactly 'nix develop -c bats \"$SUITE\"' with SUITE set to " + "${{ matrix.suite }}, found %r" % (name, label, command) + ) + return problems + + CHECKS = { "concurrency": check_concurrency, + "matrix": check_matrix, "suites": check_suites, } diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats index 2487191..aed7c13 100644 --- a/tests/ci-workflow.bats +++ b/tests/ci-workflow.bats @@ -162,18 +162,64 @@ nix develop -c bats tests/missing.bats")" assert_check_rejects "no '## Running Tests' section" suites "$WORKFLOW" "$doc" } -@test "each suite job runs bats through the flake dev shell" { - run workflow_py ' -for name, job in workflow["jobs"].items(): - if "suite" not in job.get("strategy", {}).get("matrix", {}): - continue - commands = " ".join(step.get("run", "") for step in job["steps"]) - if "nix develop -c bats" not in commands: - sys.exit("job %s does not run nix develop -c bats" % name) - if job["strategy"].get("fail-fast", True): - sys.exit("job %s must set fail-fast: false so every suite reports" % name) -' - [ "$status" -eq 0 ] || { echo "$output" >&2; return 1; } +@test "each matrix suite runs through the flake dev shell and can fail the job" { + assert_check_passes matrix +} + +@test "matrix check rejects a suite dropped by matrix.exclude" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml \ + " - plugins/branch-guard/tests +" \ + " - plugins/branch-guard/tests + exclude: + - suite: plugins/branch-guard/tests +")" + assert_check_rejects "matrix may only define suite" matrix "$workflow" +} + +@test "matrix check rejects a hardcoded suite path in the run step" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml \ + 'run: nix develop -c bats "$SUITE"' \ + 'run: nix develop -c bats tests/ci-workflow.bats')" + assert_check_rejects "must run exactly" matrix "$workflow" +} + +@test "matrix check rejects a run step that swallows failures" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml \ + 'run: nix develop -c bats "$SUITE"' \ + 'run: nix develop -c bats "$SUITE" || true')" + assert_check_rejects "must run exactly" matrix "$workflow" +} + +@test "matrix check rejects continue-on-error on the suite job" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml \ + " runs-on: ubuntu-latest +" \ + " runs-on: ubuntu-latest + continue-on-error: true +")" + assert_check_rejects "continue-on-error" matrix "$workflow" +} + +@test "matrix check rejects continue-on-error on the run step" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml \ + " - name: Run suite +" \ + " - name: Run suite + continue-on-error: true +")" + assert_check_rejects "continue-on-error" matrix "$workflow" +} + +@test "matrix check rejects fail-fast" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml "fail-fast: false" "fail-fast: true")" + assert_check_rejects "fail-fast: false" matrix "$workflow" } @test "third-party actions are pinned to full commit SHAs with a version comment" { From 375fd758772f4f4a718ddf006c06741b2d06f39e Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 15:35:59 -0500 Subject: [PATCH 06/14] test(ci): require the default pull_request activity types The trigger check looked only for branch and path filters, so `types: [opened]` passed even though pushes to an open pull request would no longer run the suites. Add a triggers check to tests/ci-workflow-check.py, replacing the inline bats checks. pull_request must have no branch or path filter and, when it lists types, must include opened, reopened and synchronize. push must run on main only, with no path filter. String and list forms of `on` are normalized first. Bats tests cover a branch filter, `types: [opened]`, explicit types that include the defaults, a push on another branch and a push path filter. Remove the now unused workflow_py helper. Refs #40 --- tests/ci-workflow-check.py | 55 +++++++++++++++++++++++++++++ tests/ci-workflow.bats | 71 ++++++++++++++++++++++---------------- 2 files changed, 97 insertions(+), 29 deletions(-) diff --git a/tests/ci-workflow-check.py b/tests/ci-workflow-check.py index 7f4aa2e..4814d67 100755 --- a/tests/ci-workflow-check.py +++ b/tests/ci-workflow-check.py @@ -262,6 +262,60 @@ def run(event, ref, run_id): return problems +# Activity types pull_request runs on when `types` is omitted. +DEFAULT_PR_TYPES = {"opened", "reopened", "synchronize"} +FILTERS = {"branches", "branches-ignore", "paths", "paths-ignore"} + + +def triggers(workflow): + """Returns the `on` block as a mapping of event to settings. + + PyYAML reads the bare `on` key as boolean true. A string or list of + events becomes a mapping with no settings. + """ + on = workflow.get("on", workflow.get(True)) + if isinstance(on, str): + return {on: None} + if isinstance(on, list): + return {event: None for event in on} + if isinstance(on, dict): + return on + raise CheckFailed("workflow has no `on` triggers") + + +def check_triggers(workflow, args): + """Checks that every pull request, whatever its base, and each push to + main run the workflow.""" + events = triggers(workflow) + problems = [] + + if "pull_request" not in events: + problems.append("no pull_request trigger") + else: + pr = events["pull_request"] or {} + filters = sorted(set(pr) & FILTERS) + if filters: + problems.append("pull_request has filters: " + ", ".join(filters)) + if "types" in pr: + types = pr["types"] if isinstance(pr["types"], list) else [pr["types"]] + if not DEFAULT_PR_TYPES <= set(types): + problems.append( + "pull_request types must include %s, found %s" + % (", ".join(sorted(DEFAULT_PR_TYPES)), ", ".join(map(str, types))) + ) + + if "push" not in events: + problems.append("no push trigger") + else: + push = events["push"] or {} + if push.get("branches") != ["main"]: + problems.append("push branches are %r, expected ['main']" % push.get("branches")) + filters = sorted(set(push) & (FILTERS - {"branches"})) + if filters: + problems.append("push has filters: " + ", ".join(filters)) + return problems + + MATRIX_SUITE = re.compile(r"\$\{\{\s*matrix\.suite\s*\}\}") @@ -321,6 +375,7 @@ def suite_vars(env): "concurrency": check_concurrency, "matrix": check_matrix, "suites": check_suites, + "triggers": check_triggers, } diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats index aed7c13..4fc8ae1 100644 --- a/tests/ci-workflow.bats +++ b/tests/ci-workflow.bats @@ -5,20 +5,6 @@ WORKFLOW="$REPO_ROOT/.github/workflows/tests.yml" DEV_DOC="$REPO_ROOT/docs/development.md" CHECK="$REPO_ROOT/tests/ci-workflow-check.py" -# Runs a Python snippet against the parsed workflow, bound to `workflow`. -# PyYAML reads the bare `on` key as boolean true, so `triggers` is provided. -workflow_py() { - python3 - "$WORKFLOW" "$1" <<'PY' -import sys -import yaml - -with open(sys.argv[1], encoding="utf-8") as handle: - workflow = yaml.safe_load(handle) -triggers = workflow.get("on", workflow.get(True)) -exec(sys.argv[2]) -PY -} - # Runs one check from tests/ci-workflow-check.py. Optional second and # third arguments replace the workflow and docs paths. check() { @@ -67,23 +53,50 @@ assert_check_rejects() { [ -f "$WORKFLOW" ] } -@test "pull_request trigger has no branch or path filter" { - run workflow_py ' -pr = triggers["pull_request"] if "pull_request" in triggers else sys.exit("no pull_request trigger") -filters = sorted(set(pr or {}) & {"branches", "branches-ignore", "paths", "paths-ignore"}) -if filters: - sys.exit("pull_request has filters: " + ", ".join(filters)) -' - [ "$status" -eq 0 ] || { echo "$output" >&2; return 1; } +@test "every pull request and each push to main trigger the workflow" { + assert_check_passes triggers } -@test "push trigger runs on main" { - run workflow_py ' -push = triggers.get("push") or sys.exit("no push trigger") -if push.get("branches") != ["main"]: - sys.exit("push branches are %r, expected [main]" % push.get("branches")) -' - [ "$status" -eq 0 ] || { echo "$output" >&2; return 1; } +@test "triggers check rejects a pull_request branch filter" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml " pull_request: +" " pull_request: + branches: [main] +")" + assert_check_rejects "pull_request has filters: branches" triggers "$workflow" +} + +@test "triggers check rejects pull_request types without synchronize and reopened" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml " pull_request: +" " pull_request: + types: [opened] +")" + assert_check_rejects "pull_request types must include opened, reopened, synchronize" triggers "$workflow" +} + +@test "triggers check accepts explicit pull_request types that include the defaults" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml " pull_request: +" " pull_request: + types: [opened, synchronize, reopened, ready_for_review] +")" + assert_check_passes triggers "$workflow" +} + +@test "triggers check rejects a push trigger on another branch" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml "branches: [main]" "branches: [develop]")" + assert_check_rejects "push branches are ['develop'], expected ['main']" triggers "$workflow" +} + +@test "triggers check rejects a push path filter" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml " branches: [main] +" " branches: [main] + paths: [plugins/**] +")" + assert_check_rejects "push has filters: paths" triggers "$workflow" } @test "push runs never cancel each other; pull request runs cancel superseded ones" { From 175acc5b664f873068d503a2f04b19227181a769 Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 15:36:43 -0500 Subject: [PATCH 07/14] test(ci): check every parsed action reference for a full SHA pin The pin check grepped for block-style `uses:` lines, so a flow-style step such as `- {uses: owner/action@v5}` or a quoted "uses" key escaped it. Add a pins check to tests/ci-workflow-check.py, replacing the grep. It collects every `uses` value from the parsed workflow, requires each to be `owner/repo@<40-hex SHA>`, and, since YAML parsing drops comments, matches the `# v` comment after each reference in the raw text. Bats tests cover a flow-style step, a quoted key, a missing version comment and a short SHA. Refs #40 --- tests/ci-workflow-check.py | 38 ++++++++++++++++++++++++++++++++++ tests/ci-workflow.bats | 42 ++++++++++++++++++++++++++++++-------- 2 files changed, 71 insertions(+), 9 deletions(-) diff --git a/tests/ci-workflow-check.py b/tests/ci-workflow-check.py index 4814d67..455286a 100755 --- a/tests/ci-workflow-check.py +++ b/tests/ci-workflow-check.py @@ -371,9 +371,47 @@ def suite_vars(env): return problems +PINNED_ACTION = re.compile(r"[\w.-]+/[\w./-]+@[0-9a-f]{40}") + + +def action_references(node): + """Yields every value of a `uses` key anywhere in the parsed workflow.""" + if isinstance(node, dict): + for key, value in node.items(): + if key == "uses": + yield value + else: + yield from action_references(value) + elif isinstance(node, list): + for item in node: + yield from action_references(item) + + +def check_pins(workflow, args): + """Checks that each action is pinned to a full commit SHA with the + release tag in a trailing `# v` comment on the same line. + + References come from the parsed workflow, so flow-style steps and + quoted keys count. Comments are not part of the YAML data, so the + version comment is matched in the raw text. + """ + text = pathlib.Path(args.workflow).read_text(encoding="utf-8") + references = list(action_references(workflow)) + if not references: + return ["no action references (uses) found"] + problems = [] + for reference in references: + if not isinstance(reference, str) or not PINNED_ACTION.fullmatch(reference): + problems.append("not pinned to a full commit SHA: %s" % reference) + elif not re.search(re.escape(reference) + r"(?![\w.-])[^#\n]*#\s*v\d", text): + problems.append("no '# v' comment after %s" % reference) + return problems + + CHECKS = { "concurrency": check_concurrency, "matrix": check_matrix, + "pins": check_pins, "suites": check_suites, "triggers": check_triggers, } diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats index 4fc8ae1..8367b60 100644 --- a/tests/ci-workflow.bats +++ b/tests/ci-workflow.bats @@ -236,13 +236,37 @@ nix develop -c bats tests/missing.bats")" } @test "third-party actions are pinned to full commit SHAs with a version comment" { - run grep -nE '^[[:space:]]*-?[[:space:]]*uses:' "$WORKFLOW" - [ "$status" -eq 0 ] || { echo "no uses: lines found" >&2; return 1; } - local unpinned - unpinned="$(printf '%s\n' "$output" | grep -vE 'uses: [^@[:space:]]+@[0-9a-f]{40} # v[0-9][^[:space:]]*$' || true)" - [ -z "$unpinned" ] || { - echo "actions not pinned to a SHA with a # vX comment:" >&2 - echo "$unpinned" >&2 - return 1 - } + assert_check_passes pins +} + +@test "pins check rejects a tag-pinned action in a flow-style step" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml " - name: Run suite +" " - {uses: actions/setup-python@v5} + - name: Run suite +")" + assert_check_rejects "not pinned to a full commit SHA: actions/setup-python@v5" pins "$workflow" +} + +@test "pins check rejects a tag-pinned action under a quoted uses key" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml " - name: Run suite +" " - \"uses\": actions/setup-python@v5 + - name: Run suite +")" + assert_check_rejects "not pinned to a full commit SHA: actions/setup-python@v5" pins "$workflow" +} + +@test "pins check rejects a SHA pin without a version comment" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml " # v7.0.1" "")" + assert_check_rejects "no '# v' comment" pins "$workflow" +} + +@test "pins check rejects a short SHA" { + local workflow + workflow="$(broken_copy "$WORKFLOW" tests.yml \ + "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1" \ + "actions/checkout@3d3c42e")" + assert_check_rejects "not pinned to a full commit SHA: actions/checkout@3d3c42e" pins "$workflow" } From 73f88bcd869169dacc4df85de3ca41e949f4980e Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 15:46:49 -0500 Subject: [PATCH 08/14] test(ci): require the workflow to match one exact expected shape The triggers, concurrency and matrix checks interpreted the workflow and missed cases GitHub handles differently: a step-level SUITE override of a job-level binding passed the matrix check, the concurrency evaluator compared event names case-sensitively where GitHub does not, and a literal `true:` key passed for `on:` because PyYAML reads `on` as true. Replace the three checks and the expression evaluator with a shape check. EXPECTED in tests/ci-workflow-check.py holds the one supported workflow; every key and value must match it, apart from the matrix suite list (checked by `suites`) and the action commit SHAs (checked by `pins`). Changing the workflow now means changing EXPECTED deliberately. Load YAML with a loader that reads only true and false as booleans, so `on` stays a string, and that rejects duplicate keys instead of keeping the last one. Build the workflow fixtures by changing the parsed workflow and dumping it, not by replacing literal text, so updating a SHA or a comment no longer breaks them. Document the exact-shape rule in the workflow header and docs/development.md. Refs #40 --- .github/workflows/tests.yml | 5 +- docs/development.md | 7 + .../ci-workflow-check.cpython-313.pyc | Bin 0 -> 16118 bytes tests/ci-workflow-check.py | 421 +++++++----------- tests/ci-workflow.bats | 242 +++++----- 5 files changed, 294 insertions(+), 381 deletions(-) create mode 100644 tests/__pycache__/ci-workflow-check.cpython-313.pyc diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index caa8e18..3f01823 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -2,7 +2,10 @@ name: Tests # Runs every bats suite listed under "Running Tests" in docs/development.md. # Adding a suite means adding it to both that list and the matrix below; -# tests/ci-workflow.bats fails when they differ. +# tests/ci-workflow.bats fails when they differ. That suite also requires +# this file to match EXPECTED in tests/ci-workflow-check.py, apart from the +# suite list and the action commit SHAs. Any other change to this file needs +# the same change there. on: # No branch filter: pull requests into any base branch run the suites. diff --git a/docs/development.md b/docs/development.md index 3c56ca2..e2cc227 100644 --- a/docs/development.md +++ b/docs/development.md @@ -152,6 +152,13 @@ the workflow. `tests/ci-workflow.bats` fails when the two differ, and when the block holds a command other than `nix develop -c bats ` or `git diff --check`. Its checks live in `tests/ci-workflow-check.py`. +The guard also requires the workflow to match `EXPECTED` in +`tests/ci-workflow-check.py` exactly, apart from the suite list and the action +commit SHAs. It compares triggers, concurrency, permissions, the job and its +steps as written instead of interpreting them. Any other change to the +workflow, such as a new trigger setting or step, needs the same change to +`EXPECTED`. + Third-party actions in the workflow are pinned to full commit SHAs, with the release tag in a trailing comment. To update one, look up the new release's commit with `gh api repos///commits/ --jq .sha`. diff --git a/tests/__pycache__/ci-workflow-check.cpython-313.pyc b/tests/__pycache__/ci-workflow-check.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a648fa554a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9iSdjleb^1}X literal 0 HcmV?d00001 diff --git a/tests/ci-workflow-check.py b/tests/ci-workflow-check.py index 455286a..dca3dc2 100755 --- a/tests/ci-workflow-check.py +++ b/tests/ci-workflow-check.py @@ -3,10 +3,17 @@ Usage: ci-workflow-check.py [--workflow PATH] [--doc PATH] +Checks: + shape the workflow equals EXPECTED, apart from the suite list and the + action commit SHAs + suites the workflow matrix lists exactly the suites in the "Running + Tests" block of docs/development.md + pins every action is pinned to a full commit SHA with a `# v` + comment + Each check prints one line per problem and exits 1 when it finds any. -A check function takes the parsed workflow and the parsed arguments. -tests/ci-workflow.bats runs every check against the real files and -against broken copies. +tests/ci-workflow.bats runs every check against the real files and against +broken ones. """ import argparse @@ -18,31 +25,146 @@ REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent -# Commands allowed in the "Running Tests" block that are not bats suites. -NON_SUITE_COMMANDS = {"git diff --check"} - -SUITE_COMMAND = re.compile(r"nix develop -c bats (\S+)") - class CheckFailed(Exception): pass +class Loader(yaml.SafeLoader): + """PyYAML's safe loader, changed to read workflows the way GitHub does. + + Only true and false are booleans, so the `on` key stays a string + (YAML 1.1 also reads on, off, yes and no as booleans). A duplicate key + is an error rather than silently replacing the earlier value. + """ + + def construct_mapping(self, node, deep=False): + seen = set() + for key_node, _ in node.value: + key = self.construct_object(key_node, deep=True) + if key in seen: + raise yaml.constructor.ConstructorError( + None, None, "duplicate key %r" % (key,), key_node.start_mark + ) + seen.add(key) + return super().construct_mapping(node, deep) + + +BOOL = "tag:yaml.org,2002:bool" +Loader.yaml_implicit_resolvers = { + first: [(tag, regexp) for tag, regexp in resolvers if tag != BOOL] + for first, resolvers in yaml.SafeLoader.yaml_implicit_resolvers.items() +} +Loader.add_implicit_resolver(BOOL, re.compile(r"^(?:true|True|TRUE|false|False|FALSE)$"), list("tTfF")) + + def load_workflow(path): with open(path, encoding="utf-8") as handle: - return yaml.safe_load(handle) + return yaml.load(handle, Loader=Loader) + + +def pinned(action): + """Matches `@<40-hex commit SHA>`.""" + + def check(value): + if not (isinstance(value, str) and re.fullmatch(re.escape(action) + r"@[0-9a-f]{40}", value)): + return "expected %s@, found %r" % (action, value) + + return check + + +def suite_list(value): + """Matches a non-empty list of paths. The suites check compares them + with the docs.""" + if not (isinstance(value, list) and value and all(isinstance(item, str) for item in value)): + return "expected a list of suite paths, found %r" % (value,) + + +# The one supported workflow. Every key and value must match exactly, +# except the two placeholders: the matrix suite list (checked by `suites`) +# and the action commit SHAs (checked by `pins`). To change anything else +# in the workflow, change it here too, deliberately: these settings make +# every pull request and every push to main run every suite, and make a +# failing suite fail CI. +EXPECTED = { + "name": "Tests", + # No filters or types: every pull request, whatever its base branch. + "on": {"pull_request": None, "push": {"branches": ["main"]}}, + "permissions": {"contents": "read"}, + # Runs for one pull request share a group and cancel superseded runs. + # Each push to main gets its own group, so no push run is canceled. + "concurrency": { + "group": "${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}", + "cancel-in-progress": "${{ github.event_name == 'pull_request' }}", + }, + "jobs": { + "bats": { + "name": "bats ${{ matrix.suite }}", + "runs-on": "ubuntu-latest", + "strategy": {"fail-fast": False, "matrix": {"suite": suite_list}}, + "steps": [ + {"uses": pinned("actions/checkout"), "with": {"persist-credentials": False}}, + { + "uses": pinned("cachix/install-nix-action"), + "with": {"github_access_token": "${{ secrets.GITHUB_TOKEN }}"}, + }, + { + "name": "Run suite", + "env": {"SUITE": "${{ matrix.suite }}"}, + "run": 'nix develop -c bats "$SUITE"', + }, + ], + } + }, +} + + +def differences(expected, actual, path=""): + """Yields one line per place where `actual` differs from `expected`.""" + if callable(expected): + problem = expected(actual) + if problem: + yield "%s: %s" % (path, problem) + elif isinstance(expected, dict): + if not isinstance(actual, dict): + yield "%s: expected a mapping, found %r" % (path or "workflow", actual) + return + def child(key): + name = key if isinstance(key, str) else repr(key) + return "%s.%s" % (path, name) if path else name + + for key in expected: + if key in actual: + yield from differences(expected[key], actual[key], child(key)) + else: + yield "%s: missing" % child(key) + for key in actual: + if key not in expected: + yield "%s: unexpected key" % child(key) + elif isinstance(expected, list): + if not isinstance(actual, list) or len(actual) != len(expected): + yield "%s: expected %d items, found %r" % (path, len(expected), actual) + return + for index, (want, have) in enumerate(zip(expected, actual)): + yield from differences(want, have, "%s[%d]" % (path, index)) + elif type(actual) is not type(expected) or actual != expected: + yield "%s: expected %r, found %r" % (path, expected, actual) + + +def check_shape(workflow, args): + problems = list(differences(EXPECTED, workflow)) + if problems: + problems.append( + "the workflow must match EXPECTED in tests/ci-workflow-check.py; " + "to change the workflow, update EXPECTED deliberately" + ) + return problems + +# Commands allowed in the "Running Tests" block that are not bats suites. +NON_SUITE_COMMANDS = {"git diff --check"} -def suite_jobs(workflow): - """Returns (name, job) for each job with a `suite` matrix.""" - jobs = [ - (name, job) - for name, job in (workflow.get("jobs") or {}).items() - if "suite" in ((job.get("strategy") or {}).get("matrix") or {}) - ] - if not jobs: - raise CheckFailed("no job has a strategy.matrix.suite list") - return jobs +SUITE_COMMAND = re.compile(r"nix develop -c bats (\S+)") def documented_suites(doc_path): @@ -106,12 +228,13 @@ def duplicates(items): def check_suites(workflow, args): documented = documented_suites(args.doc) - matrix = [] - for name, job in suite_jobs(workflow): - suites = job["strategy"]["matrix"]["suite"] - if not isinstance(suites, list) or not all(isinstance(s, str) for s in suites): - raise CheckFailed("job %s: matrix.suite must be a list of paths" % name) - matrix.extend(suites) + try: + matrix = workflow["jobs"]["bats"]["strategy"]["matrix"]["suite"] + except (KeyError, TypeError): + raise CheckFailed("workflow has no jobs.bats.strategy.matrix.suite list") + problem = suite_list(matrix) + if problem: + raise CheckFailed("jobs.bats.strategy.matrix.suite: " + problem) problems = [] for suite in duplicates(documented): @@ -129,248 +252,6 @@ def check_suites(workflow, args): return problems -# A minimal evaluator for GitHub Actions expressions: string literals, -# true/false/null, dotted context names, !, ==, !=, && and ||, and -# parentheses. Enough to evaluate the concurrency settings. -EXPRESSION_TOKEN = re.compile(r"\s*(?:(==|!=|&&|\|\||!|\(|\))|'((?:[^']|'')*)'|([A-Za-z_][\w.-]*))") - - -def evaluate(expression, context): - tokens, position = [], 0 - expression = expression.strip() - while position < len(expression): - match = EXPRESSION_TOKEN.match(expression, position) - if not match or match.end() == position: - raise CheckFailed("cannot parse expression: %r" % expression) - operator, string, name = match.groups() - if operator: - tokens.append(("op", operator)) - elif string is not None: - tokens.append(("value", string.replace("''", "'"))) - else: - literals = {"true": True, "false": False, "null": None} - if name in literals: - tokens.append(("value", literals[name])) - else: - value = context - for part in name.split("."): - value = value.get(part) if isinstance(value, dict) else None - tokens.append(("value", value)) - position = match.end() - - def peek(): - return tokens[0] if tokens else (None, None) - - def take(operator): - if peek() == ("op", operator): - tokens.pop(0) - return True - return False - - def parse_or(): - left = parse_and() - while take("||"): - right = parse_and() - left = left if left else right - return left - - def parse_and(): - left = parse_equality() - while take("&&"): - right = parse_equality() - left = right if left else left - return left - - def parse_equality(): - left = parse_unary() - if take("=="): - return left == parse_unary() - if take("!="): - return left != parse_unary() - return left - - def parse_unary(): - if take("!"): - return not parse_unary() - if take("("): - value = parse_or() - if not take(")"): - raise CheckFailed("unbalanced parentheses: %r" % expression) - return value - kind, value = tokens.pop(0) if tokens else (None, None) - if kind != "value": - raise CheckFailed("unexpected token in expression: %r" % expression) - return value - - value = parse_or() - if tokens: - raise CheckFailed("trailing tokens in expression: %r" % expression) - return value - - -def render(value, context): - """Evaluates a workflow value that may hold ${{ }} expressions.""" - if not isinstance(value, str): - return value - whole = re.fullmatch(r"\$\{\{(.*)\}\}", value.strip(), re.S) - if whole and "}}" not in whole.group(1): - return evaluate(whole.group(1), context) - - def text(match): - result = evaluate(match.group(1), context) - if result is None: - return "" - if isinstance(result, bool): - return "true" if result else "false" - return str(result) - - return re.sub(r"\$\{\{(.*?)\}\}", text, value) - - -def check_concurrency(workflow, args): - """Simulates runs to check which ones share a group and cancel. - - Each push to main must get its own group: in a shared group, a third - push cancels a queued second one. Commits on one pull request share a - group with cancel-in-progress, so a new commit replaces the old run. - """ - concurrency = workflow.get("concurrency") - if not isinstance(concurrency, dict) or "group" not in concurrency: - raise CheckFailed("workflow must set concurrency.group") - - def run(event, ref, run_id): - context = {"github": {"workflow": workflow.get("name", ""), "event_name": event, "ref": ref, "run_id": run_id}} - group = render(concurrency["group"], context) - cancel = render(concurrency.get("cancel-in-progress", False), context) - return str(group), cancel in (True, "true") - - push_a, push_b = run("push", "refs/heads/main", "101"), run("push", "refs/heads/main", "102") - pr_a, pr_b = run("pull_request", "refs/pull/7/merge", "103"), run("pull_request", "refs/pull/7/merge", "104") - other_pr = run("pull_request", "refs/pull/8/merge", "105") - - problems = [] - if push_a[0] == push_b[0]: - problems.append("two pushes to main share concurrency group %r; a queued push run can be canceled" % push_a[0]) - if pr_a[0] != pr_b[0]: - problems.append("commits on one pull request get different groups (%r, %r); superseded runs are not canceled" % (pr_a[0], pr_b[0])) - if not pr_a[1]: - problems.append("pull request runs must set cancel-in-progress") - if pr_a[0] == other_pr[0]: - problems.append("different pull requests share concurrency group %r" % pr_a[0]) - if pr_a[0] in (push_a[0], push_b[0]): - problems.append("a pull request run shares a group with a push run: %r" % pr_a[0]) - return problems - - -# Activity types pull_request runs on when `types` is omitted. -DEFAULT_PR_TYPES = {"opened", "reopened", "synchronize"} -FILTERS = {"branches", "branches-ignore", "paths", "paths-ignore"} - - -def triggers(workflow): - """Returns the `on` block as a mapping of event to settings. - - PyYAML reads the bare `on` key as boolean true. A string or list of - events becomes a mapping with no settings. - """ - on = workflow.get("on", workflow.get(True)) - if isinstance(on, str): - return {on: None} - if isinstance(on, list): - return {event: None for event in on} - if isinstance(on, dict): - return on - raise CheckFailed("workflow has no `on` triggers") - - -def check_triggers(workflow, args): - """Checks that every pull request, whatever its base, and each push to - main run the workflow.""" - events = triggers(workflow) - problems = [] - - if "pull_request" not in events: - problems.append("no pull_request trigger") - else: - pr = events["pull_request"] or {} - filters = sorted(set(pr) & FILTERS) - if filters: - problems.append("pull_request has filters: " + ", ".join(filters)) - if "types" in pr: - types = pr["types"] if isinstance(pr["types"], list) else [pr["types"]] - if not DEFAULT_PR_TYPES <= set(types): - problems.append( - "pull_request types must include %s, found %s" - % (", ".join(sorted(DEFAULT_PR_TYPES)), ", ".join(map(str, types))) - ) - - if "push" not in events: - problems.append("no push trigger") - else: - push = events["push"] or {} - if push.get("branches") != ["main"]: - problems.append("push branches are %r, expected ['main']" % push.get("branches")) - filters = sorted(set(push) & (FILTERS - {"branches"})) - if filters: - problems.append("push has filters: " + ", ".join(filters)) - return problems - - -MATRIX_SUITE = re.compile(r"\$\{\{\s*matrix\.suite\s*\}\}") - - -def check_matrix(workflow, args): - """Checks that every matrix suite runs and that its failure fails CI. - - The matrix may hold only the `suite` list (no include or exclude), the - job must not use fail-fast, and one step must run - `nix develop -c bats ` with nothing else on the line. No - job or step may set continue-on-error or an `if` condition. - """ - problems = [] - for name, job in suite_jobs(workflow): - strategy = job["strategy"] - extra = sorted(set(strategy["matrix"]) - {"suite"}) - if extra: - problems.append("job %s: matrix may only define suite, found %s" % (name, ", ".join(extra))) - if strategy.get("fail-fast", True) is not False: - problems.append("job %s must set fail-fast: false so every suite reports" % name) - if job.get("continue-on-error", False) is not False: - problems.append("job %s must not set continue-on-error" % name) - if "if" in job: - problems.append("job %s must not set an if condition" % name) - - # Environment variables bound to ${{ matrix.suite }}, step or job level. - def suite_vars(env): - return {key for key, value in (env or {}).items() if MATRIX_SUITE.fullmatch(str(value).strip())} - - job_vars = suite_vars(job.get("env")) - bats_steps = [] - for index, step in enumerate(job.get("steps") or []): - label = step.get("name") or step.get("uses") or "step %d" % (index + 1) - if step.get("continue-on-error", False) is not False: - problems.append("job %s, %s: must not set continue-on-error" % (name, label)) - if "bats" in str(step.get("run", "")): - bats_steps.append((label, step)) - if len(bats_steps) != 1: - problems.append("job %s must have exactly one step that runs bats, found %d" % (name, len(bats_steps))) - continue - - label, step = bats_steps[0] - if "if" in step: - problems.append("job %s, %s: must not set an if condition" % (name, label)) - variables = job_vars | suite_vars(step.get("env")) - suite_args = [r"\$\{\{\s*matrix\.suite\s*\}\}"] + [r"\$\{?%s\}?" % re.escape(var) for var in variables] - pattern = r'nix develop -c bats (?:"(?:%s)"|(?:%s))' % ("|".join(suite_args), "|".join(suite_args)) - command = str(step["run"]).strip() - if not re.fullmatch(pattern, command): - problems.append( - "job %s, %s: must run exactly 'nix develop -c bats \"$SUITE\"' with SUITE set to " - "${{ matrix.suite }}, found %r" % (name, label, command) - ) - return problems - - PINNED_ACTION = re.compile(r"[\w.-]+/[\w./-]+@[0-9a-f]{40}") @@ -409,11 +290,9 @@ def check_pins(workflow, args): CHECKS = { - "concurrency": check_concurrency, - "matrix": check_matrix, "pins": check_pins, + "shape": check_shape, "suites": check_suites, - "triggers": check_triggers, } @@ -428,6 +307,8 @@ def main(): problems = CHECKS[args.check](load_workflow(args.workflow), args) except CheckFailed as failure: problems = [str(failure)] + except yaml.YAMLError as error: + problems = ["cannot parse %s: %s" % (args.workflow, error)] for problem in problems: print(problem) return 1 if problems else 0 diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats index 8367b60..b48cf19 100644 --- a/tests/ci-workflow.bats +++ b/tests/ci-workflow.bats @@ -29,6 +29,30 @@ print(target) PY } +# Loads the real workflow with the checker's loader, runs the Python +# statements in on it as the dict `w`, writes the result to +# $BATS_TEST_TMPDIR/tests.yml and prints that path. Fixtures change parsed +# data, not text, so routine edits to the workflow cannot break them. YAML +# comments do not survive, so the pins check needs its own fixtures. +mutated_workflow() { + python3 - "$CHECK" "$WORKFLOW" "$BATS_TEST_TMPDIR/tests.yml" "$1" <<'PY' +import importlib.util +import sys + +import yaml + +check_path, source, target, code = sys.argv[1:] +spec = importlib.util.spec_from_file_location("ci_workflow_check", check_path) +checker = importlib.util.module_from_spec(spec) +spec.loader.exec_module(checker) +w = checker.load_workflow(source) +exec(code, {"w": w}) +with open(target, "w", encoding="utf-8") as handle: + yaml.safe_dump(w, handle, sort_keys=False) +print(target) +PY +} + # Passes when the check passes; prints its output otherwise. assert_check_passes() { run check "$@" @@ -53,78 +77,139 @@ assert_check_rejects() { [ -f "$WORKFLOW" ] } -@test "every pull request and each push to main trigger the workflow" { - assert_check_passes triggers +@test "workflow matches the expected shape" { + assert_check_passes shape } -@test "triggers check rejects a pull_request branch filter" { +@test "an unchanged round trip of the workflow passes the shape check" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml " pull_request: -" " pull_request: - branches: [main] -")" - assert_check_rejects "pull_request has filters: branches" triggers "$workflow" + workflow="$(mutated_workflow 'pass')" + assert_check_passes shape "$workflow" } -@test "triggers check rejects pull_request types without synchronize and reopened" { +@test "shape check rejects a pull_request branch filter" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml " pull_request: -" " pull_request: - types: [opened] -")" - assert_check_rejects "pull_request types must include opened, reopened, synchronize" triggers "$workflow" + workflow="$(mutated_workflow 'w["on"]["pull_request"] = {"branches": ["main"]}')" + assert_check_rejects "on.pull_request: expected None" shape "$workflow" } -@test "triggers check accepts explicit pull_request types that include the defaults" { +@test "shape check rejects pull_request activity types" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml " pull_request: -" " pull_request: - types: [opened, synchronize, reopened, ready_for_review] -")" - assert_check_passes triggers "$workflow" + workflow="$(mutated_workflow 'w["on"]["pull_request"] = {"types": ["opened"]}')" + assert_check_rejects "on.pull_request: expected None" shape "$workflow" } -@test "triggers check rejects a push trigger on another branch" { +@test "shape check rejects a push trigger on another branch" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml "branches: [main]" "branches: [develop]")" - assert_check_rejects "push branches are ['develop'], expected ['main']" triggers "$workflow" + workflow="$(mutated_workflow 'w["on"]["push"]["branches"] = ["develop"]')" + assert_check_rejects "on.push.branches[0]: expected 'main', found 'develop'" shape "$workflow" } -@test "triggers check rejects a push path filter" { +@test "shape check rejects a push path filter" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml " branches: [main] -" " branches: [main] - paths: [plugins/**] -")" - assert_check_rejects "push has filters: paths" triggers "$workflow" + workflow="$(mutated_workflow 'w["on"]["push"]["paths"] = ["plugins/**"]')" + assert_check_rejects "on.push.paths: unexpected key" shape "$workflow" +} + +@test "shape check rejects a literal true key in place of on" { + local workflow + workflow="$(mutated_workflow 'w[True] = w.pop("on")')" + grep -q '^true:' "$workflow" + assert_check_rejects "on: missing" shape "$workflow" } -@test "push runs never cancel each other; pull request runs cancel superseded ones" { - assert_check_passes concurrency +@test "shape check rejects a duplicate key" { + local workflow="$BATS_TEST_TMPDIR/tests.yml" + printf 'name: Tests\nname: Other\n' >"$workflow" + assert_check_rejects "duplicate key 'name'" shape "$workflow" } -@test "concurrency check rejects one group shared by all pushes to main" { +@test "shape check rejects one concurrency group shared by all pushes to main" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml \ - "github.event_name == 'pull_request' && github.ref || github.run_id" \ - "github.ref")" - assert_check_rejects "two pushes to main share concurrency group" concurrency "$workflow" + workflow="$(mutated_workflow 'w["concurrency"]["group"] = "${{ github.workflow }}-${{ github.ref }}"')" + assert_check_rejects "concurrency.group: expected" shape "$workflow" } -@test "concurrency check rejects pull request runs that do not cancel" { +@test "shape check rejects an event name compared in another case" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml \ - "cancel-in-progress: \${{ github.event_name == 'pull_request' }}" \ - "cancel-in-progress: false")" - assert_check_rejects "pull request runs must set cancel-in-progress" concurrency "$workflow" + workflow="$(mutated_workflow 'w["concurrency"]["group"] = "${{ github.workflow }}-${{ github.event_name == '"'pull_request'"' && github.ref || github.event_name == '"'PUSH'"' && github.ref || github.run_id }}"')" + assert_check_rejects "concurrency.group: expected" shape "$workflow" } -@test "concurrency check rejects a group per pull request commit" { +@test "shape check rejects pull request runs that do not cancel" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml \ - "github.event_name == 'pull_request' && github.ref || github.run_id" \ - "github.run_id")" - assert_check_rejects "commits on one pull request get different groups" concurrency "$workflow" + workflow="$(mutated_workflow 'w["concurrency"]["cancel-in-progress"] = False')" + assert_check_rejects "concurrency.cancel-in-progress: expected" shape "$workflow" +} + +@test "shape check rejects a suite dropped by matrix.exclude" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["bats"]["strategy"]["matrix"]["exclude"] = [{"suite": "tests/ci-workflow.bats"}]')" + assert_check_rejects "jobs.bats.strategy.matrix.exclude: unexpected key" shape "$workflow" +} + +@test "shape check rejects fail-fast" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["bats"]["strategy"]["fail-fast"] = True')" + assert_check_rejects "jobs.bats.strategy.fail-fast: expected False, found True" shape "$workflow" +} + +@test "shape check rejects continue-on-error on the suite job" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["bats"]["continue-on-error"] = True')" + assert_check_rejects "jobs.bats.continue-on-error: unexpected key" shape "$workflow" +} + +@test "shape check rejects continue-on-error on the run step" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["bats"]["steps"][-1]["continue-on-error"] = True')" + assert_check_rejects "jobs.bats.steps[2].continue-on-error: unexpected key" shape "$workflow" +} + +@test "shape check rejects a hardcoded suite path in the run step" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["bats"]["steps"][-1]["run"] = "nix develop -c bats tests/ci-workflow.bats"')" + assert_check_rejects "jobs.bats.steps[2].run: expected" shape "$workflow" +} + +@test "shape check rejects a run step that swallows failures" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["bats"]["steps"][-1]["run"] += " || true"')" + assert_check_rejects "jobs.bats.steps[2].run: expected" shape "$workflow" +} + +@test "shape check rejects a step-level SUITE override of a job-level binding" { + local workflow + workflow="$(mutated_workflow ' +job = w["jobs"]["bats"] +job["env"] = {"SUITE": "${{ matrix.suite }}"} +job["steps"][-1]["env"] = {"SUITE": "tests/ci-workflow.bats"} +')" + assert_check_rejects "jobs.bats.steps[2].env.SUITE: expected" shape "$workflow" +} + +@test "shape check rejects a workflow-level env" { + local workflow + workflow="$(mutated_workflow 'w["env"] = {"SUITE": "tests/ci-workflow.bats"}')" + assert_check_rejects "env: unexpected key" shape "$workflow" +} + +@test "shape check rejects an extra step" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["bats"]["steps"].append({"run": "true"})')" + assert_check_rejects "jobs.bats.steps: expected 3 items" shape "$workflow" +} + +@test "shape check rejects wider permissions" { + local workflow + workflow="$(mutated_workflow 'w["permissions"]["contents"] = "write"')" + assert_check_rejects "permissions.contents: expected 'read', found 'write'" shape "$workflow" +} + +@test "shape check rejects a tag-pinned action" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["bats"]["steps"][0]["uses"] = "actions/checkout@v7"')" + assert_check_rejects "jobs.bats.steps[0].uses: expected actions/checkout@" shape "$workflow" } @test "workflow runs exactly the suites listed in docs/development.md" { @@ -161,10 +246,7 @@ nix develop -c bats tests/missing.bats")" @test "suites check rejects a matrix suite missing from docs" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml \ - " - tests/ci-workflow.bats" \ - " - tests/ci-workflow.bats - - tests/undocumented.bats")" + workflow="$(mutated_workflow 'w["jobs"]["bats"]["strategy"]["matrix"]["suite"].append("tests/undocumented.bats")')" assert_check_rejects "in the workflow matrix but not in docs: tests/undocumented.bats" \ suites "$workflow" } @@ -175,66 +257,6 @@ nix develop -c bats tests/missing.bats")" assert_check_rejects "no '## Running Tests' section" suites "$WORKFLOW" "$doc" } -@test "each matrix suite runs through the flake dev shell and can fail the job" { - assert_check_passes matrix -} - -@test "matrix check rejects a suite dropped by matrix.exclude" { - local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml \ - " - plugins/branch-guard/tests -" \ - " - plugins/branch-guard/tests - exclude: - - suite: plugins/branch-guard/tests -")" - assert_check_rejects "matrix may only define suite" matrix "$workflow" -} - -@test "matrix check rejects a hardcoded suite path in the run step" { - local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml \ - 'run: nix develop -c bats "$SUITE"' \ - 'run: nix develop -c bats tests/ci-workflow.bats')" - assert_check_rejects "must run exactly" matrix "$workflow" -} - -@test "matrix check rejects a run step that swallows failures" { - local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml \ - 'run: nix develop -c bats "$SUITE"' \ - 'run: nix develop -c bats "$SUITE" || true')" - assert_check_rejects "must run exactly" matrix "$workflow" -} - -@test "matrix check rejects continue-on-error on the suite job" { - local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml \ - " runs-on: ubuntu-latest -" \ - " runs-on: ubuntu-latest - continue-on-error: true -")" - assert_check_rejects "continue-on-error" matrix "$workflow" -} - -@test "matrix check rejects continue-on-error on the run step" { - local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml \ - " - name: Run suite -" \ - " - name: Run suite - continue-on-error: true -")" - assert_check_rejects "continue-on-error" matrix "$workflow" -} - -@test "matrix check rejects fail-fast" { - local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml "fail-fast: false" "fail-fast: true")" - assert_check_rejects "fail-fast: false" matrix "$workflow" -} - @test "third-party actions are pinned to full commit SHAs with a version comment" { assert_check_passes pins } From bbc8157353cadc1a3c1458552d7a0e6eca3668e4 Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 15:48:39 -0500 Subject: [PATCH 09/14] test(ci): parse both fence styles in the Running Tests section The docs parser treated only backtick lines as fences. A second block fenced with tildes escaped the one-block rule, so a suite listed there never had to reach the workflow matrix, and a tilde fence on the real block made the check fail with no block found. Parse fences in one pass: three or more backticks or tildes open a block, which closes only on a line of the same character that is at least as long. A heading inside a block no longer ends the section. The section must still hold exactly one block, subsections included. Build the docs fixtures as standalone files from the workflow matrix instead of replacing literal text in docs/development.md. Refs #40 --- docs/development.md | 7 +- .../ci-workflow-check.cpython-313.pyc | Bin 16118 -> 16658 bytes tests/ci-workflow-check.py | 36 ++++---- tests/ci-workflow.bats | 85 +++++++++++++++--- 4 files changed, 94 insertions(+), 34 deletions(-) diff --git a/docs/development.md b/docs/development.md index e2cc227..8cc8d59 100644 --- a/docs/development.md +++ b/docs/development.md @@ -148,9 +148,10 @@ that pull request's running checks; runs for pushes to `main` never cancel or replace each other. When you add a suite, add it to both the list above and the `suite` matrix in -the workflow. `tests/ci-workflow.bats` fails when the two differ, and when the -block holds a command other than `nix develop -c bats ` or -`git diff --check`. Its checks live in `tests/ci-workflow-check.py`. +the workflow. `tests/ci-workflow.bats` fails when the two differ, when this +section holds more than one code block, and when the block holds a command +other than `nix develop -c bats ` or `git diff --check`. Its checks live +in `tests/ci-workflow-check.py`. The guard also requires the workflow to match `EXPECTED` in `tests/ci-workflow-check.py` exactly, apart from the suite list and the action diff --git a/tests/__pycache__/ci-workflow-check.cpython-313.pyc b/tests/__pycache__/ci-workflow-check.cpython-313.pyc index 8a648fa554a282a0c84ecf1122e0cdcbe3c5991a..16d650586218d7050f54644c86ebe7a9178c50c2 100644 GIT binary patch delta 1932 zcmY*ZdrVVT7(cf!Y74Yr0gKX}wiXMtOWLfucI+yv#qH)7Tw`7UaJzTbA5R9_UKg_ncm`nq@E!jWIzEij;P44g9{?70F z&hPuaoAXcq(L+r3qpU0qg5StUW=G0Bn!SX1^^+9`Wy~saO17Fz%Zx=XFGB?g2}P{C z5D6x>9MH^G0Ai|GQ#r4&uvNfXSr4EsWD6CBFuT$%7nZYLVCEB6=Rz6z(O-?6>VJbCI^929(3|=%#|4 ztF)7IMSWIQ$tt^B;_}v9R^@^{R;fUX(dIu9imQT(@Bl(&oyo?iNTtW1$EfMYHbXiW zK%jtRo0l2l8Nm$49LLon6wC-1$xP*9vq~zERV!)cMd>2)=$oV|&`25|C?b%$d_LYb zAK%^Le-R=7OYppcP@8`4Fcip#R^-XGZF<6Z@W$C=q=aonk}Rl{xRo-O3Jj{eve~_P z+h8gv517fc+K?}aG4vv?@c#l^3fRgvo1XJOKuC))5IeMBL?@lVW=cUk^TfF@pIHT~ zs_BLK6)cF!dQwTgFfYwZ2IaFgzyOZG05m~Oz(OjRLPJ~|)XtmD2S?g~jrN$yCQfYB zE|-kJNCvT?N;-GJXsi&X4wxn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Auc#OL z@0sii>Y~oL)V zzNx4;o0oKcAAbb@&o=${LphBj5yTlmBFecTNoWCE(fpY1Vq!y9BhPhgb51p)^M+`!YF z7nt{9YQ&E^Z&Ufg*ImD<3|E0Dv3*1ReTPK(I{v(8p4wR$>TRan0ohOD)(DidMu?PF zPAf7zeJFx+dtB6Yytd~cczL{MFnEd3iv-Bw%cKRF7?y7mC_5$fOqGDNP_+uj2=T+`3mk;I*!IXb5&|f%(GA G0{#okwnJP1 diff --git a/tests/ci-workflow-check.py b/tests/ci-workflow-check.py index dca3dc2..019c76d 100755 --- a/tests/ci-workflow-check.py +++ b/tests/ci-workflow-check.py @@ -165,14 +165,18 @@ def check_shape(workflow, args): NON_SUITE_COMMANDS = {"git diff --check"} SUITE_COMMAND = re.compile(r"nix develop -c bats (\S+)") +FENCE = re.compile(r" {0,3}(`{3,}|~{3,})(.*)") def documented_suites(doc_path): """Returns the suite paths in the "Running Tests" block, in order. - The section runs from "## Running Tests" to the next level-2 heading - and must hold exactly one fenced block. Every command in it must be a - `nix develop -c bats ` line or one of NON_SUITE_COMMANDS. + The section runs from "## Running Tests" to the next level-1 or level-2 + heading outside a code block, and must hold exactly one fenced code + block. A fence is three or more backticks or tildes; it closes only on + a line of the same character, at least as long, with nothing after it. + Every command in the block must be a `nix develop -c bats ` line + or one of NON_SUITE_COMMANDS. """ lines = pathlib.Path(doc_path).read_text(encoding="utf-8").splitlines() try: @@ -180,21 +184,19 @@ def documented_suites(doc_path): except StopIteration: raise CheckFailed("%s has no '## Running Tests' section" % doc_path) - section = [] + blocks, block, fence = [], None, None for line in lines[start + 1 :]: - if re.match(r"##\s", line): - break - section.append(line) - - blocks, block = [], None - for line in section: - if line.strip().startswith("```"): - if block is None: - block = [] - else: - blocks.append(block) - block = None - elif block is not None: + if block is None: + if re.match(r"#{1,2}\s", line): + break + match = FENCE.fullmatch(line) + # A backtick fence's info string cannot hold a backtick. + if match and not (match.group(1)[0] == "`" and "`" in match.group(2)): + block, fence = [], match.group(1) + elif re.fullmatch(r" {0,3}%s{%d,}\s*" % (re.escape(fence[0]), len(fence)), line): + blocks.append(block) + block = None + else: block.append(line) if block is not None: raise CheckFailed("Running Tests has an unclosed code fence") diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats index b48cf19..dc5a33d 100644 --- a/tests/ci-workflow.bats +++ b/tests/ci-workflow.bats @@ -53,6 +53,28 @@ print(target) PY } +# Prints the workflow matrix as `nix develop -c bats ` lines. +matrix_commands() { + python3 - "$WORKFLOW" <<'PY' +import sys + +import yaml + +with open(sys.argv[1], encoding="utf-8") as handle: + workflow = yaml.safe_load(handle) +for suite in workflow["jobs"]["bats"]["strategy"]["matrix"]["suite"]: + print("nix develop -c bats " + suite) +PY +} + +# Writes $BATS_TEST_TMPDIR/development.md with as the whole +# "Running Tests" section and prints its path. +doc_with() { + local doc="$BATS_TEST_TMPDIR/development.md" + printf '# Development\n\n## Running Tests\n\n%s\n\n## Repository Structure\n\n```text\nagent-plugins/\n```\n' "$1" >"$doc" + echo "$doc" +} + # Passes when the check passes; prints its output otherwise. assert_check_passes() { run check "$@" @@ -216,32 +238,67 @@ job["steps"][-1]["env"] = {"SUITE": "tests/ci-workflow.bats"} assert_check_passes suites } +@test "suites check passes on a docs block built from the matrix" { + local doc + doc="$(doc_with "$(printf '```bash\n%s\ngit diff --check\n```' "$(matrix_commands)")")" + assert_check_passes suites "$WORKFLOW" "$doc" +} + +@test "suites check reads a tilde-fenced docs block" { + local doc + doc="$(doc_with "$(printf '~~~bash\n%s\n~~~' "$(matrix_commands)")")" + assert_check_passes suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects a second backtick-fenced block" { + local doc + doc="$(doc_with "$(printf '```bash\n%s\n```\n\n```bash\nnix develop -c bats tests/not-in-ci.bats\n```' "$(matrix_commands)")")" + assert_check_rejects "exactly one code block, found 2" suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects a second tilde-fenced block" { + local doc + doc="$(doc_with "$(printf '```bash\n%s\n```\n\n~~~bash\nnix develop -c bats tests/not-in-ci.bats\n~~~' "$(matrix_commands)")")" + assert_check_rejects "exactly one code block, found 2" suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects a second block in a subsection" { + local doc + doc="$(doc_with "$(printf '```bash\n%s\n```\n\n### More\n\n```bash\nnix develop -c bats tests/not-in-ci.bats\n```' "$(matrix_commands)")")" + assert_check_rejects "exactly one code block, found 2" suites "$WORKFLOW" "$doc" +} + +@test "suites check closes a fence only with the same delimiter" { + local doc + doc="$(doc_with "$(printf '~~~bash\n%s\n```\nnix develop -c bats tests/not-in-ci.bats\n~~~' "$(matrix_commands)")")" + assert_check_rejects "unrecognized command in Running Tests: '\`\`\`'" suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects an unclosed fence" { + local doc + doc="$(doc_with "$(printf '~~~bash\n%s' "$(matrix_commands)")")" + assert_check_rejects "unclosed code fence" suites "$WORKFLOW" "$doc" +} + @test "suites check rejects a documented suite missing from the matrix" { local doc - doc="$(broken_copy "$DEV_DOC" development.md \ - "nix develop -c bats tests/ci-workflow.bats" \ - "nix develop -c bats tests/ci-workflow.bats -nix develop -c bats tests/missing.bats")" + doc="$(doc_with "$(printf '```bash\n%s\nnix develop -c bats tests/missing.bats\n```' "$(matrix_commands)")")" assert_check_rejects "in docs but not in the workflow matrix: tests/missing.bats" \ suites "$WORKFLOW" "$doc" } @test "suites check reads indented suite lines in the docs block" { local doc - doc="$(broken_copy "$DEV_DOC" development.md \ - "nix develop -c bats tests/ci-workflow.bats" \ - "nix develop -c bats tests/ci-workflow.bats - nix develop -c bats tests/indented.bats")" + doc="$(doc_with "$(printf '```bash\n%s\n nix develop -c bats tests/indented.bats\n```' "$(matrix_commands)")")" assert_check_rejects "in docs but not in the workflow matrix: tests/indented.bats" \ suites "$WORKFLOW" "$doc" } @test "suites check rejects an unrecognized command in the docs block" { local doc - doc="$(broken_copy "$DEV_DOC" development.md \ - "nix develop -c bats tests/ci-workflow.bats" \ - "nix develop --command bats tests/ci-workflow.bats")" - assert_check_rejects "unrecognized command in Running Tests" suites "$WORKFLOW" "$doc" + doc="$(doc_with "$(printf '```bash\n%s\nnix develop --command bats tests/other.bats\n```' "$(matrix_commands)")")" + assert_check_rejects "unrecognized command in Running Tests: 'nix develop --command bats tests/other.bats'" \ + suites "$WORKFLOW" "$doc" } @test "suites check rejects a matrix suite missing from docs" { @@ -252,8 +309,8 @@ nix develop -c bats tests/missing.bats")" } @test "suites check fails when docs have no Running Tests section" { - local doc - doc="$(broken_copy "$DEV_DOC" development.md "## Running Tests" "## Tests")" + local doc="$BATS_TEST_TMPDIR/development.md" + printf '# Development\n\n## Tests\n\n```bash\nnix develop -c bats tests/ci-workflow.bats\n```\n' >"$doc" assert_check_rejects "no '## Running Tests' section" suites "$WORKFLOW" "$doc" } From 2550836178f1a65fbcecfed1ba3320403f3a1a8f Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 15:50:00 -0500 Subject: [PATCH 10/14] test(ci): read each pin's version comment from its own source line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pins check searched the whole file for the reference followed by a version comment, so a second use of the same SHA without a comment borrowed the first one's. It also rejected local actions (`uses: ./…`), which have no SHA to pin. Compose the YAML node tree, take each `uses` value node's line and column, and require the `# v` comment on the rest of that line. Skip references that start with `./`. Build the pins fixtures as standalone minimal workflows with a placeholder SHA, and drop the text-replacement fixture helper, which no test uses any more. Refs #40 --- .../ci-workflow-check.cpython-313.pyc | Bin 16658 -> 17501 bytes tests/ci-workflow-check.py | 46 +++++++----- tests/ci-workflow.bats | 69 +++++++++++------- 3 files changed, 68 insertions(+), 47 deletions(-) diff --git a/tests/__pycache__/ci-workflow-check.cpython-313.pyc b/tests/__pycache__/ci-workflow-check.cpython-313.pyc index 16d650586218d7050f54644c86ebe7a9178c50c2..3c4519e1cb873f7513954d484f191b2ba3b649ce 100644 GIT binary patch delta 2949 zcmaJ@X>1$E72a81;vrK9t=rK`B27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9W(@iOr{9W0tRu#s6O{y35R{-i6#o zsfRx5^V5!g$9kSfY1S_m#CfNi#hYThFdH@g$kPKW%hdS@n^r)B;1;(*w!oT+IWJ`{_udb(b6 z$6j{EGcUC}<4XHVJb9*xUhy}ryUWOTVC@?KTKo7eNMisR-L?AZVNxtqMSHA zmrG|9@(X6OLb=^U^y7h+mIv0VKiXSwn6~VPx2)agPW-u~YNx_?r@ZHmsb{C$dT#1| zRpWUxogD0Z;hrV2w_Hyk;_XqxW{nuXHa(M4_Pv3P+-_CDaBU{$Uj>UE{bRl%7 ze&pBwyYvY=%?87m>013aoquId)P_;J>KK}nh9Bs;m`lcaZNe}I_##sbaGJGbXq2RZJRzL N;DCu~e%s44{2xCJJ!${| diff --git a/tests/ci-workflow-check.py b/tests/ci-workflow-check.py index 019c76d..901f9a3 100755 --- a/tests/ci-workflow-check.py +++ b/tests/ci-workflow-check.py @@ -255,39 +255,47 @@ def check_suites(workflow, args): PINNED_ACTION = re.compile(r"[\w.-]+/[\w./-]+@[0-9a-f]{40}") +VERSION_COMMENT = re.compile(r"(?:^|\s)#\s*v\d") -def action_references(node): - """Yields every value of a `uses` key anywhere in the parsed workflow.""" - if isinstance(node, dict): - for key, value in node.items(): - if key == "uses": +def uses_nodes(node): + """Yields the value node of every `uses` key in a composed YAML tree, + so flow-style steps and quoted keys count.""" + if isinstance(node, yaml.MappingNode): + for key, value in node.value: + if isinstance(key, yaml.ScalarNode) and key.value == "uses": yield value else: - yield from action_references(value) - elif isinstance(node, list): - for item in node: - yield from action_references(item) + yield from uses_nodes(value) + elif isinstance(node, yaml.SequenceNode): + for item in node.value: + yield from uses_nodes(item) def check_pins(workflow, args): - """Checks that each action is pinned to a full commit SHA with the - release tag in a trailing `# v` comment on the same line. + """Checks that each action is pinned to a full commit SHA, with the + release tag in a `# v` comment after it on the same line. - References come from the parsed workflow, so flow-style steps and - quoted keys count. Comments are not part of the YAML data, so the - version comment is matched in the raw text. + Comments are not part of the YAML data, so each reference's node gives + its source line and the comment is read from the rest of that line. + Local actions (`uses: ./path`) are skipped. """ text = pathlib.Path(args.workflow).read_text(encoding="utf-8") - references = list(action_references(workflow)) - if not references: + lines = text.splitlines() + nodes = list(uses_nodes(yaml.compose(text, Loader=Loader))) + if not nodes: return ["no action references (uses) found"] problems = [] - for reference in references: + for node in nodes: + reference = node.value + if isinstance(reference, str) and reference.startswith("./"): + continue if not isinstance(reference, str) or not PINNED_ACTION.fullmatch(reference): problems.append("not pinned to a full commit SHA: %s" % reference) - elif not re.search(re.escape(reference) + r"(?![\w.-])[^#\n]*#\s*v\d", text): - problems.append("no '# v' comment after %s" % reference) + continue + end = node.end_mark + if end.line != node.start_mark.line or not VERSION_COMMENT.search(lines[end.line][end.column :]): + problems.append("line %d: no '# v' comment after %s" % (end.line + 1, reference)) return problems diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats index dc5a33d..59c9ef9 100644 --- a/tests/ci-workflow.bats +++ b/tests/ci-workflow.bats @@ -11,22 +11,16 @@ check() { python3 "$CHECK" "$1" --workflow "${2:-$WORKFLOW}" --doc "${3:-$DEV_DOC}" } -# Copies to $BATS_TEST_TMPDIR/ with the first -# replaced by , and prints the copy's path. Fails when is -# absent, so a stale fixture cannot pass silently. -broken_copy() { - python3 - "$1" "$BATS_TEST_TMPDIR/$2" "$3" "$4" <<'PY' -import sys +# A placeholder commit SHA for standalone pins fixtures. +SHA=0123456789abcdef0123456789abcdef01234567 -source, target, old, new = sys.argv[1:] -with open(source, encoding="utf-8") as handle: - text = handle.read() -if old not in text: - sys.exit("broken_copy: text not found in %s: %r" % (source, old)) -with open(target, "w", encoding="utf-8") as handle: - handle.write(text.replace(old, new, 1)) -print(target) -PY +# Writes a minimal workflow whose only job has (YAML lines indented +# for a steps list, the first on line 6) to $BATS_TEST_TMPDIR/steps.yml +# and prints its path. +steps_workflow() { + local workflow="$BATS_TEST_TMPDIR/steps.yml" + printf 'on: push\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n%s\n' "$1" >"$workflow" + echo "$workflow" } # Loads the real workflow with the checker's loader, runs the Python @@ -318,34 +312,53 @@ job["steps"][-1]["env"] = {"SUITE": "tests/ci-workflow.bats"} assert_check_passes pins } +@test "pins check passes a pinned action with a version comment" { + local workflow + workflow="$(steps_workflow " - uses: actions/checkout@$SHA # v1.2.3")" + assert_check_passes pins "$workflow" +} + @test "pins check rejects a tag-pinned action in a flow-style step" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml " - name: Run suite -" " - {uses: actions/setup-python@v5} - - name: Run suite -")" + workflow="$(steps_workflow " - {uses: actions/setup-python@v5}")" assert_check_rejects "not pinned to a full commit SHA: actions/setup-python@v5" pins "$workflow" } @test "pins check rejects a tag-pinned action under a quoted uses key" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml " - name: Run suite -" " - \"uses\": actions/setup-python@v5 - - name: Run suite -")" + workflow="$(steps_workflow " - \"uses\": actions/setup-python@v5")" assert_check_rejects "not pinned to a full commit SHA: actions/setup-python@v5" pins "$workflow" } @test "pins check rejects a SHA pin without a version comment" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml " # v7.0.1" "")" - assert_check_rejects "no '# v' comment" pins "$workflow" + workflow="$(steps_workflow " - uses: actions/checkout@$SHA")" + assert_check_rejects "line 6: no '# v' comment after actions/checkout@$SHA" pins "$workflow" +} + +@test "pins check rejects a version comment borrowed from another line" { + local workflow + workflow="$(steps_workflow " - uses: actions/checkout@$SHA # v1.2.3 + - uses: actions/checkout@$SHA")" + assert_check_rejects "line 7: no '# v' comment after actions/checkout@$SHA" pins "$workflow" +} + +@test "pins check rejects a version comment on the next line" { + local workflow + workflow="$(steps_workflow " - uses: actions/checkout@$SHA + # v1.2.3")" + assert_check_rejects "line 6: no '# v' comment" pins "$workflow" } @test "pins check rejects a short SHA" { local workflow - workflow="$(broken_copy "$WORKFLOW" tests.yml \ - "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1" \ - "actions/checkout@3d3c42e")" + workflow="$(steps_workflow " - uses: actions/checkout@3d3c42e # v1.2.3")" assert_check_rejects "not pinned to a full commit SHA: actions/checkout@3d3c42e" pins "$workflow" } + +@test "pins check allows a local action" { + local workflow + workflow="$(steps_workflow " - uses: actions/checkout@$SHA # v1.2.3 + - uses: ./.github/actions/setup")" + assert_check_passes pins "$workflow" +} From f404685a46a3126cf5578cd44ba5e3e18c648f48 Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 15:57:25 -0500 Subject: [PATCH 11/14] chore(ci): stop tracking Python bytecode from the checker The bats suite imports tests/ci-workflow-check.py to build fixtures, which wrote a .pyc into tests/__pycache__/ that was committed by mistake and embedded a local absolute path. - Remove tests/__pycache__/ci-workflow-check.cpython-313.pyc. - Ignore __pycache__/ and *.pyc. - Export PYTHONDONTWRITEBYTECODE=1 in tests/ci-workflow.bats so the suite writes no bytecode. Refs #40 --- .gitignore | 3 ++- .../ci-workflow-check.cpython-313.pyc | Bin 17501 -> 0 bytes tests/ci-workflow.bats | 3 +++ 3 files changed, 5 insertions(+), 1 deletion(-) delete mode 100644 tests/__pycache__/ci-workflow-check.cpython-313.pyc diff --git a/.gitignore b/.gitignore index 4662664..e19eb3c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .direnv/ - +__pycache__/ +*.pyc diff --git a/tests/__pycache__/ci-workflow-check.cpython-313.pyc b/tests/__pycache__/ci-workflow-check.cpython-313.pyc deleted file mode 100644 index 3c4519e1cb873f7513954d484f191b2ba3b649ce..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 17501 zcmb7rd2k!&m1j2&;v@myhbXDVQ{Vwoq9n@{MOz{%Q3pwhP1v+a34#ESghc{OHz13! zJ>e#q3}w$ma>iNHiFYg~u0&2;i866jlw)cXJG0|VZPfyTVlZu$%d>IKuB*1TbR}bF z|JmRB8V!IH<;;E(KXiZh@xJ$d@4c_@78Y7LgpV%R&&+gk-0$f{3q_fSyWiJy+&4Ip z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#QP= zBB=W^Rq=|>Rk6E`hS)>V07X%XW+*yG(bp*Y8;V|_h}1CEDD+)=`XNPEC}P5!1fFz_ zB1SbPJShhH&KDmp8QFKRBtkPoRP=ykN`Vxd#-%>?EkP%OY8*26sNd7}N-JmsgvZGb zgWX_bc>cD*!5i+@alG>buIK~K@&RZ4J!ks}qBZBdX-V2!a7iz1?@HRc()RA8y?fDe zuYl(*7hTwO-g3`e%h6eEE-^P*|_Dkkyl32wSCFjzH}{w;Gr9} zNB(Hk*XjO8?UAGzMjL2t4Un~1r>kC6m;tNA>K5^Z4;JV?! z?`n_SqdJQPH@Ho=%p7k@bG1pXc6sd5_V0CnyF1~2JXJrQeDY+%8%#Ypb%UF}Q=sEJ z?^sQI@traQKfvFrg+J<}4Vy2wTseDXCgFM{X?=91Y}2KJL}@b`EQ#_fn-1SL>dOjl zSviYirOdrj*|gHsdewBTCh^eGWYy5WR&P!S+f&tDiC!_`c`~tgBI%s`*V?*7eQ&Dv zk(G_x6FZJ4YDduqKL4|F8@I01)+ZXf6C3udYCTSd`ri?i5zOJ7o0aJzDo zUAJhyx1ZmL0p59(H}Pe+D!58lqTH3>NBLlymoD;fmRM!TP*4QQDp| zyBCdjaHFQ=&O9~{Rn3*Cxq~Y%RV(aCIeSo{r0nIEueT&NcBD!=7aeyBZ2Z Date: Sun, 29 Nov 2026 15:59:07 -0500 Subject: [PATCH 12/14] ci: run the workflow guard suite in its own fixed job A merge that dropped tests/ci-workflow.bats from the matrix while it stayed documented would silently remove the guard from CI. - Add a guard job that always runs tests/ci-workflow.bats, and take that suite out of the bats matrix. - Add the guard job to EXPECTED, sharing the suite job steps, so the shape check rejects its removal or any change to its command. - The suites check compares the docs with the guard job's suite plus the matrix, reports a suite the workflow runs twice, and reports the guard suite as missing when the guard job no longer runs it. - Document the guard job in docs/development.md. Refs #40 --- .github/workflows/tests.yml | 27 +++++++++++---- docs/development.md | 8 +++-- tests/ci-workflow-check.py | 65 +++++++++++++++++++++++++---------- tests/ci-workflow.bats | 68 +++++++++++++++++++++++++++---------- 4 files changed, 125 insertions(+), 43 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 3f01823..844910f 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,11 +1,12 @@ name: Tests # Runs every bats suite listed under "Running Tests" in docs/development.md. -# Adding a suite means adding it to both that list and the matrix below; -# tests/ci-workflow.bats fails when they differ. That suite also requires -# this file to match EXPECTED in tests/ci-workflow-check.py, apart from the -# suite list and the action commit SHAs. Any other change to this file needs -# the same change there. +# The guard job always runs tests/ci-workflow.bats; the bats job runs every +# other suite from its matrix. Adding a suite means adding it to both that +# list and the matrix below; tests/ci-workflow.bats fails when they differ. +# That suite also requires this file to match EXPECTED in +# tests/ci-workflow-check.py, apart from the suite list and the action commit +# SHAs. Any other change to this file needs the same change there. on: # No branch filter: pull requests into any base branch run the suites. @@ -24,6 +25,21 @@ concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + # A fixed job rather than a matrix entry, so a change to the matrix cannot + # drop the check that compares the matrix with the docs. + guard: + name: bats tests/ci-workflow.bats + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: cachix/install-nix-action@382a9ed9481c7c1f94f68b72ef105b3417c73877 # v32.1.0 + with: + github_access_token: ${{ secrets.GITHUB_TOKEN }} + - name: Run suite + run: nix develop -c bats tests/ci-workflow.bats + bats: name: bats ${{ matrix.suite }} runs-on: ubuntu-latest @@ -32,7 +48,6 @@ jobs: matrix: suite: - tests/marketplace-package.bats - - tests/ci-workflow.bats - plugins/product-development/tests/plugin-package.bats - plugins/product-development/skills/product-development/tests/init.bats - plugins/delivery-engineering/tests/plugin-package.bats diff --git a/docs/development.md b/docs/development.md index 8cc8d59..ab060d9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -147,9 +147,11 @@ so CI uses the flake's pinned tool versions and a failing job names its suite. that pull request's running checks; runs for pushes to `main` never cancel or replace each other. -When you add a suite, add it to both the list above and the `suite` matrix in -the workflow. `tests/ci-workflow.bats` fails when the two differ, when this -section holds more than one code block, and when the block holds a command +`tests/ci-workflow.bats` runs in its own `guard` job instead of the matrix, so +an edit to the matrix cannot drop it. When you add a suite, add it to both the +list above and the `suite` matrix in the workflow. `tests/ci-workflow.bats` +fails when the list differs from the guard job's suite plus the matrix, when +this section holds more than one code block, and when the block holds a command other than `nix develop -c bats ` or `git diff --check`. Its checks live in `tests/ci-workflow-check.py`. diff --git a/tests/ci-workflow-check.py b/tests/ci-workflow-check.py index 901f9a3..a2e565c 100755 --- a/tests/ci-workflow-check.py +++ b/tests/ci-workflow-check.py @@ -6,8 +6,8 @@ Checks: shape the workflow equals EXPECTED, apart from the suite list and the action commit SHAs - suites the workflow matrix lists exactly the suites in the "Running - Tests" block of docs/development.md + suites the guard job and the workflow matrix together run exactly the + suites in the "Running Tests" block of docs/development.md pins every action is pinned to a full commit SHA with a `# v` comment @@ -80,6 +80,23 @@ def suite_list(value): return "expected a list of suite paths, found %r" % (value,) +# The suite that runs these checks. The guard job runs it on its own. +GUARD_SUITE = "tests/ci-workflow.bats" +GUARD_RUN = "nix develop -c bats " + GUARD_SUITE + + +def suite_steps(run_step): + """The steps every suite job runs: checkout, Nix, then `run_step`.""" + return [ + {"uses": pinned("actions/checkout"), "with": {"persist-credentials": False}}, + { + "uses": pinned("cachix/install-nix-action"), + "with": {"github_access_token": "${{ secrets.GITHUB_TOKEN }}"}, + }, + run_step, + ] + + # The one supported workflow. Every key and value must match exactly, # except the two placeholders: the matrix suite list (checked by `suites`) # and the action commit SHAs (checked by `pins`). To change anything else @@ -98,23 +115,25 @@ def suite_list(value): "cancel-in-progress": "${{ github.event_name == 'pull_request' }}", }, "jobs": { + # Runs the guard suite outside the matrix, so editing the matrix + # cannot drop it. + "guard": { + "name": "bats " + GUARD_SUITE, + "runs-on": "ubuntu-latest", + "steps": suite_steps({"name": "Run suite", "run": GUARD_RUN}), + }, "bats": { "name": "bats ${{ matrix.suite }}", "runs-on": "ubuntu-latest", "strategy": {"fail-fast": False, "matrix": {"suite": suite_list}}, - "steps": [ - {"uses": pinned("actions/checkout"), "with": {"persist-credentials": False}}, - { - "uses": pinned("cachix/install-nix-action"), - "with": {"github_access_token": "${{ secrets.GITHUB_TOKEN }}"}, - }, + "steps": suite_steps( { "name": "Run suite", "env": {"SUITE": "${{ matrix.suite }}"}, "run": 'nix develop -c bats "$SUITE"', - }, - ], - } + } + ), + }, }, } @@ -228,7 +247,18 @@ def duplicates(items): return sorted({item for item in items if items.count(item) > 1}) +def guard_suites(workflow): + """Returns [GUARD_SUITE] when the guard job's last step runs it, else [].""" + try: + run = workflow["jobs"]["guard"]["steps"][-1]["run"] + except (KeyError, IndexError, TypeError): + return [] + return [GUARD_SUITE] if run == GUARD_RUN else [] + + def check_suites(workflow, args): + """Compares the documented suites with the suites CI runs: the guard + job's suite plus the matrix.""" documented = documented_suites(args.doc) try: matrix = workflow["jobs"]["bats"]["strategy"]["matrix"]["suite"] @@ -237,20 +267,21 @@ def check_suites(workflow, args): problem = suite_list(matrix) if problem: raise CheckFailed("jobs.bats.strategy.matrix.suite: " + problem) + ci = guard_suites(workflow) + matrix problems = [] for suite in duplicates(documented): problems.append("listed twice in docs: %s" % suite) - for suite in duplicates(matrix): - problems.append("listed twice in the workflow matrix: %s" % suite) + for suite in duplicates(ci): + problems.append("run twice by the workflow: %s" % suite) for suite in documented: - if suite not in matrix: - problems.append("in docs but not in the workflow matrix: %s" % suite) + if suite not in ci: + problems.append("in docs but not run by the workflow: %s" % suite) if not (REPO_ROOT / suite).exists(): problems.append("documented suite does not exist: %s" % suite) - for suite in matrix: + for suite in ci: if suite not in documented: - problems.append("in the workflow matrix but not in docs: %s" % suite) + problems.append("run by the workflow but not in docs: %s" % suite) return problems diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats index 0c54530..c18c0db 100644 --- a/tests/ci-workflow.bats +++ b/tests/ci-workflow.bats @@ -50,8 +50,9 @@ print(target) PY } -# Prints the workflow matrix as `nix develop -c bats ` lines. -matrix_commands() { +# Prints the suites CI runs as `nix develop -c bats ` lines: the +# guard job's command, then one per matrix suite. +ci_commands() { python3 - "$WORKFLOW" <<'PY' import sys @@ -59,6 +60,7 @@ import yaml with open(sys.argv[1], encoding="utf-8") as handle: workflow = yaml.safe_load(handle) +print(workflow["jobs"]["guard"]["steps"][-1]["run"]) for suite in workflow["jobs"]["bats"]["strategy"]["matrix"]["suite"]: print("nix develop -c bats " + suite) PY @@ -161,9 +163,27 @@ assert_check_rejects() { assert_check_rejects "concurrency.cancel-in-progress: expected" shape "$workflow" } +@test "shape check rejects a workflow without the guard job" { + local workflow + workflow="$(mutated_workflow 'del w["jobs"]["guard"]')" + assert_check_rejects "jobs.guard: missing" shape "$workflow" +} + +@test "shape check rejects a guard job that runs another suite" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["guard"]["steps"][-1]["run"] = "nix develop -c bats tests/marketplace-package.bats"')" + assert_check_rejects "jobs.guard.steps[2].run: expected" shape "$workflow" +} + +@test "shape check rejects continue-on-error on the guard job" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["guard"]["continue-on-error"] = True')" + assert_check_rejects "jobs.guard.continue-on-error: unexpected key" shape "$workflow" +} + @test "shape check rejects a suite dropped by matrix.exclude" { local workflow - workflow="$(mutated_workflow 'w["jobs"]["bats"]["strategy"]["matrix"]["exclude"] = [{"suite": "tests/ci-workflow.bats"}]')" + workflow="$(mutated_workflow 'w["jobs"]["bats"]["strategy"]["matrix"]["exclude"] = [{"suite": "tests/marketplace-package.bats"}]')" assert_check_rejects "jobs.bats.strategy.matrix.exclude: unexpected key" shape "$workflow" } @@ -235,65 +255,65 @@ job["steps"][-1]["env"] = {"SUITE": "tests/ci-workflow.bats"} assert_check_passes suites } -@test "suites check passes on a docs block built from the matrix" { +@test "suites check passes on a docs block built from the CI suites" { local doc - doc="$(doc_with "$(printf '```bash\n%s\ngit diff --check\n```' "$(matrix_commands)")")" + doc="$(doc_with "$(printf '```bash\n%s\ngit diff --check\n```' "$(ci_commands)")")" assert_check_passes suites "$WORKFLOW" "$doc" } @test "suites check reads a tilde-fenced docs block" { local doc - doc="$(doc_with "$(printf '~~~bash\n%s\n~~~' "$(matrix_commands)")")" + doc="$(doc_with "$(printf '~~~bash\n%s\n~~~' "$(ci_commands)")")" assert_check_passes suites "$WORKFLOW" "$doc" } @test "suites check rejects a second backtick-fenced block" { local doc - doc="$(doc_with "$(printf '```bash\n%s\n```\n\n```bash\nnix develop -c bats tests/not-in-ci.bats\n```' "$(matrix_commands)")")" + doc="$(doc_with "$(printf '```bash\n%s\n```\n\n```bash\nnix develop -c bats tests/not-in-ci.bats\n```' "$(ci_commands)")")" assert_check_rejects "exactly one code block, found 2" suites "$WORKFLOW" "$doc" } @test "suites check rejects a second tilde-fenced block" { local doc - doc="$(doc_with "$(printf '```bash\n%s\n```\n\n~~~bash\nnix develop -c bats tests/not-in-ci.bats\n~~~' "$(matrix_commands)")")" + doc="$(doc_with "$(printf '```bash\n%s\n```\n\n~~~bash\nnix develop -c bats tests/not-in-ci.bats\n~~~' "$(ci_commands)")")" assert_check_rejects "exactly one code block, found 2" suites "$WORKFLOW" "$doc" } @test "suites check rejects a second block in a subsection" { local doc - doc="$(doc_with "$(printf '```bash\n%s\n```\n\n### More\n\n```bash\nnix develop -c bats tests/not-in-ci.bats\n```' "$(matrix_commands)")")" + doc="$(doc_with "$(printf '```bash\n%s\n```\n\n### More\n\n```bash\nnix develop -c bats tests/not-in-ci.bats\n```' "$(ci_commands)")")" assert_check_rejects "exactly one code block, found 2" suites "$WORKFLOW" "$doc" } @test "suites check closes a fence only with the same delimiter" { local doc - doc="$(doc_with "$(printf '~~~bash\n%s\n```\nnix develop -c bats tests/not-in-ci.bats\n~~~' "$(matrix_commands)")")" + doc="$(doc_with "$(printf '~~~bash\n%s\n```\nnix develop -c bats tests/not-in-ci.bats\n~~~' "$(ci_commands)")")" assert_check_rejects "unrecognized command in Running Tests: '\`\`\`'" suites "$WORKFLOW" "$doc" } @test "suites check rejects an unclosed fence" { local doc - doc="$(doc_with "$(printf '~~~bash\n%s' "$(matrix_commands)")")" + doc="$(doc_with "$(printf '~~~bash\n%s' "$(ci_commands)")")" assert_check_rejects "unclosed code fence" suites "$WORKFLOW" "$doc" } @test "suites check rejects a documented suite missing from the matrix" { local doc - doc="$(doc_with "$(printf '```bash\n%s\nnix develop -c bats tests/missing.bats\n```' "$(matrix_commands)")")" - assert_check_rejects "in docs but not in the workflow matrix: tests/missing.bats" \ + doc="$(doc_with "$(printf '```bash\n%s\nnix develop -c bats tests/missing.bats\n```' "$(ci_commands)")")" + assert_check_rejects "in docs but not run by the workflow: tests/missing.bats" \ suites "$WORKFLOW" "$doc" } @test "suites check reads indented suite lines in the docs block" { local doc - doc="$(doc_with "$(printf '```bash\n%s\n nix develop -c bats tests/indented.bats\n```' "$(matrix_commands)")")" - assert_check_rejects "in docs but not in the workflow matrix: tests/indented.bats" \ + doc="$(doc_with "$(printf '```bash\n%s\n nix develop -c bats tests/indented.bats\n```' "$(ci_commands)")")" + assert_check_rejects "in docs but not run by the workflow: tests/indented.bats" \ suites "$WORKFLOW" "$doc" } @test "suites check rejects an unrecognized command in the docs block" { local doc - doc="$(doc_with "$(printf '```bash\n%s\nnix develop --command bats tests/other.bats\n```' "$(matrix_commands)")")" + doc="$(doc_with "$(printf '```bash\n%s\nnix develop --command bats tests/other.bats\n```' "$(ci_commands)")")" assert_check_rejects "unrecognized command in Running Tests: 'nix develop --command bats tests/other.bats'" \ suites "$WORKFLOW" "$doc" } @@ -301,7 +321,21 @@ job["steps"][-1]["env"] = {"SUITE": "tests/ci-workflow.bats"} @test "suites check rejects a matrix suite missing from docs" { local workflow workflow="$(mutated_workflow 'w["jobs"]["bats"]["strategy"]["matrix"]["suite"].append("tests/undocumented.bats")')" - assert_check_rejects "in the workflow matrix but not in docs: tests/undocumented.bats" \ + assert_check_rejects "run by the workflow but not in docs: tests/undocumented.bats" \ + suites "$workflow" +} + +@test "suites check rejects a documented guard suite with no guard job" { + local workflow + workflow="$(mutated_workflow 'del w["jobs"]["guard"]')" + assert_check_rejects "in docs but not run by the workflow: tests/ci-workflow.bats" \ + suites "$workflow" +} + +@test "suites check rejects the guard suite also listed in the matrix" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["bats"]["strategy"]["matrix"]["suite"].append("tests/ci-workflow.bats")')" + assert_check_rejects "run twice by the workflow: tests/ci-workflow.bats" \ suites "$workflow" } From ce5a8ca5982a1e12ea8352268d46a94c78dd113d Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 16:00:14 -0500 Subject: [PATCH 13/14] test(ci): reject option-like and non-bats suite paths A documented or matrix suite path reaches bats as an argument, so a leading '-' would be read as an option, and a path to a non-bats file or an empty directory runs no tests. - The suites check rejects any documented or CI suite path that starts with '-', is absolute or contains '..', or is neither a .bats file nor a directory with a .bats file directly inside it (bats does not recurse). This replaces the docs-only existence check. - Add fixtures for each rejection, in the docs and in the matrix. - Document the path rule in docs/development.md. Refs #40 --- docs/development.md | 6 ++++-- tests/ci-workflow-check.py | 26 ++++++++++++++++++++++-- tests/ci-workflow.bats | 41 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 4 deletions(-) diff --git a/docs/development.md b/docs/development.md index ab060d9..b8e20cf 100644 --- a/docs/development.md +++ b/docs/development.md @@ -152,8 +152,10 @@ an edit to the matrix cannot drop it. When you add a suite, add it to both the list above and the `suite` matrix in the workflow. `tests/ci-workflow.bats` fails when the list differs from the guard job's suite plus the matrix, when this section holds more than one code block, and when the block holds a command -other than `nix develop -c bats ` or `git diff --check`. Its checks live -in `tests/ci-workflow-check.py`. +other than `nix develop -c bats ` or `git diff --check`. Each suite path +must be a repository-relative `.bats` file, or a directory with `.bats` files +directly inside, and must not start with `-`. Its checks live in +`tests/ci-workflow-check.py`. The guard also requires the workflow to match `EXPECTED` in `tests/ci-workflow-check.py` exactly, apart from the suite list and the action diff --git a/tests/ci-workflow-check.py b/tests/ci-workflow-check.py index a2e565c..ea629ad 100755 --- a/tests/ci-workflow-check.py +++ b/tests/ci-workflow-check.py @@ -277,14 +277,36 @@ def check_suites(workflow, args): for suite in documented: if suite not in ci: problems.append("in docs but not run by the workflow: %s" % suite) - if not (REPO_ROOT / suite).exists(): - problems.append("documented suite does not exist: %s" % suite) for suite in ci: if suite not in documented: problems.append("run by the workflow but not in docs: %s" % suite) + for suite in dict.fromkeys(documented + ci): + problem = suite_path_problem(suite) + if problem: + problems.append("%s: %s" % (problem, suite)) return problems +def suite_path_problem(suite): + """Returns why `suite` is not a valid suite path, or None. + + A suite is a repository-relative path to a `.bats` file, or to a + directory with a `.bats` file directly inside it (bats runs only those, + not subdirectories). A leading `-` would reach bats as an option. + """ + if suite.startswith("-"): + return "suite path starts with '-'" + path = pathlib.PurePosixPath(suite) + if path.is_absolute() or ".." in path.parts: + return "suite path is not repository-relative" + full = REPO_ROOT / path + if full.is_file() and full.suffix == ".bats": + return None + if full.is_dir() and any(full.glob("*.bats")): + return None + return "not a .bats file or a directory holding .bats files" + + PINNED_ACTION = re.compile(r"[\w.-]+/[\w./-]+@[0-9a-f]{40}") VERSION_COMMENT = re.compile(r"(?:^|\s)#\s*v\d") diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats index c18c0db..93d74ce 100644 --- a/tests/ci-workflow.bats +++ b/tests/ci-workflow.bats @@ -325,6 +325,47 @@ job["steps"][-1]["env"] = {"SUITE": "tests/ci-workflow.bats"} suites "$workflow" } +@test "suites check rejects an option-like path in the docs block" { + local doc + doc="$(doc_with "$(printf '```bash\n%s\nnix develop -c bats --tap\n```' "$(ci_commands)")")" + assert_check_rejects "suite path starts with '-': --tap" suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects an option-like path in the matrix" { + local workflow + workflow="$(mutated_workflow 'w["jobs"]["bats"]["strategy"]["matrix"]["suite"].append("--tap")')" + assert_check_rejects "suite path starts with '-': --tap" suites "$workflow" +} + +@test "suites check rejects an absolute suite path" { + local doc + doc="$(doc_with "$(printf '```bash\n%s\nnix develop -c bats %s\n```' "$(ci_commands)" "$REPO_ROOT/tests/ci-workflow.bats")")" + assert_check_rejects "suite path is not repository-relative: $REPO_ROOT/tests/ci-workflow.bats" \ + suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects a suite path outside the repository" { + local doc + doc="$(doc_with "$(printf '```bash\n%s\nnix develop -c bats ../tests/ci-workflow.bats\n```' "$(ci_commands)")")" + assert_check_rejects "suite path is not repository-relative: ../tests/ci-workflow.bats" \ + suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects a suite path that is not a .bats file" { + local doc + doc="$(doc_with "$(printf '```bash\n%s\nnix develop -c bats docs/development.md\n```' "$(ci_commands)")")" + assert_check_rejects "not a .bats file or a directory holding .bats files: docs/development.md" \ + suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects a directory with no .bats file directly inside" { + local doc + [ -z "$(compgen -G "$REPO_ROOT/docs/*.bats")" ] + doc="$(doc_with "$(printf '```bash\n%s\nnix develop -c bats docs\n```' "$(ci_commands)")")" + assert_check_rejects "not a .bats file or a directory holding .bats files: docs" \ + suites "$WORKFLOW" "$doc" +} + @test "suites check rejects a documented guard suite with no guard job" { local workflow workflow="$(mutated_workflow 'del w["jobs"]["guard"]')" From eab509d6758d74a220dbae96b95be2bba22be053 Mon Sep 17 00:00:00 2001 From: John Lianoglou Date: Sun, 29 Nov 2026 16:00:54 -0500 Subject: [PATCH 14/14] test(ci): generate fixture suite paths absent from the real suites The negative fixtures used fixed names (tests/undocumented.bats, tests/missing.bats, tests/indented.bats), which would break the tests if a real suite with one of those names were added. - Add absent_suite, which picks tests/-.bats for the lowest that the workflow and docs never mention and that does not exist. - Use it in the fixtures that add an undocumented, missing or indented suite, and add a fixture for a documented suite that does not exist. Refs #40 --- tests/ci-workflow.bats | 40 +++++++++++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats index 93d74ce..b8ed165 100644 --- a/tests/ci-workflow.bats +++ b/tests/ci-workflow.bats @@ -66,6 +66,17 @@ for suite in workflow["jobs"]["bats"]["strategy"]["matrix"]["suite"]: PY } +# Prints tests/-.bats for the lowest that the workflow and +# docs never mention and that does not exist, so a fixture suite cannot +# collide with a real one. +absent_suite() { + local n=0 + while grep -qF -- "tests/$1-$n.bats" "$WORKFLOW" "$DEV_DOC" || [ -e "$REPO_ROOT/tests/$1-$n.bats" ]; do + n=$((n + 1)) + done + echo "tests/$1-$n.bats" +} + # Writes $BATS_TEST_TMPDIR/development.md with as the whole # "Running Tests" section and prints its path. doc_with() { @@ -298,16 +309,26 @@ job["steps"][-1]["env"] = {"SUITE": "tests/ci-workflow.bats"} } @test "suites check rejects a documented suite missing from the matrix" { - local doc - doc="$(doc_with "$(printf '```bash\n%s\nnix develop -c bats tests/missing.bats\n```' "$(ci_commands)")")" - assert_check_rejects "in docs but not run by the workflow: tests/missing.bats" \ + local suite doc + suite="$(absent_suite missing)" + doc="$(doc_with "$(printf '```bash\n%s\nnix develop -c bats %s\n```' "$(ci_commands)" "$suite")")" + assert_check_rejects "in docs but not run by the workflow: $suite" \ + suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects a documented suite that does not exist" { + local suite doc + suite="$(absent_suite missing)" + doc="$(doc_with "$(printf '```bash\n%s\nnix develop -c bats %s\n```' "$(ci_commands)" "$suite")")" + assert_check_rejects "not a .bats file or a directory holding .bats files: $suite" \ suites "$WORKFLOW" "$doc" } @test "suites check reads indented suite lines in the docs block" { - local doc - doc="$(doc_with "$(printf '```bash\n%s\n nix develop -c bats tests/indented.bats\n```' "$(ci_commands)")")" - assert_check_rejects "in docs but not run by the workflow: tests/indented.bats" \ + local suite doc + suite="$(absent_suite indented)" + doc="$(doc_with "$(printf '```bash\n%s\n nix develop -c bats %s\n```' "$(ci_commands)" "$suite")")" + assert_check_rejects "in docs but not run by the workflow: $suite" \ suites "$WORKFLOW" "$doc" } @@ -319,9 +340,10 @@ job["steps"][-1]["env"] = {"SUITE": "tests/ci-workflow.bats"} } @test "suites check rejects a matrix suite missing from docs" { - local workflow - workflow="$(mutated_workflow 'w["jobs"]["bats"]["strategy"]["matrix"]["suite"].append("tests/undocumented.bats")')" - assert_check_rejects "run by the workflow but not in docs: tests/undocumented.bats" \ + local suite workflow + suite="$(absent_suite undocumented)" + workflow="$(mutated_workflow "w['jobs']['bats']['strategy']['matrix']['suite'].append('$suite')")" + assert_check_rejects "run by the workflow but not in docs: $suite" \ suites "$workflow" }