diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..844910f --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,66 @@ +name: Tests + +# Runs every bats suite listed under "Running Tests" in docs/development.md. +# 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. + pull_request: + push: + branches: [main] + +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.event_name == 'pull_request' && github.ref || github.run_id }} + 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 + strategy: + fail-fast: false + matrix: + suite: + - tests/marketplace-package.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/.gitignore b/.gitignore index 4662664..e19eb3c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .direnv/ - +__pycache__/ +*.pyc diff --git a/docs/development.md b/docs/development.md index 7414e4a..b8e20cf 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 @@ -136,6 +137,37 @@ 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. 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. + +`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`. 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 +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`. + ## Repository Structure ```text @@ -144,8 +176,12 @@ 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-check.py +│ ├── ci-workflow.bats +│ └── marketplace-package.bats └── plugins/ ├── product-development/ │ ├── plugin.json diff --git a/tests/ci-workflow-check.py b/tests/ci-workflow-check.py new file mode 100755 index 0000000..ea629ad --- /dev/null +++ b/tests/ci-workflow-check.py @@ -0,0 +1,381 @@ +#!/usr/bin/env python3 +"""Checks .github/workflows/tests.yml against docs/development.md. + +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 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 + +Each check prints one line per problem and exits 1 when it finds any. +tests/ci-workflow.bats runs every check against the real files and against +broken ones. +""" + +import argparse +import pathlib +import re +import sys + +import yaml + +REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent + + +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.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 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 +# 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": { + # 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": suite_steps( + { + "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"} + +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-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: + 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) + + blocks, block, fence = [], None, None + for line in lines[start + 1 :]: + 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") + 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 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"] + 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) + ci = guard_suites(workflow) + matrix + + problems = [] + for suite in duplicates(documented): + problems.append("listed twice in docs: %s" % suite) + for suite in duplicates(ci): + problems.append("run twice by the workflow: %s" % suite) + for suite in documented: + if suite not in ci: + problems.append("in docs but not run by the workflow: %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") + + +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 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 `# v` comment after it on the same line. + + 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") + lines = text.splitlines() + nodes = list(uses_nodes(yaml.compose(text, Loader=Loader))) + if not nodes: + return ["no action references (uses) found"] + problems = [] + 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) + 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 + + +CHECKS = { + "pins": check_pins, + "shape": check_shape, + "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)] + 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 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/ci-workflow.bats b/tests/ci-workflow.bats new file mode 100644 index 0000000..b8ed165 --- /dev/null +++ b/tests/ci-workflow.bats @@ -0,0 +1,464 @@ +#!/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" +CHECK="$REPO_ROOT/tests/ci-workflow-check.py" + +# Importing the checker would otherwise write tests/__pycache__/. +export PYTHONDONTWRITEBYTECODE=1 + +# 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}" +} + +# A placeholder commit SHA for standalone pins fixtures. +SHA=0123456789abcdef0123456789abcdef01234567 + +# 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 +# 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 +} + +# 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 + +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 +} + +# 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() { + 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 "$@" + [ "$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" { + [ -f "$WORKFLOW" ] +} + +@test "workflow matches the expected shape" { + assert_check_passes shape +} + +@test "an unchanged round trip of the workflow passes the shape check" { + local workflow + workflow="$(mutated_workflow 'pass')" + assert_check_passes shape "$workflow" +} + +@test "shape check rejects a pull_request branch filter" { + local workflow + workflow="$(mutated_workflow 'w["on"]["pull_request"] = {"branches": ["main"]}')" + assert_check_rejects "on.pull_request: expected None" shape "$workflow" +} + +@test "shape check rejects pull_request activity types" { + local workflow + workflow="$(mutated_workflow 'w["on"]["pull_request"] = {"types": ["opened"]}')" + assert_check_rejects "on.pull_request: expected None" shape "$workflow" +} + +@test "shape check rejects a push trigger on another branch" { + local workflow + workflow="$(mutated_workflow 'w["on"]["push"]["branches"] = ["develop"]')" + assert_check_rejects "on.push.branches[0]: expected 'main', found 'develop'" shape "$workflow" +} + +@test "shape check rejects a push path filter" { + local 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 "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 "shape check rejects one concurrency group shared by all pushes to main" { + local workflow + workflow="$(mutated_workflow 'w["concurrency"]["group"] = "${{ github.workflow }}-${{ github.ref }}"')" + assert_check_rejects "concurrency.group: expected" shape "$workflow" +} + +@test "shape check rejects an event name compared in another case" { + local 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 "shape check rejects pull request runs that do not cancel" { + local 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 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/marketplace-package.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" { + assert_check_passes suites +} + +@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```' "$(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~~~' "$(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```' "$(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~~~' "$(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```' "$(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~~~' "$(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' "$(ci_commands)")")" + assert_check_rejects "unclosed code fence" suites "$WORKFLOW" "$doc" +} + +@test "suites check rejects a documented suite missing from the matrix" { + 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 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" +} + +@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```' "$(ci_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" { + 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" +} + +@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"]')" + 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" +} + +@test "suites check fails when docs have no Running Tests section" { + 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" +} + +@test "third-party actions are pinned to full commit SHAs with a version comment" { + 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="$(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="$(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="$(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="$(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" +}