diff --git a/.github/actions/review/action.yml b/.github/actions/review/action.yml new file mode 100644 index 0000000..13ed91d --- /dev/null +++ b/.github/actions/review/action.yml @@ -0,0 +1,29 @@ +name: Review +description: >- + The required Review check of a pull request. It passes when the PR is ready + for review, every job the calling job needs succeeded and each listed + Netlify preview of the head built. A CloudCannon publication then gets + GitHub's auto-merge, which merges it once the required checks pass. +inputs: + needs: + description: The calling job's needs, as toJSON(needs). + required: true + netlify-checks: + description: JSON array of the Netlify status contexts the PR head must report as success. + default: "[]" + timeout-minutes: + description: How long to wait for the previews. + default: "15" +runs: + using: composite + steps: + - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + env: + ACTION_PATH: ${{ github.action_path }} + NEEDS: ${{ inputs.needs }} + NETLIFY_CHECKS: ${{ inputs.netlify-checks }} + TIMEOUT_MINUTES: ${{ inputs.timeout-minutes }} + with: + script: | + const review = require(`${process.env.ACTION_PATH}/review.cjs`) + await review({github, context, core, env: process.env}) diff --git a/.github/actions/review/review.cjs b/.github/actions/review/review.cjs new file mode 100644 index 0000000..856c831 --- /dev/null +++ b/.github/actions/review/review.cjs @@ -0,0 +1,61 @@ +// The Review check (action.yml). It runs as a job of the pull request's own +// workflow, so a new push cancels it and a rerun resets it. +module.exports = async ({github, context, core, env, sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), now = Date.now}) => { + const pull = context.payload.pull_request; + if (!pull) throw new Error('Review runs on pull_request events only.'); + // A skipped required check counts as passed, so a draft fails instead. + if (pull.draft) return core.setFailed('A draft is not reviewed. Mark the PR ready for review.'); + + // So does a skipped, cancelled or failed job, and a caller that names none. + const needs = JSON.parse(env.NEEDS || '{}'); + if (!Object.keys(needs).length) return core.setFailed('Review needs the jobs it reviews, as toJSON(needs).'); + const unfinished = Object.entries(needs).filter(([, job]) => job.result !== 'success') + .map(([name, job]) => `${name} (${job.result})`); + if (unfinished.length) return core.setFailed(`Did not succeed: ${unfinished.join(', ')}.`); + + // Netlify reports each preview as a commit status of the head, often after + // the checks. A skipped preview reports success too. + const {owner, repo} = context.repo; + const sha = pull.head.sha; + const previews = JSON.parse(env.NETLIFY_CHECKS || '[]'); + const minutes = Number(env.TIMEOUT_MINUTES || 15); + const deadline = now() + minutes * 60_000; + for (;;) { + const {data} = await github.rest.repos.getCombinedStatusForRef({owner, repo, ref: sha, per_page: 100}); + const state = name => data.statuses.find(status => status.context === name)?.state; + const failed = previews.filter(name => ['error', 'failure'].includes(state(name))); + if (failed.length) return core.setFailed(`Preview failed: ${failed.join(', ')}.`); + const waiting = previews.filter(name => state(name) !== 'success'); + if (!waiting.length) break; + if (now() > deadline) { + return core.setFailed(`Previews did not finish within ${minutes} minutes: ${waiting.join(', ')}. Re-run Review once they have.`); + } + core.info(`Waiting for ${waiting.join(', ')}`); + await sleep(15_000); + } + + // CloudCannon's Publish button opens a same-repository PR from `preview`; + // GitHub merges it once the required checks pass. Without auto-merge it + // would wait unseen, so a refusal fails Review. + const publication = pull.user?.login === 'cloudcannon[bot]' && pull.head.ref === 'preview' + && pull.head.repo?.full_name === `${owner}/${repo}`; + if (!publication) return; + // The PR may have changed while Review waited for the previews. + const {data: current} = await github.rest.pulls.get({owner, repo, pull_number: pull.number}); + if (current.state !== 'open' || current.draft || current.head.sha !== sha || current.base.ref !== pull.base.ref) { + return core.setFailed('The PR changed while Review waited. Re-run Review.'); + } + if (current.auto_merge) { + if (current.auto_merge.merge_method === 'merge') return; + return core.setFailed(`Auto-merge is on as ${current.auto_merge.merge_method}; a publication from preview merges with a merge commit.`); + } + try { + await github.graphql(`mutation($id: ID!, $sha: GitObjectID!) { + enablePullRequestAutoMerge(input: {pullRequestId: $id, expectedHeadOid: $sha, mergeMethod: MERGE}) { + pullRequest { number } + } + }`, {id: pull.node_id, sha}); + } catch (error) { + core.setFailed(`Auto-merge could not be turned on, so this publication would not merge: ${error.message}`); + } +}; diff --git a/.github/workflows/ci-check.yml b/.github/workflows/ci-check.yml index ec541ad..710012c 100644 --- a/.github/workflows/ci-check.yml +++ b/.github/workflows/ci-check.yml @@ -1,7 +1,6 @@ name: Check on: - workflow_dispatch: push: branches: [main] pull_request: @@ -12,7 +11,7 @@ permissions: contents: read concurrency: - group: check-${{ github.event.pull_request.number || github.ref }}-${{ github.event.pull_request.draft && 'draft' || 'ready' }} + group: check-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true jobs: @@ -22,3 +21,21 @@ jobs: with: install: false command: node --test tests/*.test.mjs + + review: + name: Review + if: ${{ always() && github.event_name == 'pull_request' }} + needs: [check] + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + statuses: read + steps: + # This repository tests the action of its own PR; other callers pin it. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: ./.github/actions/review + with: + needs: ${{ toJSON(needs) }} diff --git a/.github/workflows/ci-ready.yml b/.github/workflows/ci-ready.yml deleted file mode 100644 index 09bd102..0000000 --- a/.github/workflows/ci-ready.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Ready - -on: - pull_request_target: - branches: [main] - types: [opened, synchronize, reopened, ready_for_review, converted_to_draft] - workflow_run: - workflows: [Check] - types: [completed] - -permissions: - actions: read - contents: write - pull-requests: write - statuses: write - checks: read - -jobs: - ready: - uses: ./.github/workflows/ready.yml diff --git a/.github/workflows/ready.yml b/.github/workflows/ready.yml deleted file mode 100644 index 2ead6b8..0000000 --- a/.github/workflows/ready.yml +++ /dev/null @@ -1,239 +0,0 @@ -name: Ready - -on: - workflow_call: - inputs: - runner: - type: string - default: blacksmith-2vcpu-ubuntu-2404 - netlify-checks: - type: string - default: "[]" - check-name: - type: string - default: Check / Check - test-checks: - type: string - default: "[]" - merge-app-client-id: - type: string - default: "" - secrets: - merge-app-private-key: - required: false - -permissions: - actions: read - contents: write - pull-requests: write - statuses: write - checks: read - -concurrency: - group: ready-policy-${{ github.repository }} - cancel-in-progress: false - -jobs: - ready: - name: Ready - runs-on: ${{ vars.CI_RUNNER || (github.event.repository.private == false && 'ubuntu-24.04') || inputs.runner }} - timeout-minutes: 3 - steps: - - name: Create merge token for repositories with release workflows - if: ${{ inputs.merge-app-client-id != '' }} - id: merge-token - uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 - with: - client-id: ${{ inputs.merge-app-client-id }} - private-key: ${{ secrets.merge-app-private-key }} - owner: ${{ github.repository_owner }} - repositories: ${{ github.event.repository.name }} - # Only the merge uses this token, so existing push-triggered releases still run. - # Only GitHub metadata is read. Never check out or execute PR code here. - - name: Reconcile publication requirements - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 - env: - NETLIFY_CHECKS: ${{ inputs.netlify-checks }} - CHECK_NAME: ${{ inputs.check-name }} - TEST_CHECKS: ${{ inputs.test-checks }} - MERGE_TOKEN: ${{ steps.merge-token.outputs.token }} - with: - script: | - const {owner, repo} = context.repo; - const repository = (await github.rest.repos.get({owner, repo})).data; - const candidates = await github.paginate(github.rest.pulls.list, {owner, repo, state: 'open', - base: repository.default_branch, per_page: 100}); - async function mergeRequest(path, method, body) { - const response = await fetch(`${process.env.GITHUB_API_URL}${path}`, { - method, headers: {Authorization: `Bearer ${process.env.MERGE_TOKEN}`, - Accept: 'application/vnd.github+json', 'Content-Type': 'application/json', - 'X-GitHub-Api-Version': '2022-11-28'}, body: JSON.stringify(body)}); - const result = await response.json(); - if (!response.ok || result.errors) { - throw new Error(`Merge request failed (${response.status}): ${result.message ?? 'GraphQL error'}`); - } - return result; - } - async function processPull(number) { - const getPull = async () => (await github.rest.pulls.get({owner, repo, pull_number: number})).data; - const pull = await getPull(); - if (pull.state !== 'open' || pull.base.ref !== repository.default_branch) return; - const sha = pull.head.sha; - const requiredTests = JSON.parse(process.env.TEST_CHECKS || '[]'); - const reviewTarget = {owner, repo, sha, context: 'Review', target_url: pull.html_url}; - let review; - async function setReview(state, description) { - // Pending already blocks publication, regardless of its wording. - if (review?.state === state && (state === 'pending' || review.description === description)) return; - await github.rest.repos.createCommitStatus({...reviewTarget, state, description}); - review = {state, description}; - } - try { - const result = await github.rest.repos.getCombinedStatusForRef({owner, repo, ref: sha, per_page: 100}); - review = result.data.statuses.find(status => status.context === 'Review'); - } catch (error) { - // A failed status read must not leave a previous success in force. - await setReview('pending', 'Unable to verify the current Review status.'); - throw error; - } - if (pull.draft) { - await setReview('pending', 'Draft: publication is not authorized.'); - return; - } - // Every event reconciles every open PR, and GitHub refuses more than 1000 - // statuses per commit and context. Block an old success before checking - // only when the event concerns this PR, such as a Test rerun of its head. - const {payload} = context; - const ownEvent = payload.pull_request?.number === number - || payload.workflow_run?.head_sha === sha || payload.sha === sha; - if (requiredTests.length && ownEvent) await setReview('pending', 'Checking the current Test run and attempt.'); - async function testsPassed() { - if (!requiredTests.length) return true; - // Read the current run and attempt on every event. Check runs can - // still show a previous success while the workflow is rerunning. - const event = context.payload.workflow_run; - let completedRunPending = false; - for (let retry = 0; retry < 4; retry++) { - const runs = await github.paginate(github.rest.actions.listWorkflowRunsForRepo, - {owner, repo, head_sha: sha, event: 'pull_request', per_page: 100}); - const run = runs.filter(run => run.name === 'Test' && run.head_sha === sha - && run.path === '.github/workflows/test.yml') - .sort((a, b) => b.id - a.id)[0]; - const eventIsNewer = event?.name === 'Test' && event.head_sha === sha - && (!run || event.id > run.id || (event.id === run.id - && event.run_attempt > run.run_attempt)); - const eventIsCurrent = event?.name === 'Test' && event.head_sha === sha - && run && event.id === run.id && event.run_attempt === run.run_attempt; - const completedEvent = (eventIsNewer || eventIsCurrent) - && event.status === 'completed' && event.conclusion === 'success'; - completedRunPending = completedEvent - || (run?.status === 'completed' && run.conclusion === 'success'); - if (eventIsNewer) { - if (!completedEvent) return false; - } else if (run) { - if (run.status === 'completed' && run.conclusion === 'success') { - const jobs = await github.paginate(github.rest.actions.listJobsForWorkflowRunAttempt, - {owner, repo, run_id: run.id, attempt_number: run.run_attempt, per_page: 100}); - if (requiredTests.every(name => jobs.some(job => job.name === name - && job.status === 'completed' && job.conclusion === 'success'))) return true; - } else if (!completedEvent) return false; - } - // Successful completion can precede its jobs' metadata. Retry - // briefly so a final completion event cannot strand the PR. - if (retry < 3) await new Promise(resolve => setTimeout(resolve, 2000)); - } - if (completedRunPending) throw new Error('Successful Test metadata is still incomplete. Rerun Ready to reconcile it.'); - return false; - } - // Every Netlify preview of the revision built, so no organization rule names a site. - async function previewsPassed() { - const names = JSON.parse(process.env.NETLIFY_CHECKS || '[]'); - if (!names.length) return true; - const {data} = await github.rest.repos.getCombinedStatusForRef({owner, repo, ref: sha, per_page: 100}); - return names.every(name => data.statuses.find(status => status.context === name)?.state === 'success'); - } - let previews, reviewPassed; - try { - const approved = await testsPassed(); - previews = await previewsPassed(); - const current = await getPull(); - if (current.state !== 'open' || current.base.ref !== pull.base.ref - || current.head.sha !== sha || current.draft !== pull.draft) { - // The change's own event reconciles it; an old success must not stay meanwhile. - if (review?.state === 'success') await setReview('pending', 'The PR changed while it was checked.'); - return; - } - reviewPassed = !pull.draft && approved && previews && await testsPassed(); - } catch (error) { - // A failed read must not leave a previous success in force. - await setReview('pending', 'Unable to verify the Ready requirements of this revision.'); - throw error; - } - await setReview(reviewPassed ? 'success' : 'pending', reviewPassed - ? 'Ready requirements passed for this revision.' - : previews ? 'Waiting for required tests of this revision.' - : 'Waiting for the Netlify previews of this revision.'); - if (!reviewPassed) return; - // Agents own code merges so they can follow the production deployment. - // Keep the customer's CloudCannon Publish button automatic. - const isCloudCannonPublication = candidate => candidate.user?.type === 'Bot' - && candidate.user.login === 'cloudcannon[bot]' - && candidate.head.ref === 'preview' - && candidate.head.repo?.full_name === repository.full_name - && candidate.base.repo?.full_name === repository.full_name; - if (!isCloudCannonPublication(pull)) return core.info('Ready for the agent to merge and verify production.'); - // Workflow events can create jobs out of order. Compare the originating run first. - // A skipped draft Check must never authorize automatic publication. - const checks = await github.paginate(github.rest.checks.listForRef, {owner, repo, ref: sha, per_page: 100}); - const candidates = checks.filter(run => run.name === process.env.CHECK_NAME && run.app?.id === 15368); - const runId = check => Number(check.details_url?.match(/\/actions\/runs\/(\d+)(?:\/|$)/)?.[1]); - if (candidates.some(run => !runId(run))) return core.info('Waiting for comparable Ready Check metadata.'); - const check = candidates.sort((a, b) => runId(b) - runId(a) || b.id - a.id)[0]; - if (check?.conclusion !== 'success') return core.info('Waiting for a successful Ready Check.'); - // Rollout must install central requirements before enabling auto-merge. - const {data: rules} = await github.request('GET /repos/{owner}/{repo}/rules/branches/{branch}', - {owner, repo, branch: pull.base.ref}); - const required = rules.filter(rule => rule.type === 'required_status_checks') - .flatMap(rule => rule.parameters.required_status_checks.map(status => status.context)); - if (![process.env.CHECK_NAME, 'Review'].every(name => required.includes(name))) { - return core.info('The central Check and Review requirements are not active yet.'); - } - if (!repository.allow_auto_merge) return core.info('Repository auto-merge is not enabled yet.'); - const final = await getPull(); - if (final.state !== 'open' || final.draft || final.base.ref !== pull.base.ref || final.head.sha !== sha) return; - if (!isCloudCannonPublication(final)) return; - if (!await testsPassed()) { - await setReview('pending', 'Waiting for required tests of this revision.'); - return; - } - const method = final.head.ref === 'preview' && final.head.repo?.full_name === final.base.repo?.full_name - ? 'merge' : 'squash'; - // Unrequired failed jobs can make GitHub report unstable; required rules still enforce this merge. - if (['clean', 'unstable'].includes(final.mergeable_state)) { - if (process.env.MERGE_TOKEN) { - await mergeRequest(`/repos/${owner}/${repo}/pulls/${number}/merge`, 'PUT', {sha, merge_method: method}); - } else { - await github.rest.pulls.merge({owner, repo, pull_number: number, sha, merge_method: method}); - } - return; - } - if (final.auto_merge) return core.info('Auto-merge is already enabled.'); - const mutation = `mutation($id: ID!, $sha: GitObjectID!, $mergeMethod: PullRequestMergeMethod!) { - enablePullRequestAutoMerge(input: {pullRequestId: $id, expectedHeadOid: $sha, mergeMethod: $mergeMethod}) { - pullRequest { number } - } - }`; - const variables = {id: final.node_id, sha, mergeMethod: method.toUpperCase()}; - if (process.env.MERGE_TOKEN) await mergeRequest('/graphql', 'POST', {query: mutation, variables}); - else await github.graphql(mutation, variables); - } - let failed = false; - for (const pull of candidates) { - try { - await processPull(pull.number); - } catch (error) { - failed = true; - core.error(`PR #${pull.number}: ${error.message}`); - } - } - if (failed) core.setFailed('Some PRs could not be reconciled; see their errors above.'); diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 05f03cc..ed9bfa8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -138,8 +138,11 @@ jobs: let baseline; try { baseline = git(['merge-base', pull.base.sha, sha]); } catch { core.info('No PR baseline available; test every deployment.'); } - // Test changes must exercise the new tests on every declared target. - const testChanges = !baseline || git(['diff', '--name-only', baseline, sha, '--', 'tests', '.github/workflows/test.yml']); + // Test changes must exercise the new tests on every declared target, + // also a change of the calling workflow (GITHUB_WORKFLOW_REF names it). + const caller = (process.env.GITHUB_WORKFLOW_REF || '').split('@')[0].split('/').slice(2).join('/'); + const testChanges = !baseline || git(['diff', '--name-only', baseline, sha, '--', 'tests', + '.github/workflows/test.yml', ...caller ? [caller] : []]); selected = targets.filter(site => testChanges || changed(site, baseline, sha)); names = selected.map(site => site.context); compatible = (site, revision) => { diff --git a/README.md b/README.md index 00a28d5..466deeb 100644 --- a/README.md +++ b/README.md @@ -14,20 +14,20 @@ New projects take their callers from [astro-template](https://github.com/fulldot Fulldev, astro-template and vite-template expose `fix`, `check`, `build` and `test`. `check` validates source; `build` includes intrinsic artifact validation. Internal `test:unit`, `test:http` and `test:browser` helpers let CI run the enabled suites in the right environment. Devices stay manual. Do not add empty scripts or test workflows for disabled categories. -These callers use the Check workflow's optional `test-command` to run unit and service tests after source checks with one installation. Their Test caller disables its separate unit job. A separate Preview job waits for the selected PR revision’s deployments before Web installs dependencies or acquires its shared-account lock. Waiting does not consume the Web test budget. +These callers use the Check workflow's optional `test-command` to run unit and service tests after source checks with one installation. Their Test caller disables its separate unit job. Check, Test and Review are jobs of one workflow per PR, with Test alongside Check. A separate Preview job waits for the selected PR revision’s deployments before Web installs dependencies or acquires its shared-account lock. Waiting does not consume the Web test budget. Single-site callers using `preview-checks` also require `/.well-known/build.json` to identify the tested PR head. Every selected revision is checked again after Web waits for its shared-account lock. -Monorepos can give Test a `deployments` array of Netlify `context`, production `url`, repository-relative `config` and optional `base`. Preview selects targets by running each native `build.ignore` against the cumulative PR diff. Changes in `tests/` or `.github/workflows/test.yml` select every target. Netlify uses the same ignore rule against its cached revision. Skipped previews are reusable only when `/.well-known/build.json` proves an ancestor with unchanged build inputs. Static websites may explicitly enable `production-fallback: true` for a skipped first preview; signed-in apps always require an isolated preview. `QA_DEPLOY_URLS` contains only selected targets, and repositories must exclude absent targets from their suites. An explicitly empty selection skips Web and passes Test; missing or failed selection never does. +Monorepos can give Test a `deployments` array of Netlify `context`, production `url`, repository-relative `config` and optional `base`. Preview selects targets by running each native `build.ignore` against the cumulative PR diff. Changes in `tests/`, `.github/workflows/test.yml` or the calling workflow select every target. Netlify uses the same ignore rule against its cached revision. Skipped previews are reusable only when `/.well-known/build.json` proves an ancestor with unchanged build inputs. Static websites may explicitly enable `production-fallback: true` for a skipped first preview; signed-in apps always require an isolated preview. `QA_DEPLOY_URLS` contains only selected targets, and repositories must exclude absent targets from their suites. An explicitly empty selection skips Web and passes Test; missing or failed selection never does. After a push to main, Check runs source checks and unit/service tests again, Netlify runs the same build command, and Test live waits for the published revision before safe live HTTP/browser tests. Its `deployments` input lists HTTPS origins and their repository-relative Netlify config/base paths. Each build publishes `/.well-known/build.json` with its `COMMIT_REF`. For an older production deploy, Test live accepts it only if it is an ancestor of the requested revision and that site's existing Netlify `build.ignore` command confirms unchanged inputs. No Netlify token or second build is needed. Other repositories retain their existing `check:source`, `check:build` and Test caller contracts until explicitly migrated. The reusable defaults remain compatible with them. Non-Node repositories keep their existing language-specific check command with dependency installation disabled. -Repositories with `test.yml` require `Test / Test` through the existing `Review` status. Missing, failed or superseded enabled results cannot pass that gate. Skipped URL work passes only for an explicitly empty selection. Independent agent review owns code assessment; Ready has no external review-service dependency. +Organization rules require `Check / Check` and `Review`, without requiring synchronization with main. `Review` is the last job of the PR workflow, named `Review` and calling [the review action](.github/actions/review). It needs every other job of the run and fails when one failed, was cancelled or was skipped, and on a draft, since GitHub counts a skipped required check as passed. It then waits for every `netlify-checks` preview of the PR head, so no rule names a site. A new push cancels the run and a rerun resets it. A workflow with `Review` has no `workflow_dispatch`: a skipped `Review` on a PR head would pass. The PR's own workflow file runs, so a PR that changes it changes its own gate; such a PR needs an independent review before it merges. Skipped URL work passes only for an explicitly empty selection. Independent agent review owns code assessment. -The Ready caller grants `actions: read` so the gate reads the current Test workflow attempt and its jobs, including reruns. +Jobs that mostly wait, such as Test, Test live and Review, run on Blacksmith's ARM runners in private repositories. -Organization rules require `Check / Check` and `Review`, without requiring synchronization with main. `Review` also requires every `netlify-checks` preview of the revision, so no rule names a site. A preview can finish after Check and Test, so callers with `netlify-checks` also run Ready on Netlify's `status` events. Live URL tests run after deployment, outside the build command. Product scenarios and fixture writes stay on previews. A repository may pass `live-test-email` and `live-test-password` only from its trusted main workflow for one ordinary login/read/sign-out smoke with its own limited account; browser recordings and signed-in artifacts stay off. +Live URL tests run after deployment, outside the build command. Product scenarios and fixture writes stay on previews. A repository may pass `live-test-email` and `live-test-password` only from its trusted main workflow for one ordinary login/read/sign-out smoke with its own limited account; browser recordings and signed-in artifacts stay off. -Keep repository auto-merge disabled except for content publishers. CloudCannon's Publish button keeps automatic publication for same-repository `preview` PRs created by `cloudcannon[bot]`, with all required checks and previews. Fulldev Sites publishes a content PR by asking GitHub to merge it once its required checks pass. Code PRs are merged by their agent. +Keep repository auto-merge disabled except for content publishers. For CloudCannon's Publish button, a same-repository `preview` PR from `cloudcannon[bot]`, Review turns on GitHub's auto-merge with a merge commit once its checks and previews pass, and fails when GitHub refuses it; its job needs `contents: write` and `pull-requests: write`, and the repository both settings. Fulldev Sites publishes a content PR by asking GitHub to merge it once its required checks pass. Code PRs are merged by their agent. diff --git a/tests/preview.test.mjs b/tests/preview.test.mjs index 5754fe0..5f8338f 100644 --- a/tests/preview.test.mjs +++ b/tests/preview.test.mjs @@ -57,7 +57,8 @@ async function scenario(options = {}) { }}; await execute(github, {repo: {owner: 'o', repo: 'r'}, payload: {pull_request: pull}}, {info() {}, setOutput: (name, value) => { outputs[name] = value; }}, - {env: {...process.env, PREVIEW_CHECKS: JSON.stringify(names), DEPLOYMENTS: JSON.stringify(options.targets ?? []), GITHUB_WORKSPACE: options.root}}, + {env: {...process.env, PREVIEW_CHECKS: JSON.stringify(names), DEPLOYMENTS: JSON.stringify(options.targets ?? []), GITHUB_WORKSPACE: options.root, + GITHUB_WORKFLOW_REF: options.workflowRef ?? ''}}, {now: () => clock}, callback => { clock += 60 * 1000; callback(); }, createRequire(import.meta.url), async url => ({ok: !options.missingMarker, json: async () => ({revision: options.revisions?.[new URL(url).origin] ?? pull.head.sha})})); @@ -181,11 +182,16 @@ test('only explicitly read-only sites may reuse matching production when no firs await assert.rejects(scenario({...options, targets: f.targets.map(site => ({...site, 'production-fallback': false}))}), /within 12 minutes/); }); -test('changed tests exercise all targets and missing baselines fail safe to every target', async t => { +test('changed tests or a changed calling workflow exercise all targets and missing baselines fail safe to every target', async t => { const f = fixture(t); const head = f.commit('tests/http/example.spec.ts', 'new test'); assert.equal(Object.keys(JSON.parse((await scenario({...f, head})).outputs['deploy-urls'])).length, 2); assert.equal(Object.keys(JSON.parse((await scenario({...f, head, base: 'missing-base'})).outputs['deploy-urls'])).length, 2); + const g = fixture(t); + const caller = g.commit('.github/workflows/check.yml', 'calling workflow changed'); + const workflowRef = 'o/r/.github/workflows/check.yml@refs/pull/7/merge'; + assert.equal((await scenario({...g, head: caller})).outputs['web-enabled'], 'false'); + assert.equal(Object.keys(JSON.parse((await scenario({...g, head: caller, workflowRef})).outputs['deploy-urls'])).length, 2); }); test('an explicit empty scope skips URL work without waiting for unused statuses', async t => { diff --git a/tests/ready.test.mjs b/tests/ready.test.mjs deleted file mode 100644 index bbd0446..0000000 --- a/tests/ready.test.mjs +++ /dev/null @@ -1,383 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const source = readFileSync(new URL('../.github/workflows/ready.yml', import.meta.url), 'utf8') - .split(' script: |\n')[1].split('\n').map(line => line.slice(12)).join('\n'); -const execute = new (Object.getPrototypeOf(async function () {}).constructor)('github', 'context', 'core', 'process', 'fetch', 'setTimeout', source); - -async function scenario(options = {}) { - const pull = {number: 1, node_id: 'PR1', state: 'open', draft: false, head: {sha: 'head', ref: 'preview', repo: {full_name: 'o/r'}}, - base: {ref: 'main', repo: {full_name: 'o/r'}}, user: {type: 'Bot', login: 'cloudcannon[bot]'}, labels: options.selected ? [{name: 'review-ready'}] : [], html_url: 'https://github.com/o/r/pull/1', - ...options.pull}; - const pulls = options.pulls ?? [pull]; - const errors = []; - const statuses = []; - const merges = []; - let reads = 0; - let runReads = 0; - let jobReads = 0; - const checks = () => (options.checks ?? [{id: 1, name: 'Check / Check', app: {id: 15368}, conclusion: 'success'}]).map(check => - Object.hasOwn(check, 'details_url') ? check : {...check, details_url: `https://github.com/o/r/actions/runs/${check.id}/job/${check.id}`}); - const defaultRuns = () => checks().filter(check => check.name === 'Test / Test' && check.app?.id === 15368) - .map(check => ({id: Number(check.details_url?.match(/\/actions\/runs\/(\d+)/)?.[1]), run_attempt: 1, - name: 'Test', path: '.github/workflows/test.yml', head_sha: 'head', status: check.status, conclusion: check.conclusion})) - .filter(run => run.id); - const github = { - rest: { - pulls: {get: async ({pull_number}) => ({data: ++reads >= 2 && options.changed ? {...pull, head: {sha: 'new'}} : pulls.find(candidate => candidate.number === pull_number)}), - list: 'pulls', merge: async args => { if (options.rejectPull === args.pull_number) throw Object.assign(new Error('Head changed'), {status: 409}); merges.push(args); }}, - repos: {get: async () => ({data: {default_branch: 'main', full_name: 'o/r', allow_auto_merge: options.autoMerge !== false}}), - getCombinedStatusForRef: async ({ref}) => { - if (options.statusError) throw new Error('Status unavailable'); - assert.ok(pulls.some(candidate => candidate.head.sha === ref), 'Statuses are read for a PR head'); - return {data: {statuses: [...options.review ? [{context: 'Review', ...options.review}] : [], - ...options.previews ?? (options.netlify ?? []).map(context => ({context, state: 'success'}))]}}; - }, - createCommitStatus: async status => statuses.push(status)}, - checks: {listForRef: 'checks'}, - actions: {listWorkflowRunsForRepo: 'runs', listJobsForWorkflowRunAttempt: 'jobs'}, - }, - paginate: async (endpoint, parameters) => endpoint === 'pulls' ? pulls - : endpoint === 'runs' ? options.runRead ? options.runRead(++runReads) : options.runs ?? defaultRuns() - : endpoint === 'jobs' ? options.jobRead ? options.jobRead(++jobReads, parameters) : options.jobs ?? checks() - : checks(), - request: async () => ({data: [{type: 'required_status_checks', parameters: { - required_status_checks: (options.required ?? ['Check / Check', 'Review']).map(context => ({context})), - }}]}), - graphql: async (query, args) => { - // Octokit reserves request options instead of treating them as GraphQL variables. - for (const reserved of ['method', 'url', 'baseUrl', 'headers', 'request']) { - assert.equal(Object.hasOwn(args, reserved), false, `Reserved GraphQL variable: ${reserved}`); - } - assert.match(query, /mergeMethod: \$mergeMethod/); - merges.push(args); - }, - }; - await execute(github, {repo: {owner: 'o', repo: 'r'}, payload: options.event ?? {pull_request: {number: 1}}}, - {info: () => {}, error: message => errors.push(message), setFailed: message => errors.push(message)}, {env: {CHECK_NAME: 'Check / Check', NETLIFY_CHECKS: JSON.stringify(options.netlify ?? []), - TEST_CHECKS: JSON.stringify(options.testChecks ?? []), - GITHUB_API_URL: 'https://api.github.com', MERGE_TOKEN: options.mergeToken}}, - options.fetch ?? (() => { throw new Error('Unexpected network request'); }), resolve => resolve()); - return {statuses, merges, errors, runReads}; -} - -test('CloudCannon publication with real checks enables auto-merge', async () => { - const result = await scenario(); - assert.equal(result.statuses[0].state, 'success'); - assert.equal(result.merges.length, 1); -}); -test('draft remains pending and cannot auto-merge', async () => { - const result = await scenario({pull: {draft: true}}); - assert.equal(result.statuses[0].state, 'pending'); - assert.equal(result.merges.length, 0); -}); -test('pending drafts do not append statuses or query Test metadata on repeated events', async () => { - for (const description of ['Draft: publication is not authorized.', 'Checking the current Test run and attempt.']) { - const result = await scenario({pull: {draft: true}, testChecks: ['Test / Test'], - review: {state: 'pending', description}, runRead: () => {throw new Error('Draft must not query Test');}}); - assert.deepEqual(result.statuses, []); - assert.equal(result.runReads, 0); - assert.deepEqual(result.errors, []); - assert.deepEqual(result.merges, []); - } -}); -test('converting a successful PR to draft revokes its old Review', async () => { - const result = await scenario({pull: {draft: true}, testChecks: ['Test / Test'], - review: {state: 'success'}, runRead: () => {throw new Error('Draft must not query Test');}}); - assert.equal(result.statuses.length, 1); - assert.equal(result.statuses[0].state, 'pending'); - assert.deepEqual(result.errors, []); - assert.deepEqual(result.merges, []); -}); -test('an already-pending ready PR waits without another status write', async () => { - const result = await scenario({testChecks: ['Test / Test'], review: {state: 'pending'}, - runs: [{id: 100, name: 'Test', path: '.github/workflows/test.yml', head_sha: 'head', status: 'in_progress'}]}); - assert.deepEqual(result.statuses, []); - assert.deepEqual(result.errors, []); - assert.deepEqual(result.merges, []); -}); -test('a status read failure revokes any previous success before failing Ready', async () => { - const result = await scenario({statusError: true, review: {state: 'success'}}); - assert.equal(result.statuses.at(-1).state, 'pending'); - assert.match(result.errors[0], /Status unavailable/); - assert.deepEqual(result.merges, []); -}); -test('skipped, failed or absent static checks never authorize publication', async () => { - for (const checks of [[], [{id: 1, name: 'Check / Check', app: {id: 15368}, conclusion: 'skipped'}], - [{id: 1, name: 'Check / Check', app: {id: 15368}, conclusion: 'failure'}]]) { - assert.equal((await scenario({checks})).merges.length, 0); - } -}); -test('a newer pending Check supersedes an older successful one', async () => { - const checks = [ - {id: 1, name: 'Check / Check', app: {id: 15368}, conclusion: 'success'}, - {id: 2, name: 'Check / Check', app: {id: 15368}, conclusion: null}, - ]; - assert.equal((await scenario({checks})).merges.length, 0); -}); -test('missing central requirements or disabled repository auto-merge prevents rollout races', async () => { - assert.equal((await scenario({required: ['Check / Check']})).merges.length, 0); - assert.equal((await scenario({autoMerge: false})).merges.length, 0); -}); -test('changed revision, closed PR or another target does not publish', async () => { - for (const options of [{changed: true}, {pull: {state: 'closed'}}, {pull: {base: {ref: 'preview'}}}]) { - const result = await scenario(options); - assert.equal(result.statuses.length, 0); - assert.equal(result.merges.length, 0); - } -}); -test('successful Check workflow completion resumes the associated PR', async () => { - assert.equal((await scenario({event: {workflow_run: {pull_requests: [{number: 1}]}}})).merges.length, 1); - assert.equal((await scenario({event: {workflow_run: {pull_requests: []}}})).merges.length, 1); -}); -test('already-green PR merges immediately with the validated SHA', async () => { - const result = await scenario({pull: {mergeable_state: 'clean'}}); - assert.deepEqual(result.merges, [{owner: 'o', repo: 'r', pull_number: 1, sha: 'head', merge_method: 'merge'}]); -}); -test('automatic merge is bound to the validated head', async () => { - assert.deepEqual((await scenario()).merges, [{id: 'PR1', sha: 'head', mergeMethod: 'MERGE'}]); -}); -test('unrequired failures do not strand an otherwise eligible PR', async () => { - const result = await scenario({pull: {mergeable_state: 'unstable'}}); - assert.deepEqual(result.merges, [{owner: 'o', repo: 'r', pull_number: 1, sha: 'head', merge_method: 'merge'}]); - const denied = await scenario({pull: {mergeable_state: 'unstable'}, rejectPull: 1}); - assert.equal(denied.merges.length, 0); - assert.match(denied.errors[0], /Head changed/); -}); -test('Review waits for every Netlify preview of the revision', async () => { - const netlify = ['netlify/app/deploy-preview', 'netlify/site/deploy-preview']; - for (const state of ['pending', 'failure', undefined]) { - const previews = [{context: netlify[0], state: 'success'}, ...state ? [{context: netlify[1], state}] : []]; - const result = await scenario({netlify, previews}); - assert.equal(result.statuses.at(-1).state, 'pending'); - assert.equal(result.merges.length, 0); - } - const passed = await scenario({netlify, required: ['Check / Check', 'Review']}); - assert.equal(passed.statuses.at(-1).state, 'success'); - assert.equal(passed.merges.length, 1); -}); -test('every event reconciles other open PRs, even when concurrency coalesces events', async () => { - const pulls = [1, 2].map(number => ({number, node_id: `PR${number}`, state: 'open', draft: false, - head: {sha: `head${number}`, ref: 'preview', repo: {full_name: 'o/r'}}, base: {ref: 'main', repo: {full_name: 'o/r'}}, user: {type: 'Bot', login: 'cloudcannon[bot]'}, labels: [], html_url: `https://github.com/o/r/pull/${number}`})); - const result = await scenario({pulls, event: {pull_request: {number: 2}}}); - assert.deepEqual(result.merges.map(merge => merge.id), ['PR1', 'PR2']); -}); -test('a rejected merge does not stop reconciliation of later PRs', async () => { - const pulls = [1, 2].map(number => ({number, node_id: `PR${number}`, state: 'open', draft: false, - head: {sha: `head${number}`, ref: 'preview', repo: {full_name: 'o/r'}}, base: {ref: 'main', repo: {full_name: 'o/r'}}, user: {type: 'Bot', login: 'cloudcannon[bot]'}, labels: [], mergeable_state: 'clean', - html_url: `https://github.com/o/r/pull/${number}`})); - const result = await scenario({pulls, rejectPull: 1}); - assert.deepEqual(result.merges.map(merge => merge.pull_number), [2]); - assert.match(result.errors[0], /PR #1: Head changed/); - assert.equal(result.errors.length, 2); -}); - -test('CloudCannon preview merges preserve ancestry', async () => { - const result = await scenario({pull: {mergeable_state: 'clean', - head: {sha: 'head', ref: 'preview', repo: {full_name: 'o/r'}}, - base: {ref: 'main', repo: {full_name: 'o/r'}}}}); - assert.equal(result.merges[0].merge_method, 'merge'); -}); - -test('release app handles only the merge while Review remains an Actions status', async () => { - for (const mergeable_state of ['clean', 'unstable', 'blocked']) { - const requests = []; - const result = await scenario({mergeToken: 'synthetic-token', pull: {mergeable_state}, - fetch: async (url, options) => { requests.push({url, options}); - return {ok: true, status: 200, json: async () => ({merged: true})}; }}); - assert.equal(result.statuses[0].state, 'success'); - assert.equal(result.merges.length, 0); - assert.equal(requests.length, 1); - assert.equal(requests[0].options.headers.Authorization, 'Bearer synthetic-token'); - const body = JSON.parse(requests[0].options.body); - if (mergeable_state !== 'blocked') assert.deepEqual(body, {sha: 'head', merge_method: 'merge'}); - else assert.deepEqual(body.variables, {id: 'PR1', sha: 'head', mergeMethod: 'MERGE'}); - } -}); -test('release app rejection is reported without treating the PR as merged', async () => { - const result = await scenario({mergeToken: 'synthetic-token', pull: {mergeable_state: 'clean'}, - fetch: async () => ({ok: false, status: 409, json: async () => ({message: 'Head changed'})})}); - assert.equal(result.merges.length, 0); - assert.match(result.errors[0], /Merge request failed \(409\)/); -}); - - -test('delayed draft job does not supersede the newer Ready workflow', async () => { - const checks = [ - {id: 116021792205, name: 'Check / Check', app: {id: 15368}, conclusion: 'skipped', - details_url: 'https://github.com/o/r/actions/runs/38613265941/job/116021792205'}, - {id: 116021772853, name: 'Check / Check', app: {id: 15368}, conclusion: 'success', - details_url: 'https://github.com/o/r/actions/runs/38613266353/job/116021772853'}, - ]; - assert.equal((await scenario({checks})).merges.length, 1); - for (const conclusion of [null, 'failure', 'skipped']) { - checks[1].conclusion = conclusion; - assert.equal((await scenario({checks})).merges.length, 0); - } -}); -test('newer Ready workflow and latest attempt supersede old successful jobs', async () => { - for (const newerRun of [100, 101]) { - const checks = [ - {id: 200, name: 'Check / Check', app: {id: 15368}, conclusion: 'success', - details_url: 'https://github.com/o/r/actions/runs/100/job/200'}, - {id: newerRun === 100 ? 201 : 199, name: 'Check / Check', app: {id: 15368}, conclusion: 'failure', - details_url: `https://github.com/o/r/actions/runs/${newerRun}/job/new`}, - ]; - assert.equal((await scenario({checks})).merges.length, 0); - } -}); - -test('mixed or absent workflow metadata cannot authorize an old successful result', async () => { - for (const conclusion of ['failure', null, 'skipped', 'success']) { - const checks = [ - {id: 116021792205, name: 'Check / Check', app: {id: 15368}, conclusion: 'success', details_url: null}, - {id: 116021772853, name: 'Check / Check', app: {id: 15368}, conclusion, - details_url: 'https://github.com/o/r/actions/runs/38613266353/job/116021772853'}, - ]; - assert.equal((await scenario({checks})).merges.length, 0); - } - assert.equal((await scenario({checks: [{id: 1, name: 'Check / Check', app: {id: 15368}, - conclusion: 'success', details_url: 'invalid'}]})).merges.length, 0); -}); - - -test('ordinary Ready code PRs pass Review without any automatic merge', async () => { - for (const pull of [ - {user: {type: 'User', login: 'silveltman'}}, - {user: {type: 'Bot', login: 'dependabot[bot]'}}, - {head: {sha: 'head', ref: 'feature/code', repo: {full_name: 'o/r'}}}, - {head: {sha: 'head', ref: 'preview', repo: {full_name: 'fork/r'}}}, - {head: {sha: 'head', ref: 'preview'}}, - ]) { - for (const mergeable_state of ['clean', 'blocked', 'unstable']) { - const result = await scenario({pull: {...pull, mergeable_state}}); - assert.equal(result.statuses[0].state, 'success'); - assert.equal(result.merges.length, 0); - } - } -}); - -test('legacy review labels do not add an external review dependency', async () => { - const result = await scenario({selected: true, - pull: {user: {type: 'User', login: 'silveltman'}}}); - assert.equal(result.statuses[0].state, 'success'); - assert.equal(result.merges.length, 0); -}); - -test('required tests gate Review for ordinary PRs without adding an organization rule', async () => { - const options = {testChecks: ['Test / Test'], - pull: {user: {type: 'User', login: 'silveltman'}}}; - for (const check of [null, - {id: 1, name: 'Test / Test', app: {id: 15368}, status: 'completed', conclusion: 'skipped'}, - {id: 1, name: 'Test / Test', app: {id: 15368}, status: 'completed', conclusion: 'failure'}, - {id: 1, name: 'Test / Test', app: {id: 15368}, status: 'in_progress', conclusion: null}, - {id: 1, name: 'Test / Test', app: {id: 1}, status: 'completed', conclusion: 'success'}]) { - assert.equal((await scenario({...options, checks: check ? [check] : []})).statuses.at(-1).state, 'pending'); - } - const passed = {id: 2, name: 'Test / Test', app: {id: 15368}, status: 'completed', conclusion: 'success'}; - assert.equal((await scenario({...options, checks: [passed]})).statuses.at(-1).state, 'success'); - assert.equal((await scenario({...options, checks: [passed, {...passed, id: 3, status: 'in_progress', conclusion: null}]})).statuses.at(-1).state, 'pending'); - assert.equal((await scenario({...options, checks: [{...passed, details_url: null}]})).statuses.at(-1).state, 'pending'); - assert.equal((await scenario({...options, checks: [passed], event: {workflow_run: { - name: 'Test', head_sha: 'head', id: 3, status: 'queued'}}})).statuses.at(-1).state, 'pending'); - assert.equal((await scenario({...options, checks: [passed], event: {workflow_run: { - name: 'Test', head_sha: 'head', id: 3, status: 'completed', conclusion: 'failure'}}})).statuses.at(-1).state, 'pending'); - assert.equal((await scenario({...options, checks: [passed], runs: [{id: 2, run_attempt: 1, name: 'Test', path: '.github/workflows/test.yml', head_sha: 'head', status: 'completed', conclusion: 'failure'}], event: {workflow_run: { - name: 'Test', head_sha: 'head', id: 2, status: 'completed', conclusion: 'failure'}}})).statuses.at(-1).state, 'pending'); -}); - -const trial = {testChecks: ['Test / Test'], pull: {user: {type: 'User', login: 'silveltman'}}}; -const testRun = {id: 100, run_attempt: 1, name: 'Test', path: '.github/workflows/test.yml', head_sha: 'head', status: 'completed', conclusion: 'success'}; -const testJob = {id: 200, name: 'Test / Test', status: 'completed', conclusion: 'success'}; - -test('Check events cannot pass a Test rerun using the preceding successful check', async () => { - const result = await scenario({...trial, checks: [{...testJob, app: {id: 15368}}], - runs: [{...testRun, run_attempt: 2, status: 'in_progress', conclusion: null}], jobs: [testJob], - event: {workflow_run: {name: 'Check', head_sha: 'head', status: 'completed', conclusion: 'success'}}}); - assert.equal(result.statuses.at(-1).state, 'pending'); -}); - -test('the exact latest Test attempt supplies every required successful job', async () => { - for (const jobs of [[], [{...testJob, conclusion: 'skipped'}], [{...testJob, conclusion: 'failure'}]]) { - const result = await scenario({...trial, runs: [{...testRun, run_attempt: 2}], jobRead: (_, parameters) => { - assert.equal(parameters.run_id, 100); - assert.equal(parameters.attempt_number, 2); - return jobs; - }}); - assert.equal(result.statuses.at(-1).state, 'pending'); - } - const result = await scenario({...trial, runs: [{...testRun, run_attempt: 2}], jobs: [testJob]}); - assert.equal(result.statuses.at(-1).state, 'success'); -}); - -test('other PRs\' events do not rewrite an unchanged successful Review', async () => { - // GitHub refuses more than 1000 statuses per commit and context. - const passed = {...trial, runs: [testRun], jobs: [testJob], - review: {state: 'success', description: 'Ready requirements passed for this revision.'}}; - for (const event of [{pull_request: {number: 2}}, {workflow_run: {name: 'Check', head_sha: 'other'}}, {sha: 'other'}]) { - const result = await scenario({...passed, event}); - assert.deepEqual(result.statuses, []); - assert.deepEqual(result.errors, []); - } - // The PR's own events still block the old success before checking. - const own = await scenario(passed); - assert.deepEqual(own.statuses.map(status => status.state), ['pending', 'success']); -}); -test('a PR changing while it is checked loses its old success', async () => { - const result = await scenario({changed: true, review: {state: 'success'}, event: {pull_request: {number: 2}}}); - assert.deepEqual(result.statuses.map(status => status.state), ['pending']); -}); - -test('completion retries metadata lag and passes without requiring another event', async () => { - let jobReads = 0; - const result = await scenario({...trial, - event: {workflow_run: {...testRun, id: 101}}, - runRead: reads => [reads === 1 ? testRun : {...testRun, id: 101}], - jobRead: () => ++jobReads === 1 ? [] : [testJob]}); - assert.equal(result.statuses.at(-1).state, 'success'); - assert.ok(jobReads >= 2); -}); - -test('persistent missing metadata is bounded and API errors revoke old success', async () => { - let reads = 0; - const missing = await scenario({...trial, runRead: () => {reads++; return [];}}); - assert.equal(reads, 4); - assert.equal(missing.statuses.at(-1).state, 'pending'); - const failed = await scenario({...trial, review: {state: 'success'}, - runRead: () => {throw new Error('Metadata unavailable');}}); - assert.equal(failed.statuses.at(-1).state, 'pending'); - assert.match(failed.errors[0], /Metadata unavailable/); -}); - -test('completion retries the same run and attempt while its status is stale', async () => { - let runReads = 0; - let jobReads = 0; - const result = await scenario({...trial, event: {workflow_run: testRun}, - runRead: () => [++runReads === 1 ? {...testRun, status: 'in_progress', conclusion: null} : testRun], - jobRead: () => {jobReads++; return [testJob];}}); - assert.equal(result.statuses.at(-1).state, 'success'); - assert.ok(runReads >= 3); - assert.equal(jobReads, 2); - assert.deepEqual(result.errors, []); -}); - -test('a completed older attempt cannot authorize a newer pending attempt', async () => { - const result = await scenario({...trial, event: {workflow_run: testRun}, - runs: [{...testRun, run_attempt: 2, status: 'in_progress', conclusion: null}], jobs: [testJob]}); - assert.equal(result.statuses.at(-1).state, 'pending'); - assert.deepEqual(result.errors, []); -}); - -test('persistent lag after successful completion fails Ready instead of silently waiting', async () => { - for (const options of [ - {runs: [{...testRun, status: 'in_progress', conclusion: null}]}, - {runs: [testRun], jobs: []}, - {runs: []}, - ]) { - const result = await scenario({...trial, ...options, event: {workflow_run: testRun}}); - assert.equal(result.statuses.at(-1).state, 'pending'); - assert.match(result.errors[0], /metadata is still incomplete/); - assert.match(result.errors.at(-1), /could not be reconciled/); - } -}); diff --git a/tests/review.test.mjs b/tests/review.test.mjs new file mode 100644 index 0000000..a37efdc --- /dev/null +++ b/tests/review.test.mjs @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +import {createRequire} from 'node:module'; +import test from 'node:test'; + +const review = createRequire(import.meta.url)('../.github/actions/review/review.cjs'); + +// One Review run against canned statuses: `statuses` gives the head's +// statuses per poll, the last one repeating. +async function run({needs = {check: {result: 'success'}}, previews = [], statuses = [[]], pull = {}, current = {}, autoMerge = null, refuse} = {}) { + const failures = []; + const merges = []; + let polls = 0; + let clock = 0; + const github = { + rest: { + repos: {getCombinedStatusForRef: async ({ref}) => { + assert.equal(ref, 'head'); + return {data: {statuses: statuses[Math.min(polls++, statuses.length - 1)]}}; + }}, + pulls: {get: async () => ({data: {state: 'open', draft: false, head: {sha: 'head'}, base: {ref: 'main'}, auto_merge: autoMerge, ...current}})}, + }, + graphql: async (query, variables) => { + if (refuse) throw new Error(refuse); + assert.match(query, /mergeMethod: MERGE/); + merges.push(variables); + }, + }; + await review({ + github, + context: {repo: {owner: 'o', repo: 'r'}, payload: {pull_request: {number: 1, node_id: 'PR1', draft: false, + head: {sha: 'head', ref: 'feature', repo: {full_name: 'o/r'}}, base: {ref: 'main'}, user: {login: 'someone'}, ...pull}}}, + core: {setFailed: message => failures.push(message), info: () => {}}, + env: {NEEDS: needs === null ? '' : JSON.stringify(needs), NETLIFY_CHECKS: JSON.stringify(previews), TIMEOUT_MINUTES: '1'}, + sleep: async ms => { clock += ms; }, + now: () => clock, + }); + return {failures, merges, polls}; +} + +const preview = 'netlify/site/deploy-preview'; +const cloudcannon = {user: {login: 'cloudcannon[bot]'}, head: {sha: 'head', ref: 'preview', repo: {full_name: 'o/r'}}}; + +test('Review fails a draft, a caller without needs, and a needed job that did not succeed', async () => { + assert.match((await run({pull: {draft: true}})).failures[0], /draft/); + for (const needs of [null, {}]) assert.match((await run({needs})).failures[0], /needs the jobs/); + for (const result of ['failure', 'cancelled', 'skipped']) { + const {failures} = await run({needs: {check: {result: 'success'}, test: {result}}}); + assert.match(failures[0], new RegExp(`test \\(${result}\\)`)); + } +}); + +test('Review waits for the previews of the head and fails on a failed or missing one', async () => { + const pending = [{context: preview, state: 'pending'}]; + const passed = await run({previews: [preview], statuses: [[], pending, [{context: preview, state: 'success'}]]}); + assert.deepEqual(passed.failures, []); + assert.equal(passed.polls, 3); + const failed = await run({previews: [preview], statuses: [pending, [{context: preview, state: 'failure'}]]}); + assert.match(failed.failures[0], /Preview failed/); + const missing = await run({previews: [preview], statuses: [pending]}); + assert.match(missing.failures[0], /did not finish within 1 minutes/); +}); + +test('Review turns on auto-merge only for a passed CloudCannon publication from the same repository', async () => { + assert.deepEqual((await run({pull: cloudcannon})).merges, [{id: 'PR1', sha: 'head'}]); + assert.deepEqual((await run({pull: cloudcannon, autoMerge: {merge_method: 'merge'}})).merges, []); + for (const pull of [{}, {...cloudcannon, head: {...cloudcannon.head, repo: {full_name: 'fork/r'}}}]) { + assert.deepEqual((await run({pull})).merges, []); + } + assert.deepEqual((await run({pull: cloudcannon, needs: {check: {result: 'failure'}}})).merges, []); + assert.match((await run({pull: cloudcannon, refuse: 'Auto merge is not allowed'})).failures[0], /would not merge/); + assert.match((await run({pull: cloudcannon, autoMerge: {merge_method: 'squash'}})).failures[0], /merge commit/); + for (const current of [{head: {sha: 'newer'}}, {base: {ref: 'other'}}, {draft: true}, {state: 'closed'}]) { + const changed = await run({pull: cloudcannon, current}); + assert.deepEqual(changed.merges, []); + assert.match(changed.failures[0], /changed while Review waited/); + } +});