diff --git a/.github/actions/draft-segment-schema-pr/gate.test.mjs b/.github/actions/draft-segment-schema-pr/gate.test.mjs index fd9759fd..eb0aa375 100644 --- a/.github/actions/draft-segment-schema-pr/gate.test.mjs +++ b/.github/actions/draft-segment-schema-pr/gate.test.mjs @@ -1,8 +1,7 @@ -import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; -import { describe, it } from 'node:test'; import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; import { AGREEMENT_PHRASE, @@ -55,32 +54,28 @@ function input(overrides = {}) { describe('eventSkipReason', () => { it('skips propose on issue_comment and close unless the PR closed', () => { - assert.equal( - eventSkipReason('propose', 'issue_comment', 'created'), + expect(eventSkipReason('propose', 'issue_comment', 'created')).toBe( 'wrong-event', ); - assert.equal( - eventSkipReason('propose', 'pull_request', 'closed'), + expect(eventSkipReason('propose', 'pull_request', 'closed')).toBe( 'wrong-event', ); - assert.equal( - eventSkipReason('close', 'pull_request', 'synchronize'), + expect(eventSkipReason('close', 'pull_request', 'synchronize')).toBe( 'wrong-event', ); - assert.equal(eventSkipReason('create', 'issue_comment', 'created'), ''); - assert.equal(eventSkipReason('propose', 'pull_request', 'synchronize'), ''); - assert.equal(eventSkipReason('close', 'pull_request', 'closed'), ''); + expect(eventSkipReason('create', 'issue_comment', 'created')).toBe(''); + expect(eventSkipReason('propose', 'pull_request', 'synchronize')).toBe(''); + expect(eventSkipReason('close', 'pull_request', 'closed')).toBe(''); }); }); describe('isAgreementComment', () => { it('treats trailing whitespace on the agreement sentence as a match', () => { - assert.equal( + expect( isAgreementComment(`${AGREEMENT_PHRASE} \nThanks`, 'alice', 'alice'), - true, - ); - assert.equal(isAgreementComment(AGREEMENT_PHRASE, 'bob', 'alice'), false); - assert.equal(isAgreementComment('please open it', 'alice', 'alice'), false); + ).toBe(true); + expect(isAgreementComment(AGREEMENT_PHRASE, 'bob', 'alice')).toBe(false); + expect(isAgreementComment('please open it', 'alice', 'alice')).toBe(false); }); }); @@ -94,9 +89,9 @@ describe('collectTsDiff and hasAnalyticsDiff', () => { { filename: 'README.md', patch: '+docs' }, { filename: 'app/foo.test.ts', patch: '+createEventBuilder(x)' }, ]); - assert.deepEqual(diff.files, ['app/Home.ts']); - assert.equal(diff.mentionsAnalytics, true); - assert.equal(hasAnalyticsDiff(diff, 'mobile'), true); + expect(diff.files).toStrictEqual(['app/Home.ts']); + expect(diff.mentionsAnalytics).toBe(true); + expect(hasAnalyticsDiff(diff, 'mobile')).toBe(true); }); it('treats a catalog-only change as an analytics hit', () => { @@ -106,16 +101,16 @@ describe('collectTsDiff and hasAnalyticsDiff', () => { patch: "+NEW_EVENT = 'New Event'", }, ]); - assert.equal(diff.mentionsAnalytics, false); - assert.equal(hasAnalyticsDiff(diff, 'mobile'), true); + expect(diff.mentionsAnalytics).toBe(false); + expect(hasAnalyticsDiff(diff, 'mobile')).toBe(true); }); it('does not treat unrelated TypeScript patches as analytics hits', () => { const diff = collectTsDiff([ { filename: 'app/Home.ts', patch: '+const x = 1;\n' }, ]); - assert.equal(diff.mentionsAnalytics, false); - assert.equal(hasAnalyticsDiff(diff, 'mobile'), false); + expect(diff.mentionsAnalytics).toBe(false); + expect(hasAnalyticsDiff(diff, 'mobile')).toBe(false); }); it('treats addSensitiveProperties as an analytics hit', () => { @@ -125,7 +120,7 @@ describe('collectTsDiff and hasAnalyticsDiff', () => { patch: '+.addSensitiveProperties({ secret: true })', }, ]); - assert.equal(diff.mentionsAnalytics, true); + expect(diff.mentionsAnalytics).toBe(true); }); it('counts a renamed TypeScript file once', () => { @@ -136,32 +131,30 @@ describe('collectTsDiff and hasAnalyticsDiff', () => { patch: '+const x = 1;\n', }, ]); - assert.deepEqual(diff.files, ['app/next.ts', 'app/prev.ts']); - assert.equal(diff.recordCount, 1); + expect(diff.files).toStrictEqual(['app/next.ts', 'app/prev.ts']); + expect(diff.recordCount).toBe(1); }); }); describe('shouldPushSchema', () => { it('pushes on create when open, and on propose only after a schema PR exists', () => { - assert.equal(shouldPushSchema('create', false, true, true), true); - assert.equal(shouldPushSchema('propose', false, true, true), false); - assert.equal(shouldPushSchema('propose', true, true, true), true); - assert.equal(shouldPushSchema('close', true, false, true), false); - assert.equal(shouldPushSchema('create', false, true, false), false); + expect(shouldPushSchema('create', false, true, true)).toBe(true); + expect(shouldPushSchema('propose', false, true, true)).toBe(false); + expect(shouldPushSchema('propose', true, true, true)).toBe(true); + expect(shouldPushSchema('close', true, false, true)).toBe(false); + expect(shouldPushSchema('create', false, true, false)).toBe(false); }); }); describe('decideGate', () => { it('skips forks, opt-out, closed PRs, and non-agreement comments', () => { - assert.equal( - decideGate(input({ pr: { ...PR, isFork: true } })).skipReason, + expect(decideGate(input({ pr: { ...PR, isFork: true } })).skipReason).toBe( 'fork', ); - assert.equal( + expect( decideGate(input({ pr: { ...PR, hasOptOutLabel: true } })).skipReason, - 'opt-out', - ); - assert.equal( + ).toBe('opt-out'); + expect( decideGate( input({ mode: 'create', @@ -172,9 +165,8 @@ describe('decideGate', () => { commenterLogin: 'alice', }), ).skipReason, - 'client-pr-closed', - ); - assert.equal( + ).toBe('client-pr-closed'); + expect( decideGate( input({ mode: 'create', @@ -182,8 +174,7 @@ describe('decideGate', () => { eventAction: 'created', }), ).skipReason, - 'agreement-mismatch', - ); + ).toBe('agreement-mismatch'); }); it('skips close when no schema PR exists', () => { @@ -194,8 +185,8 @@ describe('decideGate', () => { schemaPrExists: false, }), ); - assert.equal(result.skip, true); - assert.equal(result.skipReason, 'no-schema-pr'); + expect(result.skip).toBe(true); + expect(result.skipReason).toBe('no-schema-pr'); }); it('skips propose when there is no analytics diff, schema PR, or sticky comment', () => { @@ -204,7 +195,7 @@ describe('decideGate', () => { pullFiles: [{ filename: 'app/Home.ts', patch: '+const x = 1;\n' }], }), ); - assert.equal(result.skipReason, 'no-analytics-diff'); + expect(result.skipReason).toBe('no-analytics-diff'); }); it('continues propose so publish can edit a sticky comment when analytics drop off', () => { @@ -214,9 +205,9 @@ describe('decideGate', () => { hasProposalComment: true, }), ); - assert.equal(result.skip, false); - assert.equal(result.hasAnalyticsDiff, false); - assert.equal(result.shouldPush, false); + expect(result.skip).toBe(false); + expect(result.hasAnalyticsDiff).toBe(false); + expect(result.shouldPush).toBe(false); }); it('sets tooManyFiles and does not push when the TS file list exceeds the cap', () => { @@ -228,9 +219,9 @@ describe('decideGate', () => { }), ); const result = decideGate(input({ pullFiles, schemaPrExists: true })); - assert.equal(result.skip, false); - assert.equal(result.tooManyFiles, true); - assert.equal(result.shouldPush, false); + expect(result.skip).toBe(false); + expect(result.tooManyFiles).toBe(true); + expect(result.shouldPush).toBe(false); }); it('does not treat 76 renamed TypeScript files as over the cap', () => { @@ -240,7 +231,7 @@ describe('decideGate', () => { patch: '+createEventBuilder(MetaMetricsEvents.APP_OPENED)', })); const result = decideGate(input({ pullFiles })); - assert.equal(result.tooManyFiles, false); + expect(result.tooManyFiles).toBe(false); }); it('pushes on create when agreement matches and YAML can be written', () => { @@ -253,9 +244,9 @@ describe('decideGate', () => { commenterLogin: 'alice', }), ); - assert.equal(result.skip, false); - assert.equal(result.shouldPush, true); - assert.equal(result.branch, botBranchName('mobile', 12)); + expect(result.skip).toBe(false); + expect(result.shouldPush).toBe(true); + expect(result.branch).toBe(botBranchName('mobile', 12)); }); }); @@ -265,8 +256,8 @@ describe('schema pull list client', () => { join(dirname(fileURLToPath(import.meta.url)), 'action.yml'), 'utf8', ); - assert.match(action, /getOctokit\(process\.env\.SEGMENT_SCHEMA_TOKEN\)/u); - assert.doesNotMatch(action, /const \{\s*getOctokit\s*\}/u); - assert.doesNotMatch(action, /headers:\s*\{\s*authorization:/u); + expect(action).toMatch(/getOctokit\(process\.env\.SEGMENT_SCHEMA_TOKEN\)/u); + expect(action).not.toMatch(/const \{\s*getOctokit\s*\}/u); + expect(action).not.toMatch(/headers:\s*\{\s*authorization:/u); }); }); diff --git a/.github/actions/playwright-test-health-report/lib/report-health.test.mjs b/.github/actions/playwright-test-health-report/lib/report-health.test.mjs index a7b2b757..035050fe 100644 --- a/.github/actions/playwright-test-health-report/lib/report-health.test.mjs +++ b/.github/actions/playwright-test-health-report/lib/report-health.test.mjs @@ -1,5 +1,4 @@ -import assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; +import { describe, expect, it } from 'vitest'; import { allocateBucketSlots, @@ -51,11 +50,11 @@ describe('summarizeTestHealth', () => { }, ]); - const test = summary[0]; - assert.equal(test.latestClassification, 'passed'); - assert.equal(test.historicalBrokenCount, 1); - assert.equal(test.historicalFlakyCount, 1); - assert.equal(test.totalRuns, 3); + const [first] = summary; + expect(first.latestClassification).toBe('passed'); + expect(first.historicalBrokenCount).toBe(1); + expect(first.historicalFlakyCount).toBe(1); + expect(first.totalRuns).toBe(3); }); }); @@ -73,9 +72,9 @@ describe('partitionSummary', () => { }, ]); - assert.equal(watchItems.length, 1); - assert.equal(flakyItems.length, 0); - assert.equal(brokenItems.length, 0); + expect(watchItems).toHaveLength(1); + expect(flakyItems).toHaveLength(0); + expect(brokenItems).toHaveLength(0); }); }); @@ -88,12 +87,11 @@ describe('allocateBucketSlots', () => { infra: 0, }); - assert.equal(slots.maxBroken, 0); - assert.equal(slots.maxWatch, 13); - assert.equal( + expect(slots.maxBroken).toBe(0); + expect(slots.maxWatch).toBe(13); + expect( slots.maxBroken + slots.maxFlaky + slots.maxWatch + slots.maxInfra, - 13, - ); + ).toBe(13); }); }); @@ -105,54 +103,51 @@ describe('formatWatchHistory', () => { totalRuns: 8, }); - assert.match(text, /failed 2\/8 runs/); - assert.match(text, /flaky 3\/8 runs/); + expect(text).toMatch(/failed 2\/8 runs/u); + expect(text).toMatch(/flaky 3\/8 runs/u); }); }); describe('normalizeRepoFilePath', () => { it('prefixes testDir-relative paths', () => { - assert.equal( + expect( normalizeRepoFilePath( 'accounts/account-syncing-settings-toggle.spec.ts', { prefix: 'tests/smoke-appium', }, ), + ).toBe( 'tests/smoke-appium/accounts/account-syncing-settings-toggle.spec.ts', ); }); it('strips CI absolute checkout paths to repo-relative', () => { - assert.equal( + expect( normalizeRepoFilePath( '/Users/runner/work/metamask-mobile/metamask-mobile/tests/framework/config/global.setup.ts', ), - 'tests/framework/config/global.setup.ts', - ); + ).toBe('tests/framework/config/global.setup.ts'); }); it('leaves paths already under tests/ unchanged when prefix is set', () => { - assert.equal( + expect( normalizeRepoFilePath('tests/smoke-appium/accounts/foo.spec.ts', { prefix: 'tests/smoke-appium', }), - 'tests/smoke-appium/accounts/foo.spec.ts', - ); + ).toBe('tests/smoke-appium/accounts/foo.spec.ts'); }); it('does not double-apply an identical prefix', () => { - assert.equal( + expect( normalizeRepoFilePath('tests/smoke-appium/accounts/foo.spec.ts', { prefix: 'tests/smoke-appium', }), - 'tests/smoke-appium/accounts/foo.spec.ts', - ); + ).toBe('tests/smoke-appium/accounts/foo.spec.ts'); }); it('returns relative paths unchanged when no prefix is set', () => { - assert.equal( - normalizeRepoFilePath('accounts/foo.spec.ts'), + expect(normalizeRepoFilePath('accounts/foo.spec.ts')).toBe( 'accounts/foo.spec.ts', ); }); @@ -195,16 +190,16 @@ describe('createSlackBlocks path links', () => { }, ); - const link = blocks - .flatMap((block) => block.elements || []) - .flatMap((element) => element.elements || []) - .find( - (element) => element.type === 'link' && element.text === 'toggles sync', - ); + const elements = blocks + .flatMap(({ elements: blockElements = [] }) => blockElements) + .flatMap(({ elements: innerElements = [] }) => innerElements); - assert.equal( - link?.url, - 'https://github.com/MetaMask/metamask-mobile/blob/main/tests/smoke-appium/accounts/account-syncing-settings-toggle.spec.ts', + expect(elements).toContainEqual( + expect.objectContaining({ + type: 'link', + text: 'toggles sync', + url: 'https://github.com/MetaMask/metamask-mobile/blob/main/tests/smoke-appium/accounts/account-syncing-settings-toggle.spec.ts', + }), ); }); }); diff --git a/.github/scripts/tests/clean-release-changelog.test.mts b/.github/scripts/tests/clean-release-changelog.test.mts index 971fd5f6..f869e567 100644 --- a/.github/scripts/tests/clean-release-changelog.test.mts +++ b/.github/scripts/tests/clean-release-changelog.test.mts @@ -1,4 +1,3 @@ -import assert from 'node:assert/strict'; import { execFile, execFileSync } from 'node:child_process'; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { createServer } from 'node:http'; @@ -6,9 +5,9 @@ import type { ServerResponse } from 'node:http'; import type { AddressInfo } from 'node:net'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import test from 'node:test'; import { fileURLToPath } from 'node:url'; import { promisify } from 'node:util'; +import { describe, expect, it, vi } from 'vitest'; import { assertPrEvidenceAvailable, @@ -34,196 +33,193 @@ import { import { getEnvironmentWithoutAiKey } from '../shared/environment.mts'; import { getGitTestEnvironment } from './git-test-environment.mts'; -const generatedSection = `## [13.51.0] +describe('clean-release-changelog', () => { + const generatedSection = `## [13.51.0] ### Uncategorized - Added a new flow (#101) - Fixed an issue (#102)`; -test('removes LiteLLM credentials from evidence subprocesses', () => { - assert.deepEqual( - getEnvironmentWithoutAiKey({ - GH_TOKEN: 'github-token', - AI_ANALYZER_LITELLM_KEY: 'litellm-key', - }), - { GH_TOKEN: 'github-token' }, - ); -}); + it('removes LiteLLM credentials from evidence subprocesses', () => { + expect( + getEnvironmentWithoutAiKey({ + GH_TOKEN: 'github-token', + AI_ANALYZER_LITELLM_KEY: 'litellm-key', + }), + ).toStrictEqual({ GH_TOKEN: 'github-token' }); + }); -test('retries transient GitHub API failures before returning evidence', async () => { - let attempts = 0; - const retryDelays: number[] = []; - const response = await requestGhApiWithRetry( - ['repos/MetaMask/metamask-extension/pulls/1'], - async () => { - attempts += 1; - if (attempts < 3) { - throw new Error('HTTP 502: Bad Gateway'); - } - return '{"title":"Recovered"}'; - }, - async (milliseconds) => { - retryDelays.push(milliseconds); - }, - ); + it('retries transient GitHub API failures before returning evidence', async () => { + const request = vi + .fn<() => Promise>() + .mockRejectedValueOnce(new Error('HTTP 502: Bad Gateway')) + .mockRejectedValueOnce(new Error('HTTP 502: Bad Gateway')) + .mockResolvedValue('{"title":"Recovered"}'); + const retryDelays: number[] = []; + const response = await requestGhApiWithRetry( + ['repos/MetaMask/metamask-extension/pulls/1'], + request, + async (milliseconds) => { + retryDelays.push(milliseconds); + }, + ); - assert.equal(response, '{"title":"Recovered"}'); - assert.equal(attempts, 3); - assert.deepEqual(retryDelays, [1_000, 2_000]); -}); + expect(response).toBe('{"title":"Recovered"}'); + expect(request).toHaveBeenCalledTimes(3); + expect(retryDelays).toStrictEqual([1_000, 2_000]); + }); -test('does not retry permanent GitHub API failures', async () => { - let attempts = 0; - await assert.rejects( - async () => + it('does not retry permanent GitHub API failures', async () => { + const request = vi + .fn<() => Promise>() + .mockRejectedValue(new Error('HTTP 404: Not Found')); + await expect( requestGhApiWithRetry( ['repos/MetaMask/metamask-extension/pulls/1'], - async () => { - attempts += 1; - throw new Error('HTTP 404: Not Found'); - }, - async () => { + request, + async (): Promise => { throw new Error('Unexpected retry'); }, ), - /HTTP 404/u, - ); - assert.equal(attempts, 1); - assert.equal( - isRetryableGhApiFailure(new Error('HTTP 404: Not Found')), - false, - ); - // The command line names the PR, which is not an HTTP status. - assert.equal( - isRetryableGhApiFailure( - new Error( - 'Command failed: gh api repos/o/r/pulls/503\ngh: Not Found (HTTP 404)', + ).rejects.toThrow(/HTTP 404/u); + expect(request).toHaveBeenCalledTimes(1); + expect(isRetryableGhApiFailure(new Error('HTTP 404: Not Found'))).toBe( + false, + ); + // The command line names the PR, which is not an HTTP status. + expect( + isRetryableGhApiFailure( + new Error( + 'Command failed: gh api repos/o/r/pulls/503\ngh: Not Found (HTTP 404)', + ), ), - ), - false, - ); -}); + ).toBe(false); + }); -test('uses PR title and body when local evidence is unavailable', async () => { - const requests: string[] = []; - const evidence = await getPrEvidence( - 'https://github.com/MetaMask/metamask-mobile', - ['37469'], - async (argumentsList) => { - requests.push(argumentsList[0] ?? ''); - if (argumentsList[0]?.endsWith('/pulls/37469')) { + it('uses PR title and body when local evidence is unavailable', async () => { + const requests: string[] = []; + const evidence = await getPrEvidence( + 'https://github.com/MetaMask/metamask-mobile', + ['37469'], + async (argumentsList) => { + requests.push(argumentsList[0] as string); return JSON.stringify({ title: 'fix: match the recurring every sheet to expires after', body: 'The recurring interval picker now matches the expiration sheet.', }); - } - throw new Error('Unexpected GitHub request'); - }, - ); + }, + ); - assert.deepEqual(evidence.unavailablePrEvidence, []); - assert.match( - evidence.evidence[0] ?? '', - /#37469: fix: match the recurring every sheet/u, - ); - assert.equal(requests.length, 1); -}); + expect(evidence.unavailablePrEvidence).toStrictEqual([]); + expect(evidence.evidence[0]).toMatch( + /#37469: fix: match the recurring every sheet/u, + ); + expect(requests).toHaveLength(1); + expect(requests[0]).toMatch(/\/pulls\/37469$/u); + }); -test('collects local evidence only from mainline squash commits', async () => { - const directory = mkdtempSync(join(tmpdir(), 'local-evidence-')); - const originalDirectory = process.cwd(); - const git = (...argumentsList: string[]) => - execFileSync('git', argumentsList, { - cwd: directory, - env: getGitTestEnvironment(), - }); - const commit = (message: string) => - git('commit', '--allow-empty', '-m', message); - - try { - git('init', '--initial-branch', 'main'); - commit('feat: add thing (#1)\n\nBody one'); - commit('feat: real thing (#4)\n\nReal body'); - commit('Revert "feat: real thing (#4)" (#5)\n\nRevert body'); - commit('chore: backport (#2)\n\nThis is a cherry-pick of another commit.'); - // `origin/main` is what marks a commit as mainline. - git('update-ref', 'refs/remotes/origin/main', 'HEAD'); - commit('feat: side branch only (#3)'); - // A newer copy of #1 that is not on main must not hide the mainline one. - commit('feat: add thing for the release (#1)\n\nRelease copy'); - - process.chdir(directory); - const evidence = await getLocalPrEvidence(['1', '2', '3', '4']); - - // A revert quotes the PR it undoes but is not evidence for that PR. - assert.deepEqual([...evidence].sort(), [ - ['1', '#1: feat: add thing (#1)\nLocal squash commit body:\nBody one'], - ['4', '#4: feat: real thing (#4)\nLocal squash commit body:\nReal body'], - ]); - } finally { - process.chdir(originalDirectory); - rmSync(directory, { force: true, recursive: true }); - } -}); + it('collects local evidence only from mainline squash commits', async () => { + const directory = mkdtempSync(join(tmpdir(), 'local-evidence-')); + const originalDirectory = process.cwd(); + const git = (...argumentsList: string[]): Buffer => + execFileSync('git', argumentsList, { + cwd: directory, + env: getGitTestEnvironment(), + }); + const commit = (message: string): Buffer => + git('commit', '--allow-empty', '-m', message); -test('falls back to GitHub when local history cannot be read', async (context) => { - const directory = mkdtempSync(join(tmpdir(), 'no-repo-')); - const originalDirectory = process.cwd(); - const warn = context.mock.method(console, 'warn', () => undefined); - - try { - process.chdir(directory); - assert.deepEqual([...(await getLocalPrEvidence(['1']))], []); - assert.equal(warn.mock.callCount(), 1); - } finally { - process.chdir(originalDirectory); - rmSync(directory, { force: true, recursive: true }); - } -}); + try { + git('init', '--initial-branch', 'main'); + commit('feat: add thing (#1)\n\nBody one'); + commit('feat: real thing (#4)\n\nReal body'); + commit('Revert "feat: real thing (#4)" (#5)\n\nRevert body'); + commit( + 'chore: backport (#2)\n\nThis is a cherry-pick of another commit.', + ); + // `origin/main` is what marks a commit as mainline. + git('update-ref', 'refs/remotes/origin/main', 'HEAD'); + commit('feat: side branch only (#3)'); + // A newer copy of #1 that is not on main must not hide the mainline one. + commit('feat: add thing for the release (#1)\n\nRelease copy'); + + process.chdir(directory); + const evidence = await getLocalPrEvidence(['1', '2', '3', '4']); + + // A revert quotes the PR it undoes but is not evidence for that PR. + expect([...evidence].sort()).toStrictEqual([ + ['1', '#1: feat: add thing (#1)\nLocal squash commit body:\nBody one'], + [ + '4', + '#4: feat: real thing (#4)\nLocal squash commit body:\nReal body', + ], + ]); + } finally { + process.chdir(originalDirectory); + rmSync(directory, { force: true, recursive: true }); + } + }); -test('does not query GitHub when local mainline evidence exists', async () => { - const evidence = await getPrEvidence( - 'https://github.com/MetaMask/metamask-mobile', - ['37469'], - async () => { - throw new Error('GitHub evidence was not expected'); - }, - new Map([ - [ - '37469', - '#37469: fix: match the recurring every sheet to expires after\nLocal squash commit body:\nThe interval picker now matches.', - ], - ]), - ); + it('falls back to GitHub when local history cannot be read', async () => { + const directory = mkdtempSync(join(tmpdir(), 'no-repo-')); + const originalDirectory = process.cwd(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); - assert.deepEqual(evidence.unavailablePrEvidence, []); - assert.deepEqual(evidence.evidence, [ - '#37469: fix: match the recurring every sheet to expires after\nLocal squash commit body:\nThe interval picker now matches.', - ]); -}); + try { + process.chdir(directory); + expect([...(await getLocalPrEvidence(['1']))]).toStrictEqual([]); + expect(warn).toHaveBeenCalledTimes(1); + } finally { + process.chdir(originalDirectory); + rmSync(directory, { force: true, recursive: true }); + } + }); -test('limits local evidence history to referenced PR numbers', () => { - assert.deepEqual(getLocalEvidenceLogArguments([]), undefined); - assert.deepEqual(getLocalEvidenceLogArguments(['37469', '37522', '37469']), [ - 'log', - 'HEAD', - '--extended-regexp', - '--grep=\\(#(37469|37522)\\)', - '--format=%H%x1f%s%x1f%b%x1e', - ]); -}); + it('does not query GitHub when local mainline evidence exists', async () => { + const evidence = await getPrEvidence( + 'https://github.com/MetaMask/metamask-mobile', + ['37469'], + async () => { + throw new Error('GitHub evidence was not expected'); + }, + new Map([ + [ + '37469', + '#37469: fix: match the recurring every sheet to expires after\nLocal squash commit body:\nThe interval picker now matches.', + ], + ]), + ); -test('identifies LiteLLM credential rejections', () => { - const error = new LiteLlmAuthenticationError(401); - assert.equal(error.name, 'LiteLlmAuthenticationError'); - assert.match(error.message, /HTTP 401/u); - assert.equal(isLiteLlmAuthenticationError(error), true); - assert.equal(isLiteLlmAuthenticationError(new Error('HTTP 401')), false); -}); + expect(evidence.unavailablePrEvidence).toStrictEqual([]); + expect(evidence.evidence).toStrictEqual([ + '#37469: fix: match the recurring every sheet to expires after\nLocal squash commit body:\nThe interval picker now matches.', + ]); + }); -test('cleans large release sections in reference-preserving chunks', () => { - const section = `## [13.51.0] + it('limits local evidence history to referenced PR numbers', () => { + expect(getLocalEvidenceLogArguments([])).toBeUndefined(); + expect( + getLocalEvidenceLogArguments(['37469', '37522', '37469']), + ).toStrictEqual([ + 'log', + 'HEAD', + '--extended-regexp', + '--grep=\\(#(37469|37522)\\)', + '--format=%H%x1f%s%x1f%b%x1e', + ]); + }); + + it('identifies LiteLLM credential rejections', () => { + const error = new LiteLlmAuthenticationError(401); + expect(error.name).toBe('LiteLlmAuthenticationError'); + expect(error.message).toMatch(/HTTP 401/u); + expect(isLiteLlmAuthenticationError(error)).toBe(true); + expect(isLiteLlmAuthenticationError(new Error('HTTP 401'))).toBe(false); + }); + + it('cleans large release sections in reference-preserving chunks', () => { + const section = `## [13.51.0] ### Uncategorized @@ -233,29 +229,29 @@ test('cleans large release sections in reference-preserving chunks', () => { ### Fixed - Improved a flow (#103)`; - assert.deepEqual(splitReleaseSectionIntoChunks(section, '13.51.0', 2), [ - { - section: `## [13.51.0] + expect(splitReleaseSectionIntoChunks(section, '13.51.0', 2)).toStrictEqual([ + { + section: `## [13.51.0] ### Uncategorized - Added a new flow (#101) - Fixed an issue (#102)`, - prNumbers: ['101', '102'], - }, - { - section: `## [13.51.0] + prNumbers: ['101', '102'], + }, + { + section: `## [13.51.0] ### Fixed - Improved a flow (#103)`, - prNumbers: ['103'], - }, - ]); - const merged = mergeCleanRoomSections( - [ - `## [13.51.0] + prNumbers: ['103'], + }, + ]); + const merged = mergeCleanRoomSections( + [ + `## [13.51.0] ### Added @@ -264,24 +260,24 @@ test('cleans large release sections in reference-preserving chunks', () => { ### Fixed - Fixed an issue (#102)`, - `## [13.51.0] + `## [13.51.0] ### Fixed - Improved a flow (#103)`, - ], - '13.51.0', - ); - assert.doesNotThrow(() => - validateReplacement(merged, '13.51.0', ['101', '102', '103']), - ); - assert.doesNotMatch(merged, /\)\n\n- /u); -}); + ], + '13.51.0', + ); + expect(() => + validateReplacement(merged, '13.51.0', ['101', '102', '103']), + ).not.toThrow(); + expect(merged).not.toMatch(/\)\n\n- /u); + }); -test('warns about and skips an identical repeat of an entry', (context) => { - const warn = context.mock.method(console, 'warn', () => undefined); - const chunks = splitReleaseSectionIntoChunks( - `## [13.51.0] + it('warns about and skips an identical repeat of an entry', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const chunks = splitReleaseSectionIntoChunks( + `## [13.51.0] ### Fixed @@ -290,17 +286,16 @@ test('warns about and skips an identical repeat of an entry', (context) => { ### Changed - Fixed an issue (#101)`, - '13.51.0', - ); + '13.51.0', + ); - assert.deepEqual(chunks[0]?.prNumbers, ['101']); - assert.equal(warn.mock.callCount(), 1); - assert.match(String(warn.mock.calls[0]?.arguments[0]), /PR 101/u); -}); + expect(chunks[0]?.prNumbers).toStrictEqual(['101']); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toMatch(/PR 101/u); + }); -test('rejects different entries for the same PR instead of dropping one', () => { - assert.throws( - () => + it('rejects different entries for the same PR instead of dropping one', () => { + expect(() => splitReleaseSectionIntoChunks( `## [13.51.0] @@ -310,12 +305,11 @@ test('rejects different entries for the same PR instead of dropping one', () => - Fixed another issue (#101)`, '13.51.0', ), - /different entries for PR 101/u, - ); -}); + ).toThrow(/different entries for PR 101/u); + }); -test('extracts exactly one release section', () => { - const changelog = `# Changelog + it('extracts exactly one release section', () => { + const changelog = `# Changelog ${generatedSection} @@ -326,50 +320,47 @@ ${generatedSection} - An earlier fix (#100) `; - assert.equal( - extractReleaseSection(changelog, '13.51.0').section, - generatedSection, - ); - assert.deepEqual(getPrNumbers(generatedSection), ['101', '102']); -}); + expect(extractReleaseSection(changelog, '13.51.0').section).toBe( + generatedSection, + ); + expect(getPrNumbers(generatedSection)).toStrictEqual(['101', '102']); + }); -test('counts the PR groups auto-changelog counts', () => { - assert.deepEqual( - getPrNumbers(`## [1.0.0] + it('counts the PR groups auto-changelog counts', () => { + expect( + getPrNumbers(`## [1.0.0] ### Fixed - Fixed issue #4521 in the send flow (#101, #102). - Reverted "Fixed it (#67)" (#69) - Added a flow with no reference`), - ['101', '102', '67', '69'], - ); - // auto-changelog reads the first line, wherever the group sits on it. - assert.deepEqual( - getEntryPrNumbers('- Fixed it (#7)\n - nested detail (#8)'), - ['7'], - ); - assert.deepEqual(getEntryPrNumbers('- Fixed it (#7), (#8)'), ['7', '8']); - assert.deepEqual(getEntryPrNumbers('- Fixed swap from (#46000) (#101)'), [ - '46000', - '101', - ]); - assert.deepEqual(getEntryPrNumbers('- (#101)'), ['101']); -}); + ).toStrictEqual(['101', '102', '67', '69']); + // auto-changelog reads the first line, wherever the group sits on it. + expect( + getEntryPrNumbers('- Fixed it (#7)\n - nested detail (#8)'), + ).toStrictEqual(['7']); + expect(getEntryPrNumbers('- Fixed it (#7), (#8)')).toStrictEqual([ + '7', + '8', + ]); + expect( + getEntryPrNumbers('- Fixed swap from (#46000) (#101)'), + ).toStrictEqual(['46000', '101']); + expect(getEntryPrNumbers('- (#101)')).toStrictEqual(['101']); + }); -test('rejects a duplicate release heading', () => { - assert.throws( - () => + it('rejects a duplicate release heading', () => { + expect(() => extractReleaseSection( `${generatedSection}\n\n${generatedSection}`, '13.51.0', ), - /Expected exactly one release heading/u, - ); -}); + ).toThrow(/Expected exactly one release heading/u); + }); -test('replaces only the release section without changing its surrounding whitespace', () => { - const changelog = `# Changelog + it('replaces only the release section without changing its surrounding whitespace', () => { + const changelog = `# Changelog ${generatedSection} @@ -379,7 +370,7 @@ ${generatedSection} - An earlier fix (#100) `; - const replacement = `## [13.51.0] + const replacement = `## [13.51.0] ### Added @@ -389,16 +380,15 @@ ${generatedSection} - Fixed an issue (#102)`; - assert.equal( - replaceReleaseSection(changelog, '13.51.0', replacement), - changelog.replace(generatedSection, replacement), - ); -}); + expect(replaceReleaseSection(changelog, '13.51.0', replacement)).toBe( + changelog.replace(generatedSection, replacement), + ); + }); -test('accepts a categorized replacement that preserves every PR once', () => { - assert.doesNotThrow(() => - validateReplacement( - `## [13.51.0] + it('accepts a categorized replacement that preserves every PR once', () => { + expect(() => + validateReplacement( + `## [13.51.0] ### Added @@ -407,19 +397,17 @@ test('accepts a categorized replacement that preserves every PR once', () => { ### Fixed - Fixed an issue (#102)`, - '13.51.0', - ['101', '102'], - ), - ); -}); + '13.51.0', + ['101', '102'], + ), + ).not.toThrow(); + }); -test('rejects uncategorized, omitted, invented, and duplicate PR references', () => { - assert.throws( - () => validateReplacement(generatedSection, '13.51.0', ['101', '102']), - /Uncategorized/u, - ); - assert.throws( - () => + it('rejects uncategorized, omitted, invented, and duplicate PR references', () => { + expect(() => + validateReplacement(generatedSection, '13.51.0', ['101', '102']), + ).toThrow(/Uncategorized/u); + expect(() => validateReplacement( `## [13.51.0] @@ -429,10 +417,8 @@ test('rejects uncategorized, omitted, invented, and duplicate PR references', () '13.51.0', ['101', '102'], ), - /references do not match/u, - ); - assert.throws( - () => + ).toThrow(/references do not match/u); + expect(() => validateReplacement( `## [13.51.0] @@ -442,10 +428,8 @@ test('rejects uncategorized, omitted, invented, and duplicate PR references', () '13.51.0', ['101', '102'], ), - /references do not match/u, - ); - assert.throws( - () => + ).toThrow(/references do not match/u); + expect(() => validateReplacement( `## [13.51.0] @@ -457,10 +441,8 @@ test('rejects uncategorized, omitted, invented, and duplicate PR references', () '13.51.0', ['101', '102'], ), - /duplicate PR references/u, - ); - assert.throws( - () => + ).toThrow(/duplicate PR references/u); + expect(() => validateReplacement( `## [13.51.0] @@ -472,10 +454,8 @@ Here is the cleaned section: '13.51.0', ['101', '102'], ), - /unexpected Markdown/u, - ); - assert.throws( - () => + ).toThrow(/unexpected Markdown/u); + expect(() => validateReplacement( `## [13.51.0] @@ -485,13 +465,11 @@ Here is the cleaned section: '13.51.0', ['101', '102'], ), - /adjacent list items/u, - ); -}); + ).toThrow(/adjacent list items/u); + }); -test('rejects an entry without a trailing PR reference', () => { - assert.throws( - () => + it('rejects an entry without a trailing PR reference', () => { + expect(() => validateReplacement( `## [13.51.0] @@ -502,213 +480,220 @@ test('rejects an entry without a trailing PR reference', () => { '13.51.0', ['101'], ), - /must be text followed by its PR reference/u, - ); -}); + ).toThrow(/must be text followed by its PR reference/u); + }); -test('rejects entries that are not canonical or hide a PR in the text', () => { - const entry = (line: string) => `## [13.51.0]\n\n### Fixed\n\n${line}`; - assert.throws( - () => validateReplacement(entry('- Fixed X (#101).'), '13.51.0', ['101']), - /must be text followed by its PR reference/u, - ); - assert.throws( - () => validateReplacement(entry('- (#101)'), '13.51.0', ['101']), - /must be text followed by its PR reference/u, - ); - assert.throws( - () => + it('rejects entries that are not canonical or hide a PR in the text', () => { + const entry = (line: string): string => + `## [13.51.0]\n\n### Fixed\n\n${line}`; + expect(() => + validateReplacement(entry('- Fixed X (#101).'), '13.51.0', ['101']), + ).toThrow(/must be text followed by its PR reference/u); + expect(() => + validateReplacement(entry('- (#101)'), '13.51.0', ['101']), + ).toThrow(/must be text followed by its PR reference/u); + expect(() => validateReplacement( entry('- Fixed swap from (#46000) (#101)'), '13.51.0', ['101'], ), - /references do not match/u, - ); -}); + ).toThrow(/references do not match/u); + }); -test('accepts dashes and parentheses inside an entry', () => { - assert.doesNotThrow(() => - validateReplacement( - `## [13.51.0] + it('accepts dashes and parentheses inside an entry', () => { + expect(() => + validateReplacement( + `## [13.51.0] ### Fixed - Updated fees (beta) - now shown in fiat (#101)`, - '13.51.0', - ['101'], - ), - ); -}); + '13.51.0', + ['101'], + ), + ).not.toThrow(); + }); -type FetchResponse = Awaited>; -type RecordedRequest = { url: string; init: RequestInit }; - -/** - * Builds a minimal fetch response. - * - * @param status - The HTTP status. - * @param body - The JSON body. - * @returns The response. - */ -function fakeResponse(status: number, body: unknown = {}): FetchResponse { - return { - ok: status >= 200 && status < 300, - status, - json: async () => body, - } as FetchResponse; -} - -/** - * Builds a fake fetch that returns or throws the given results in order. - * - * @param responses - The results, consumed one per request. - * @param requests - Collects each request made. - * @returns The fake fetch. - */ -function createFetch( - responses: (FetchResponse | Error)[], - requests: RecordedRequest[] = [], -): typeof fetch { - return (async (url: Parameters[0], init?: RequestInit) => { - requests.push({ url: String(url), init: init ?? {} }); - const next = responses.shift(); - if (!next) { - throw new Error('Unexpected request'); + type FetchResponse = Awaited>; + type RecordedRequest = { url: string; init: RequestInit }; + + /** + * Builds a minimal fetch response. + * + * @param status - The HTTP status. + * @param body - The JSON body. + * @returns The response. + */ + function fakeResponse(status: number, body: unknown = {}): FetchResponse { + return { + ok: status >= 200 && status < 300, + status, + json: async () => body, + } as FetchResponse; + } + + /** + * Reads the URL string out of a fetch input. + * + * @param url - The first argument given to fetch. + * @returns The URL as a string. + */ + function getRequestUrl(url: Parameters[0]): string { + if (url instanceof URL) { + return url.href; } - if (next instanceof Error) { - throw next; + return url instanceof Request ? url.url : url; + } + + /** + * Builds a fake fetch that returns or throws the given results in order. + * + * @param responses - The results, consumed one per request. + * @param requests - Collects each request made. + * @returns The fake fetch. + */ + function createFetch( + responses: (FetchResponse | Error)[], + requests: RecordedRequest[] = [], + ): typeof fetch { + return async (url: Parameters[0], init?: RequestInit) => { + requests.push({ + url: getRequestUrl(url), + init: init ?? {}, + }); + const next = responses.shift(); + if (!next) { + throw new Error('Unexpected request'); + } + if (next instanceof Error) { + throw next; + } + return next; + }; + } + + /** + * Builds a successful chat-completions response. + * + * @param content - The message content. + * @returns The response. + */ + function completion(content: unknown): FetchResponse { + return fakeResponse(200, { choices: [{ message: { content } }] }); + } + + const rewriteInput = { + prompt: 'Prompt', + section: generatedSection, + prEvidence: ['#101: Title'], + apiKey: 'litellm-key', + }; + + /** + * Puts an environment variable back to its earlier value. + * + * @param name - The variable. + * @param value - Its earlier value, or undefined if it was unset. + */ + function restoreEnvironmentVariable( + name: string, + value: string | undefined, + ): void { + if (value === undefined) { + delete process.env[name]; + } else { + process.env[name] = value; } - return next; - }) as typeof fetch; -} - -/** - * Builds a successful chat-completions response. - * - * @param content - The message content. - * @returns The response. - */ -function completion(content: unknown): FetchResponse { - return fakeResponse(200, { choices: [{ message: { content } }] }); -} - -const rewriteInput = { - prompt: 'Prompt', - section: generatedSection, - prEvidence: ['#101: Title'], - apiKey: 'litellm-key', -}; - -/** - * Puts an environment variable back to its earlier value. - * - * @param name - The variable. - * @param value - Its earlier value, or undefined if it was unset. - */ -function restoreEnvironmentVariable( - name: string, - value: string | undefined, -): void { - if (value === undefined) { - delete process.env[name]; - } else { - process.env[name] = value; } -} -for (const invalidTimeout of ['soon', '0', '3000000000']) { - test(`rejects the timeout "${invalidTimeout}" in the environment`, async () => { - const originalTimeout = process.env.CHANGELOG_AI_TIMEOUT_MS; - restoreEnvironmentVariable('CHANGELOG_AI_TIMEOUT_MS', invalidTimeout); - try { - await assert.rejects( - async () => + for (const invalidTimeout of ['soon', '0', '3000000000']) { + it(`rejects the timeout "${invalidTimeout}" in the environment`, async () => { + const originalTimeout = process.env.CHANGELOG_AI_TIMEOUT_MS; + restoreEnvironmentVariable('CHANGELOG_AI_TIMEOUT_MS', invalidTimeout); + try { + await expect( requestCleanRoomRewrite({ ...rewriteInput, fetchImpl: createFetch([]), }), - /CHANGELOG_AI_TIMEOUT_MS must be a positive integer/u, - ); - } finally { - restoreEnvironmentVariable('CHANGELOG_AI_TIMEOUT_MS', originalTimeout); + ).rejects.toThrow( + /CHANGELOG_AI_TIMEOUT_MS must be a positive integer/u, + ); + } finally { + restoreEnvironmentVariable('CHANGELOG_AI_TIMEOUT_MS', originalTimeout); + } + }); + } + + it('sends the pinned model with the bearer credential to chat completions', async () => { + const requests: RecordedRequest[] = []; + const result = await requestCleanRoomRewrite({ + ...rewriteInput, + fetchImpl: createFetch([completion(' ## [13.51.0] ')], requests), + sleep: async () => undefined, + timeoutMs: 1_000, + }); + + expect(result).toBe('## [13.51.0]'); + expect(requests).toHaveLength(1); + expect(requests[0]?.url).toMatch(/\/chat\/completions$/u); + expect(requests[0]?.init.method).toBe('POST'); + const headers = requests[0]?.init.headers as Record; + expect(headers.Authorization).toBe('Bearer litellm-key'); + const body = JSON.parse(requests[0]?.init.body as string) as { + model: string; + temperature: number; + messages: { content: string }[]; + }; + expect(body.model).toBe('gpt-6.1-terra'); + expect(body.temperature).toBe(0); + expect(body.messages[1]?.content).toMatch(//u); + expect(JSON.stringify(body)).not.toMatch(/litellm-key/u); + }); + + it('does not retry a rejected LiteLLM credential', async () => { + for (const status of [401, 403]) { + const requests: RecordedRequest[] = []; + const sleeps: number[] = []; + const rewrite = requestCleanRoomRewrite({ + ...rewriteInput, + fetchImpl: createFetch([fakeResponse(status)], requests), + sleep: async (milliseconds) => { + sleeps.push(milliseconds); + }, + timeoutMs: 1_000, + }); + await expect(rewrite).rejects.toThrow(LiteLlmAuthenticationError); + await expect(rewrite).rejects.toThrow(`HTTP ${String(status)}`); + expect(requests).toHaveLength(1); + expect(sleeps).toStrictEqual([]); } }); -} - -test('sends the pinned model with the bearer credential to chat completions', async () => { - const requests: RecordedRequest[] = []; - const result = await requestCleanRoomRewrite({ - ...rewriteInput, - fetchImpl: createFetch([completion(' ## [13.51.0] ')], requests), - sleep: async () => undefined, - timeoutMs: 1_000, - }); - - assert.equal(result, '## [13.51.0]'); - assert.equal(requests.length, 1); - assert.match(requests[0]?.url ?? '', /\/chat\/completions$/u); - assert.equal(requests[0]?.init.method, 'POST'); - const headers = requests[0]?.init.headers as Record; - assert.equal(headers.Authorization, 'Bearer litellm-key'); - const body = JSON.parse(String(requests[0]?.init.body)) as { - model: string; - temperature: number; - messages: { content: string }[]; - }; - assert.equal(body.model, 'gpt-6.1-terra'); - assert.equal(body.temperature, 0); - assert.match(body.messages[1]?.content ?? '', //u); - assert.doesNotMatch(JSON.stringify(body), /litellm-key/u); -}); -test('does not retry a rejected LiteLLM credential', async () => { - for (const status of [401, 403]) { + it('retries one transient LiteLLM failure and then succeeds', async () => { const requests: RecordedRequest[] = []; const sleeps: number[] = []; - await assert.rejects( - async () => - requestCleanRoomRewrite({ - ...rewriteInput, - fetchImpl: createFetch([fakeResponse(status)], requests), - sleep: async (milliseconds) => { - sleeps.push(milliseconds); - }, - timeoutMs: 1_000, - }), - (error: unknown) => - isLiteLlmAuthenticationError(error) && - error.message.includes(`HTTP ${String(status)}`), - ); - assert.equal(requests.length, 1); - assert.deepEqual(sleeps, []); - } -}); + const result = await requestCleanRoomRewrite({ + ...rewriteInput, + fetchImpl: createFetch( + [fakeResponse(503), completion('## [13.51.0]')], + requests, + ), + sleep: async (milliseconds) => { + sleeps.push(milliseconds); + }, + timeoutMs: 1_000, + }); -test('retries one transient LiteLLM failure and then succeeds', async () => { - const requests: RecordedRequest[] = []; - const sleeps: number[] = []; - const result = await requestCleanRoomRewrite({ - ...rewriteInput, - fetchImpl: createFetch( - [fakeResponse(503), completion('## [13.51.0]')], - requests, - ), - sleep: async (milliseconds) => { - sleeps.push(milliseconds); - }, - timeoutMs: 1_000, - }); - - assert.equal(result, '## [13.51.0]'); - assert.equal(requests.length, 2); - assert.deepEqual(sleeps, [1_000]); -}); + expect(result).toBe('## [13.51.0]'); + expect(requests).toHaveLength(2); + expect(sleeps).toStrictEqual([1_000]); + }); -test('stops after the retry budget for persistent LiteLLM failures', async () => { - const requests: RecordedRequest[] = []; - await assert.rejects( - async () => + it('stops after the retry budget for persistent LiteLLM failures', async () => { + const requests: RecordedRequest[] = []; + await expect( requestCleanRoomRewrite({ ...rewriteInput, fetchImpl: createFetch( @@ -718,28 +703,25 @@ test('stops after the retry budget for persistent LiteLLM failures', async () => sleep: async () => undefined, timeoutMs: 1_000, }), - /LiteLLM returned HTTP 500/u, - ); - assert.equal(requests.length, 2); -}); + ).rejects.toThrow(/LiteLLM returned HTTP 500/u); + expect(requests).toHaveLength(2); + }); -test('rejects an empty LiteLLM message after the retry budget', async () => { - await assert.rejects( - async () => + it('rejects an empty LiteLLM message after the retry budget', async () => { + await expect( requestCleanRoomRewrite({ ...rewriteInput, fetchImpl: createFetch([completion(''), completion(null)]), sleep: async () => undefined, timeoutMs: 1_000, }), - /no message content/u, - ); -}); + ).rejects.toThrow(/no message content/u); + }); -test('requests another response when one fails validation', async (context) => { - context.mock.method(console, 'warn', () => undefined); - const requests: RecordedRequest[] = []; - const valid = `## [13.51.0] + it('requests another response when one fails validation', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const requests: RecordedRequest[] = []; + const valid = `## [13.51.0] ### Added @@ -748,31 +730,33 @@ test('requests another response when one fails validation', async (context) => { ### Fixed - Fixed an issue (#102)`; - const glued = valid.replace( - '(#101)\n\n### Fixed\n\n- Fixed', - '(#101)- Fixed', - ); + const glued = valid.replace( + '(#101)\n\n### Fixed\n\n- Fixed', + '(#101)- Fixed', + ); - const section = await requestValidatedRewrite( - { - ...rewriteInput, - fetchImpl: createFetch([completion(glued), completion(valid)], requests), - }, - '13.51.0', - ['101', '102'], - ); + const section = await requestValidatedRewrite( + { + ...rewriteInput, + fetchImpl: createFetch( + [completion(glued), completion(valid)], + requests, + ), + }, + '13.51.0', + ['101', '102'], + ); - assert.equal(section, valid); - assert.equal(requests.length, 2); -}); + expect(section).toBe(valid); + expect(requests).toHaveLength(2); + }); -test('gives up after the last response fails validation', async (context) => { - context.mock.method(console, 'warn', () => undefined); - const requests: RecordedRequest[] = []; - const invalid = '## [13.51.0]\n\n### Fixed\n\n- Fixed an issue (#101)'; + it('gives up after the last response fails validation', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const requests: RecordedRequest[] = []; + const invalid = '## [13.51.0]\n\n### Fixed\n\n- Fixed an issue (#101)'; - await assert.rejects( - async () => + await expect( requestValidatedRewrite( { ...rewriteInput, @@ -784,16 +768,14 @@ test('gives up after the last response fails validation', async (context) => { '13.51.0', ['101', '102'], ), - /references do not match/u, - ); - assert.equal(requests.length, 3); -}); + ).rejects.toThrow(/references do not match/u); + expect(requests).toHaveLength(3); + }); -test('does not request again after a rejected key', async () => { - const requests: RecordedRequest[] = []; + it('does not request again after a rejected key', async () => { + const requests: RecordedRequest[] = []; - await assert.rejects( - async () => + await expect( requestValidatedRewrite( { ...rewriteInput, @@ -802,165 +784,164 @@ test('does not request again after a rejected key', async () => { '13.51.0', ['101', '102'], ), - LiteLlmAuthenticationError, - ); - assert.equal(requests.length, 1); -}); + ).rejects.toThrow(LiteLlmAuthenticationError); + expect(requests).toHaveLength(1); + }); -test('aborts a LiteLLM request that exceeds the timeout', async () => { - const signals: (AbortSignal | null | undefined)[] = []; - const hangingFetch = (async (_url: unknown, init?: RequestInit) => { - signals.push(init?.signal); - return new Promise((_resolve, reject) => { - init?.signal?.addEventListener('abort', () => { - reject(new Error('aborted by timeout')); + it('aborts a LiteLLM request that exceeds the timeout', async () => { + const signals: (AbortSignal | null | undefined)[] = []; + const hangingFetch = (async (_url: unknown, init?: RequestInit) => { + signals.push(init?.signal); + return await new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => { + reject(new Error('aborted by timeout')); + }); }); - }); - }) as typeof fetch; + }) as typeof fetch; - await assert.rejects( - async () => + await expect( requestCleanRoomRewrite({ ...rewriteInput, fetchImpl: hangingFetch, sleep: async () => undefined, timeoutMs: 5, }), - /aborted by timeout/u, - ); - assert.equal(signals.length, 2); - assert.equal( - signals.every((signal) => signal?.aborted), - true, - ); -}); + ).rejects.toThrow(/aborted by timeout/u); + expect(signals).toHaveLength(2); + expect(signals.every((signal) => signal?.aborted)).toBe(true); + }); -test('rejects a proofread when any source PR lacks evidence', () => { - assert.throws( - () => + it('rejects a proofread when any source PR lacks evidence', () => { + expect(() => assertPrEvidenceAvailable([ { prNumber: '101', error: 'HTTP 404: Not Found' }, { prNumber: '102', error: 'HTTP 500: Internal Server Error' }, ]), - /PR evidence unavailable: #101 \(HTTP 404: Not Found\), #102 \(HTTP 500: Internal Server Error\)/u, - ); - assert.doesNotThrow(() => assertPrEvidenceAvailable([])); -}); - -const execFileAsync = promisify(execFile); -const scriptPath = fileURLToPath( - new URL('../clean-release-changelog.mts', import.meta.url), -); - -type ProofreadResult = { - exitCode: number; - original: string; - changelog: string; - report: Record; -}; - -/** - * Runs the script as a subprocess against a throwaway repository and a local - * stand-in for LiteLLM. Evidence comes from the repository's mainline commits, - * so `gh` is never called. - * - * @param respond - Writes the stand-in's response to the model request. - * @returns The exit code, the changelog before and after, and the report. - */ -async function runProofreader( - respond: (response: ServerResponse) => void, -): Promise { - const directory = mkdtempSync(join(tmpdir(), 'proofread-')); - const server = createServer((_request, response) => { - respond(response); - }); - const git = (...argumentsList: string[]) => - execFileSync('git', argumentsList, { - cwd: directory, - env: getGitTestEnvironment(), - }); - - try { - git('init', '--initial-branch', 'main'); - git('commit', '--allow-empty', '-m', 'feat: add a flow (#101)\n\nBody one'); - git( - 'commit', - '--allow-empty', - '-m', - 'fix: fix an issue (#102)\n\nBody two', + ).toThrow( + /PR evidence unavailable: #101 \(HTTP 404: Not Found\), #102 \(HTTP 500: Internal Server Error\)/u, ); - git('update-ref', 'refs/remotes/origin/main', 'HEAD'); + expect(() => assertPrEvidenceAvailable([])).not.toThrow(); + }); - const changelogPath = join(directory, 'CHANGELOG.md'); - const original = `# Changelog\n\n${generatedSection}\n\n## [13.50.3]\n\n### Fixed\n\n- An earlier fix (#100)\n`; - writeFileSync(changelogPath, original); - const promptPath = join(directory, 'prompt.md'); - writeFileSync(promptPath, 'Prompt'); - const reportPath = join(directory, 'report.json'); + const execFileAsync = promisify(execFile); + const scriptPath = fileURLToPath( + new URL('../clean-release-changelog.mts', import.meta.url), + ); - await new Promise((resolve) => { - server.listen(0, '127.0.0.1', resolve); + type ProofreadResult = { + exitCode: number; + original: string; + changelog: string; + report: Record; + }; + + /** + * Runs the script as a subprocess against a throwaway repository and a local + * stand-in for LiteLLM. Evidence comes from the repository's mainline commits, + * so `gh` is never called. + * + * @param respond - Writes the stand-in's response to the model request. + * @returns The exit code, the changelog before and after, and the report. + */ + async function runProofreader( + respond: (response: ServerResponse) => void, + ): Promise { + const directory = mkdtempSync(join(tmpdir(), 'proofread-')); + const server = createServer((_request, response) => { + respond(response); }); - const { port } = server.address() as AddressInfo; + const git = (...argumentsList: string[]): Buffer => + execFileSync('git', argumentsList, { + cwd: directory, + env: getGitTestEnvironment(), + }); - let exitCode = 0; try { - await execFileAsync( - process.execPath, - [ - scriptPath, - '--changelog', - changelogPath, - '--version', - '13.51.0', - '--repository', - 'https://github.com/MetaMask/example', - '--prompt', - promptPath, - '--report', - reportPath, - ], - { - cwd: directory, - env: { - ...process.env, - AI_ANALYZER_LITELLM_KEY: 'litellm-key', - LITELLM_BASE_URL: `http://127.0.0.1:${port}`, - }, - }, + git('init', '--initial-branch', 'main'); + git( + 'commit', + '--allow-empty', + '-m', + 'feat: add a flow (#101)\n\nBody one', ); - } catch (error) { - exitCode = (error as { code?: number }).code ?? 1; + git( + 'commit', + '--allow-empty', + '-m', + 'fix: fix an issue (#102)\n\nBody two', + ); + git('update-ref', 'refs/remotes/origin/main', 'HEAD'); + + const changelogPath = join(directory, 'CHANGELOG.md'); + const original = `# Changelog\n\n${generatedSection}\n\n## [13.50.3]\n\n### Fixed\n\n- An earlier fix (#100)\n`; + writeFileSync(changelogPath, original); + const promptPath = join(directory, 'prompt.md'); + writeFileSync(promptPath, 'Prompt'); + const reportPath = join(directory, 'report.json'); + + await new Promise((resolve) => { + server.listen(0, '127.0.0.1', resolve); + }); + const { port } = server.address() as AddressInfo; + + let exitCode = 0; + try { + await execFileAsync( + process.execPath, + [ + scriptPath, + '--changelog', + changelogPath, + '--version', + '13.51.0', + '--repository', + 'https://github.com/MetaMask/example', + '--prompt', + promptPath, + '--report', + reportPath, + ], + { + cwd: directory, + env: { + ...process.env, + AI_ANALYZER_LITELLM_KEY: 'litellm-key', + LITELLM_BASE_URL: `http://127.0.0.1:${port}`, + }, + }, + ); + } catch (error) { + exitCode = (error as { code?: number }).code ?? 1; + } + + return { + exitCode, + original, + changelog: readFileSync(changelogPath, 'utf8'), + report: JSON.parse(readFileSync(reportPath, 'utf8')), + }; + } finally { + server.closeAllConnections(); + server.close(); + rmSync(directory, { force: true, recursive: true }); } + } - return { - exitCode, - original, - changelog: readFileSync(changelogPath, 'utf8'), - report: JSON.parse(readFileSync(reportPath, 'utf8')), + /** + * Replies with a chat-completions body. + * + * @param content - The message content. + * @returns A responder for `runProofreader`. + */ + function respondWithContent(content: string) { + return (response: ServerResponse): void => { + response.setHeader('Content-Type', 'application/json'); + response.end(JSON.stringify({ choices: [{ message: { content } }] })); }; - } finally { - server.closeAllConnections(); - server.close(); - rmSync(directory, { force: true, recursive: true }); } -} - -/** - * Replies with a chat-completions body. - * - * @param content - The message content. - * @returns A responder for `runProofreader`. - */ -function respondWithContent(content: string) { - return (response: ServerResponse) => { - response.setHeader('Content-Type', 'application/json'); - response.end(JSON.stringify({ choices: [{ message: { content } }] })); - }; -} -test('writes the validated section and reports success', async () => { - const section = `## [13.51.0] + it('writes the validated section and reports success', async () => { + const section = `## [13.51.0] ### Added @@ -969,19 +950,18 @@ test('writes the validated section and reports success', async () => { ### Fixed - Fixed an issue (#102)`; - const result = await runProofreader(respondWithContent(section)); + const result = await runProofreader(respondWithContent(section)); - assert.equal(result.exitCode, 0); - assert.equal(result.report.status, 'succeeded'); - assert.equal( - result.changelog, - result.original.replace(generatedSection, section), - ); -}); + expect(result.exitCode).toBe(0); + expect(result.report.status).toBe('succeeded'); + expect(result.changelog).toBe( + result.original.replace(generatedSection, section), + ); + }); -test('leaves the changelog untouched when the model invents an entry', async () => { - const result = await runProofreader( - respondWithContent(`## [13.51.0] + it('leaves the changelog untouched when the model invents an entry', async () => { + const result = await runProofreader( + respondWithContent(`## [13.51.0] ### Added @@ -991,22 +971,25 @@ test('leaves the changelog untouched when the model invents an entry', async () ### Fixed - Fixed an issue (#102)`), - ); - - assert.equal(result.exitCode, 1); - assert.equal(result.report.status, 'failed'); - assert.equal(result.report.stage, 'cleaning'); - assert.match(String(result.report.error), /must be text followed by its PR/u); - assert.equal(result.changelog, result.original); -}); + ); -test('leaves the changelog untouched when LiteLLM rejects the key', async () => { - const result = await runProofreader((response) => { - response.statusCode = 401; - response.end('{}'); + expect(result.exitCode).toBe(1); + expect(result.report.status).toBe('failed'); + expect(result.report.stage).toBe('cleaning'); + expect(String(result.report.error)).toMatch( + /must be text followed by its PR/u, + ); + expect(result.changelog).toBe(result.original); }); - assert.equal(result.exitCode, 1); - assert.equal(result.report.stage, 'authentication'); - assert.equal(result.changelog, result.original); + it('leaves the changelog untouched when LiteLLM rejects the key', async () => { + const result = await runProofreader((response) => { + response.statusCode = 401; + response.end('{}'); + }); + + expect(result.exitCode).toBe(1); + expect(result.report.stage).toBe('authentication'); + expect(result.changelog).toBe(result.original); + }); }); diff --git a/.github/scripts/tests/merge-previous-releases.test.mts b/.github/scripts/tests/merge-previous-releases.test.mts index dbe69fb4..e1898559 100644 --- a/.github/scripts/tests/merge-previous-releases.test.mts +++ b/.github/scripts/tests/merge-previous-releases.test.mts @@ -1,4 +1,3 @@ -import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; import { chmodSync, @@ -10,198 +9,199 @@ import { } from 'node:fs'; import { tmpdir } from 'node:os'; import { delimiter, join } from 'node:path'; -import test, { after } from 'node:test'; +import { afterAll, describe, expect, it } from 'vitest'; import { getGitTestEnvironment, git } from './git-test-environment.mts'; -const SCRIPT_PATH = join( - process.cwd(), - '.github', - 'scripts', - 'merge-previous-releases.sh', -); - -const TEMPORARY_DIRECTORY = mkdtempSync( - join(tmpdir(), 'previous-release-merge-'), -); -after(() => rmSync(TEMPORARY_DIRECTORY, { force: true, recursive: true })); - -/** - * Creates an origin repository with a `main`, an older active release, and a - * new release branch, plus a clone and a fake `gh` for running the script. - * @param changelogs - The changelogs for the two release branches. - * @param changelogs.sourceChangelog - The older release branch's changelog. - * @param changelogs.destinationChangelog - The new release branch's changelog. - * @returns The clone directory and functions to run the script and read the - * resulting changelog. - */ -function createReleaseMergeFixture({ - sourceChangelog, - destinationChangelog, -}: { - sourceChangelog: string; - destinationChangelog: string; -}) { - const directory = mkdtempSync(join(TEMPORARY_DIRECTORY, 'fixture-')); - const originDirectory = join(directory, 'origin'); - const workDirectory = join(directory, 'work'); - const binDirectory = join(directory, 'bin'); - - git(directory, 'init', '--initial-branch', 'main', originDirectory); - writeFileSync( - join(originDirectory, 'CHANGELOG.md'), - '# Changelog\n\n## [13.53.0]\n\n- Existing entry (#1)\n', +describe('merge-previous-releases', () => { + const SCRIPT_PATH = join( + process.cwd(), + '.github', + 'scripts', + 'merge-previous-releases.sh', ); - git(originDirectory, 'add', 'CHANGELOG.md'); - git(originDirectory, 'commit', '-m', 'Initial changelog'); - - for (const [branch, changelog] of Object.entries({ - 'release/13.54.0': sourceChangelog, - 'release/13.55.0': destinationChangelog, - })) { - git(originDirectory, 'switch', '-c', branch, 'main'); - writeFileSync(join(originDirectory, 'CHANGELOG.md'), changelog); - git(originDirectory, 'commit', '-am', `Update ${branch} changelog`); - } - // Leave `main` checked out so the script can push the release branch. - git(originDirectory, 'switch', 'main'); - - // Check out LF on Windows too, matching the Linux runners. - git( - directory, - 'clone', - '-c', - 'core.autocrlf=false', - '--branch', - 'release/13.55.0', - originDirectory, - workDirectory, - ); - - mkdirSync(binDirectory); - const ghPath = join(binDirectory, 'gh'); - writeFileSync( - ghPath, - '#!/usr/bin/env bash\nprintf "%s\\n" release/13.54.0\n', - ); - chmodSync(ghPath, 0o755); - - return { - workDirectory, - run: () => - execFileSync('bash', [SCRIPT_PATH], { - cwd: workDirectory, - env: { - ...getGitTestEnvironment(), - NEW_RELEASE_BRANCH: 'release/13.55.0', - GITHUB_TOKEN: 'test-token', - PATH: `${binDirectory}${delimiter}${process.env.PATH ?? ''}`, - }, - stdio: 'pipe', - }), - readChangelog: () => - readFileSync(join(workDirectory, 'CHANGELOG.md'), 'utf8'), - }; -} - -test('preserves changelog history from an older active release branch', () => { - // 13.54.0 is the source's oldest section, so it ends at the link references. - const fixture = createReleaseMergeFixture({ - sourceChangelog: - '# Changelog\n\n## [Unreleased]\n\n## [13.54.0]\n\n- Released entry (#2)\n\n[Unreleased]: https://example.com/HEAD\n[13.54.0]: https://example.com/13.54.0\n', - destinationChangelog: - '# Changelog\n\n## [Unreleased]\n\n## [13.53.0]\n\n- Destination-only entry (#3)\n\n[Unreleased]: https://example.com/HEAD\n[13.53.0]: https://example.com/13.53.0\n', - }); - - fixture.run(); - assert.equal( - fixture.readChangelog(), - '# Changelog\n\n## [Unreleased]\n\n## [13.54.0]\n\n- Released entry (#2)\n\n## [13.53.0]\n\n- Destination-only entry (#3)\n\n[Unreleased]: https://example.com/HEAD\n[13.54.0]: https://example.com/13.54.0\n[13.53.0]: https://example.com/13.53.0\n', + const TEMPORARY_DIRECTORY = mkdtempSync( + join(tmpdir(), 'previous-release-merge-'), ); - assert.doesNotThrow(() => + afterAll(() => rmSync(TEMPORARY_DIRECTORY, { force: true, recursive: true })); + + /** + * Creates an origin repository with a `main`, an older active release, and a + * new release branch, plus a clone and a fake `gh` for running the script. + * @param changelogs - The changelogs for the two release branches. + * @param changelogs.sourceChangelog - The older release branch's changelog. + * @param changelogs.destinationChangelog - The new release branch's changelog. + * @returns The clone directory and functions to run the script and read the + * resulting changelog. + */ + function createReleaseMergeFixture({ + sourceChangelog, + destinationChangelog, + }: { + sourceChangelog: string; + destinationChangelog: string; + }): { + workDirectory: string; + run: () => Buffer; + readChangelog: () => string; + } { + const directory = mkdtempSync(join(TEMPORARY_DIRECTORY, 'fixture-')); + const originDirectory = join(directory, 'origin'); + const workDirectory = join(directory, 'work'); + const binDirectory = join(directory, 'bin'); + + git(directory, 'init', '--initial-branch', 'main', originDirectory); + writeFileSync( + join(originDirectory, 'CHANGELOG.md'), + '# Changelog\n\n## [13.53.0]\n\n- Existing entry (#1)\n', + ); + git(originDirectory, 'add', 'CHANGELOG.md'); + git(originDirectory, 'commit', '-m', 'Initial changelog'); + + for (const [branch, changelog] of Object.entries({ + 'release/13.54.0': sourceChangelog, + 'release/13.55.0': destinationChangelog, + })) { + git(originDirectory, 'switch', '-c', branch, 'main'); + writeFileSync(join(originDirectory, 'CHANGELOG.md'), changelog); + git(originDirectory, 'commit', '-am', `Update ${branch} changelog`); + } + // Leave `main` checked out so the script can push the release branch. + git(originDirectory, 'switch', 'main'); + + // Check out LF on Windows too, matching the Linux runners. git( - fixture.workDirectory, - 'merge-base', - '--is-ancestor', - 'origin/release/13.54.0', - 'HEAD', - ), - ); -}); + directory, + 'clone', + '-c', + 'core.autocrlf=false', + '--branch', + 'release/13.55.0', + originDirectory, + workDirectory, + ); + + mkdirSync(binDirectory); + const ghPath = join(binDirectory, 'gh'); + writeFileSync( + ghPath, + '#!/usr/bin/env bash\nprintf "%s\\n" release/13.54.0\n', + ); + chmodSync(ghPath, 0o755); + + return { + workDirectory, + run: (): Buffer => + execFileSync('bash', [SCRIPT_PATH], { + cwd: workDirectory, + env: { + ...getGitTestEnvironment(), + NEW_RELEASE_BRANCH: 'release/13.55.0', + GITHUB_TOKEN: 'test-token', + PATH: `${binDirectory}${delimiter}${process.env.PATH ?? ''}`, + }, + stdio: 'pipe', + }), + readChangelog: (): string => + readFileSync(join(workDirectory, 'CHANGELOG.md'), 'utf8'), + }; + } -test('preserves changelog history when the source changelog exceeds the default process buffer', () => { - // 80,000 lines is about 1.3 MiB, above the 1 MiB default of execFileSync. - const padding = '- Padding entry (#5)\n'.repeat(80_000); - const fixture = createReleaseMergeFixture({ - sourceChangelog: `# Changelog\n\n## [13.54.0]\n\n- Released entry (#2)\n\n## [13.52.0]\n\n${padding}`, - destinationChangelog: - '# Changelog\n\n## [13.53.0]\n\n- Destination-only entry (#3)\n', + it('preserves changelog history from an older active release branch', () => { + // 13.54.0 is the source's oldest section, so it ends at the link references. + const fixture = createReleaseMergeFixture({ + sourceChangelog: + '# Changelog\n\n## [Unreleased]\n\n## [13.54.0]\n\n- Released entry (#2)\n\n[Unreleased]: https://example.com/HEAD\n[13.54.0]: https://example.com/13.54.0\n', + destinationChangelog: + '# Changelog\n\n## [Unreleased]\n\n## [13.53.0]\n\n- Destination-only entry (#3)\n\n[Unreleased]: https://example.com/HEAD\n[13.53.0]: https://example.com/13.53.0\n', + }); + + fixture.run(); + + expect(fixture.readChangelog()).toBe( + '# Changelog\n\n## [Unreleased]\n\n## [13.54.0]\n\n- Released entry (#2)\n\n## [13.53.0]\n\n- Destination-only entry (#3)\n\n[Unreleased]: https://example.com/HEAD\n[13.54.0]: https://example.com/13.54.0\n[13.53.0]: https://example.com/13.53.0\n', + ); + expect(() => + git( + fixture.workDirectory, + 'merge-base', + '--is-ancestor', + 'origin/release/13.54.0', + 'HEAD', + ), + ).not.toThrow(); }); - fixture.run(); + it('preserves changelog history when the source changelog exceeds the default process buffer', () => { + // 80,000 lines is about 1.3 MiB, above the 1 MiB default of execFileSync. + const padding = '- Padding entry (#5)\n'.repeat(80_000); + const fixture = createReleaseMergeFixture({ + sourceChangelog: `# Changelog\n\n## [13.54.0]\n\n- Released entry (#2)\n\n## [13.52.0]\n\n${padding}`, + destinationChangelog: + '# Changelog\n\n## [13.53.0]\n\n- Destination-only entry (#3)\n', + }); - assert.equal( - fixture.readChangelog(), - '# Changelog\n\n## [13.54.0]\n\n- Released entry (#2)\n\n## [13.53.0]\n\n- Destination-only entry (#3)\n', - ); -}); + fixture.run(); -test('preserves destination changelog when the source section is ambiguous', () => { - const destinationChangelog = - '# Changelog\n\n## [13.53.0]\n\n- Destination-only entry (#3)\n'; - const fixture = createReleaseMergeFixture({ - sourceChangelog: - '# Changelog\n\n## [13.54.0]\n\n- First entry (#2)\n\n## [13.54.0]\n\n- Duplicate entry (#4)\n', - destinationChangelog, + expect(fixture.readChangelog()).toBe( + '# Changelog\n\n## [13.54.0]\n\n- Released entry (#2)\n\n## [13.53.0]\n\n- Destination-only entry (#3)\n', + ); }); - fixture.run(); + it('preserves destination changelog when the source section is ambiguous', () => { + const destinationChangelog = + '# Changelog\n\n## [13.53.0]\n\n- Destination-only entry (#3)\n'; + const fixture = createReleaseMergeFixture({ + sourceChangelog: + '# Changelog\n\n## [13.54.0]\n\n- First entry (#2)\n\n## [13.54.0]\n\n- Duplicate entry (#4)\n', + destinationChangelog, + }); - assert.equal(fixture.readChangelog(), destinationChangelog); -}); + fixture.run(); -test('preserves destination changelog when it already has the release section', () => { - const destinationChangelog = - '# Changelog\n\n## [13.54.0]\n\n- Destination entry (#3)\n'; - const fixture = createReleaseMergeFixture({ - sourceChangelog: '# Changelog\n\n## [13.54.0]\n\n- Released entry (#2)\n', - destinationChangelog, + expect(fixture.readChangelog()).toBe(destinationChangelog); }); - fixture.run(); + it('preserves destination changelog when it already has the release section', () => { + const destinationChangelog = + '# Changelog\n\n## [13.54.0]\n\n- Destination entry (#3)\n'; + const fixture = createReleaseMergeFixture({ + sourceChangelog: '# Changelog\n\n## [13.54.0]\n\n- Released entry (#2)\n', + destinationChangelog, + }); - assert.equal(fixture.readChangelog(), destinationChangelog); -}); + fixture.run(); -test('moves the Unreleased link to the restored release', () => { - const compare = 'https://example.com/compare/'; - const fixture = createReleaseMergeFixture({ - sourceChangelog: `# Changelog\n\n## [Unreleased]\n\n## [13.54.0]\n\n- Released entry (#2)\n\n## [13.53.0]\n\n- Existing entry (#1)\n\n[Unreleased]: ${compare}v13.54.0...HEAD\n[13.54.0]: ${compare}v13.53.0...v13.54.0\n[13.53.0]: ${compare}v13.52.0...v13.53.0\n`, - destinationChangelog: `# Changelog\n\n## [Unreleased]\n\n## [13.53.0]\n\n- Existing entry (#1)\n\n[Unreleased]: ${compare}v13.53.0...HEAD\n[13.53.0]: ${compare}v13.52.0...v13.53.0\n`, + expect(fixture.readChangelog()).toBe(destinationChangelog); }); - fixture.run(); + it('moves the Unreleased link to the restored release', () => { + const compare = 'https://example.com/compare/'; + const fixture = createReleaseMergeFixture({ + sourceChangelog: `# Changelog\n\n## [Unreleased]\n\n## [13.54.0]\n\n- Released entry (#2)\n\n## [13.53.0]\n\n- Existing entry (#1)\n\n[Unreleased]: ${compare}v13.54.0...HEAD\n[13.54.0]: ${compare}v13.53.0...v13.54.0\n[13.53.0]: ${compare}v13.52.0...v13.53.0\n`, + destinationChangelog: `# Changelog\n\n## [Unreleased]\n\n## [13.53.0]\n\n- Existing entry (#1)\n\n[Unreleased]: ${compare}v13.53.0...HEAD\n[13.53.0]: ${compare}v13.52.0...v13.53.0\n`, + }); - assert.equal( - fixture.readChangelog(), - `# Changelog\n\n## [Unreleased]\n\n## [13.54.0]\n\n- Released entry (#2)\n\n## [13.53.0]\n\n- Existing entry (#1)\n\n[Unreleased]: ${compare}v13.54.0...HEAD\n[13.54.0]: ${compare}v13.53.0...v13.54.0\n[13.53.0]: ${compare}v13.52.0...v13.53.0\n`, - ); -}); + fixture.run(); -test('keeps an Unreleased link that already starts from a newer release', () => { - const compare = 'https://example.com/compare/'; - const destinationLinks = `[Unreleased]: ${compare}v13.55.0...HEAD\n[13.55.0]: ${compare}v13.53.0...v13.55.0\n[13.53.0]: ${compare}v13.52.0...v13.53.0\n`; - const fixture = createReleaseMergeFixture({ - sourceChangelog: `# Changelog\n\n## [Unreleased]\n\n## [13.54.0]\n\n- Released entry (#2)\n\n[Unreleased]: ${compare}v13.54.0...HEAD\n[13.54.0]: ${compare}v13.53.0...v13.54.0\n`, - destinationChangelog: `# Changelog\n\n## [Unreleased]\n\n## [13.55.0]\n\n- New entry (#4)\n\n## [13.53.0]\n\n- Existing entry (#1)\n\n${destinationLinks}`, + expect(fixture.readChangelog()).toBe( + `# Changelog\n\n## [Unreleased]\n\n## [13.54.0]\n\n- Released entry (#2)\n\n## [13.53.0]\n\n- Existing entry (#1)\n\n[Unreleased]: ${compare}v13.54.0...HEAD\n[13.54.0]: ${compare}v13.53.0...v13.54.0\n[13.53.0]: ${compare}v13.52.0...v13.53.0\n`, + ); }); - fixture.run(); + it('keeps an Unreleased link that already starts from a newer release', () => { + const compare = 'https://example.com/compare/'; + const destinationLinks = `[Unreleased]: ${compare}v13.55.0...HEAD\n[13.55.0]: ${compare}v13.53.0...v13.55.0\n[13.53.0]: ${compare}v13.52.0...v13.53.0\n`; + const fixture = createReleaseMergeFixture({ + sourceChangelog: `# Changelog\n\n## [Unreleased]\n\n## [13.54.0]\n\n- Released entry (#2)\n\n[Unreleased]: ${compare}v13.54.0...HEAD\n[13.54.0]: ${compare}v13.53.0...v13.54.0\n`, + destinationChangelog: `# Changelog\n\n## [Unreleased]\n\n## [13.55.0]\n\n- New entry (#4)\n\n## [13.53.0]\n\n- Existing entry (#1)\n\n${destinationLinks}`, + }); - assert.ok( - fixture - .readChangelog() - .includes(`[Unreleased]: ${compare}v13.55.0...HEAD\n`), - ); + fixture.run(); + + expect(fixture.readChangelog()).toContain( + `[Unreleased]: ${compare}v13.55.0...HEAD\n`, + ); + }); }); diff --git a/.github/scripts/tests/release-section.test.mts b/.github/scripts/tests/release-section.test.mts index e49bcd90..e28dc5d4 100644 --- a/.github/scripts/tests/release-section.test.mts +++ b/.github/scripts/tests/release-section.test.mts @@ -1,5 +1,4 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; +import { describe, expect, it } from 'vitest'; import { extractReleaseSection, @@ -12,27 +11,26 @@ import { restoreGeneratedCategories, } from '../release-section.mts'; -test('finds the heading line even when its text appears earlier', () => { - const changelog = - '\n\n## [1.0.0]\n\n- Real entry (#1)\n\n## [0.9.0]\n'; +describe('release-section', () => { + it('finds the heading line even when its text appears earlier', () => { + const changelog = + '\n\n## [1.0.0]\n\n- Real entry (#1)\n\n## [0.9.0]\n'; - assert.equal( - extractReleaseSection(changelog, '1.0.0').section, - '## [1.0.0]\n\n- Real entry (#1)', - ); -}); + expect(extractReleaseSection(changelog, '1.0.0').section).toBe( + '## [1.0.0]\n\n- Real entry (#1)', + ); + }); -test('writes a replacement in the changelog line endings', () => { - const changelog = '## [1.0.0]\r\n\r\n- Old (#1)\r\n\r\n## [0.9.0]\r\n'; + it('writes a replacement in the changelog line endings', () => { + const changelog = '## [1.0.0]\r\n\r\n- Old (#1)\r\n\r\n## [0.9.0]\r\n'; - assert.equal( - replaceReleaseSection(changelog, '1.0.0', '## [1.0.0]\n\n- New (#1)'), - '## [1.0.0]\r\n\r\n- New (#1)\r\n\r\n## [0.9.0]\r\n', - ); -}); + expect( + replaceReleaseSection(changelog, '1.0.0', '## [1.0.0]\n\n- New (#1)'), + ).toBe('## [1.0.0]\r\n\r\n- New (#1)\r\n\r\n## [0.9.0]\r\n'); + }); -test('isolates newly generated entries without changing the existing release section', () => { - const existingSection = `## [13.51.0] + it('isolates newly generated entries without changing the existing release section', () => { + const existingSection = `## [13.51.0] ### Added @@ -41,7 +39,7 @@ test('isolates newly generated entries without changing the existing release sec ### Fixed - Fixed an existing issue (#102)`; - const generatedSection = `## [13.51.0] + const generatedSection = `## [13.51.0] ### Added @@ -52,27 +50,24 @@ test('isolates newly generated entries without changing the existing release sec - Reworded existing issue (#102)`; - const newEntriesSection = getNewReleaseEntriesSection({ - existingSection, - generatedSection, - version: '13.51.0', - }); + const newEntriesSection = getNewReleaseEntriesSection({ + existingSection, + generatedSection, + version: '13.51.0', + }); - assert.equal( - newEntriesSection, - `## [13.51.0] + expect(newEntriesSection).toBe(`## [13.51.0] ### Added -- Added a new feature (#103)`, - ); - assert.equal( - mergeNewReleaseEntries({ - existingSection, - newEntriesSection: newEntriesSection ?? '', - version: '13.51.0', - }), - `## [13.51.0] +- Added a new feature (#103)`); + expect( + mergeNewReleaseEntries({ + existingSection, + newEntriesSection: newEntriesSection as string, + version: '13.51.0', + }), + ).toBe(`## [13.51.0] ### Added @@ -81,12 +76,11 @@ test('isolates newly generated entries without changing the existing release sec ### Fixed -- Fixed an existing issue (#102)`, - ); -}); +- Fixed an existing issue (#102)`); + }); -test('merges new entries into matching categories and inserts missing ones in canonical order', () => { - const existingSection = `## [13.51.0] + it('merges new entries into matching categories and inserts missing ones in canonical order', () => { + const existingSection = `## [13.51.0] ### Added @@ -97,10 +91,10 @@ test('merges new entries into matching categories and inserts missing ones in ca - Fixed an existing issue (#102) with a continuation line`; - assert.equal( - mergeNewReleaseEntries({ - existingSection, - newEntriesSection: `## [13.51.0] + expect( + mergeNewReleaseEntries({ + existingSection, + newEntriesSection: `## [13.51.0] ### Changed @@ -113,9 +107,9 @@ test('merges new entries into matching categories and inserts missing ones in ca ### Security - Hardened a thing (#105)`, - version: '13.51.0', - }), - `## [13.51.0] + version: '13.51.0', + }), + ).toBe(`## [13.51.0] ### Added @@ -133,221 +127,215 @@ test('merges new entries into matching categories and inserts missing ones in ca ### Security -- Hardened a thing (#105)`, - ); -}); +- Hardened a thing (#105)`); + }); -test('restores the generator category when the proofread wording has no known verb', () => { - assert.equal( - restoreGeneratedCategories({ - generatedSection: `## [1.0.0]\n\n### Added\n\n- Added a (#1)\n\n### Fixed\n\n- Fixed b (#2)\n\n### Uncategorized\n\n- Did c (#3)\n\n### Fixed\n\n- Fixed d (#4)`, - cleanedSection: `## [1.0.0]\n\n### Changed\n\n- Improved a (#1)\n- Improved c (#3)\n- Merged d and b (#2, #4)`, - version: '1.0.0', - }), - `## [1.0.0]\n\n### Added\n\n- Improved a (#1)\n\n### Changed\n\n- Improved c (#3)\n\n### Fixed\n\n- Merged d and b (#2, #4)`, - ); -}); + it('restores the generator category when the proofread wording has no known verb', () => { + expect( + restoreGeneratedCategories({ + generatedSection: `## [1.0.0]\n\n### Added\n\n- Added a (#1)\n\n### Fixed\n\n- Fixed b (#2)\n\n### Uncategorized\n\n- Did c (#3)\n\n### Fixed\n\n- Fixed d (#4)`, + cleanedSection: `## [1.0.0]\n\n### Changed\n\n- Improved a (#1)\n- Improved c (#3)\n- Merged d and b (#2, #4)`, + version: '1.0.0', + }), + ).toBe( + `## [1.0.0]\n\n### Added\n\n- Improved a (#1)\n\n### Changed\n\n- Improved c (#3)\n\n### Fixed\n\n- Merged d and b (#2, #4)`, + ); + }); -test('files an entry under the category its wording implies', () => { - assert.equal( - restoreGeneratedCategories({ - generatedSection: `## [1.0.0]\n\n### Removed\n\n- Removed a bar (#1)\n\n### Fixed\n\n- Fixed a crash (#2)`, - cleanedSection: `## [1.0.0]\n\n### Removed\n\n- Fixed the bar layout (#1)\n\n### Fixed\n\n- Added support for X (#2)`, - version: '1.0.0', - }), - `## [1.0.0]\n\n### Added\n\n- Added support for X (#2)\n\n### Fixed\n\n- Fixed the bar layout (#1)`, - ); -}); + it('files an entry under the category its wording implies', () => { + expect( + restoreGeneratedCategories({ + generatedSection: `## [1.0.0]\n\n### Removed\n\n- Removed a bar (#1)\n\n### Fixed\n\n- Fixed a crash (#2)`, + cleanedSection: `## [1.0.0]\n\n### Removed\n\n- Fixed the bar layout (#1)\n\n### Fixed\n\n- Added support for X (#2)`, + version: '1.0.0', + }), + ).toBe( + `## [1.0.0]\n\n### Added\n\n- Added support for X (#2)\n\n### Fixed\n\n- Fixed the bar layout (#1)`, + ); + }); -test("shortens only this repository's long PR links", () => { - const repositoryUrl = 'https://github.com/MetaMask/metamask-mobile'; - assert.equal( - normalizeRepositoryPrLinks( + it("shortens only this repository's long PR links", () => { + const repositoryUrl = 'https://github.com/MetaMask/metamask-mobile'; + expect( + normalizeRepositoryPrLinks( + [ + '- Own link ([#1](https://github.com/MetaMask/metamask-mobile/pull/1))', + '- Two links ([#2](https://github.com/MetaMask/metamask-mobile/pull/2), [#3](https://github.com/MetaMask/metamask-mobile/pull/3))', + '- Legacy groups ([#4](https://github.com/MetaMask/metamask-mobile/pull/4)), ([#5](https://github.com/MetaMask/metamask-mobile/pull/5))', + '- Other repo ([#6](https://github.com/MetaMask/core/pull/6))', + '- Already short (#7)', + ].join('\r\n'), + repositoryUrl, + ), + ).toBe( [ - '- Own link ([#1](https://github.com/MetaMask/metamask-mobile/pull/1))', - '- Two links ([#2](https://github.com/MetaMask/metamask-mobile/pull/2), [#3](https://github.com/MetaMask/metamask-mobile/pull/3))', - '- Legacy groups ([#4](https://github.com/MetaMask/metamask-mobile/pull/4)), ([#5](https://github.com/MetaMask/metamask-mobile/pull/5))', + '- Own link (#1)', + '- Two links (#2, #3)', + '- Legacy groups (#4, #5)', '- Other repo ([#6](https://github.com/MetaMask/core/pull/6))', '- Already short (#7)', ].join('\r\n'), - repositoryUrl, - ), - [ - '- Own link (#1)', - '- Two links (#2, #3)', - '- Legacy groups (#4, #5)', - '- Other repo ([#6](https://github.com/MetaMask/core/pull/6))', - '- Already short (#7)', - ].join('\r\n'), - ); -}); + ); + }); -test('treats a long-link entry in the existing section as documented', () => { - assert.equal( - getNewReleaseEntriesSection({ - existingSection: `## [1.0.0]\n\n### Added\n\n- Added a ([#1](https://github.com/MetaMask/metamask-mobile/pull/1))`, - generatedSection: `## [1.0.0]\n\n### Added\n\n- Added a (#1)\n- Added b (#2)`, - version: '1.0.0', - repositoryUrl: 'https://github.com/MetaMask/metamask-mobile', - }), - `## [1.0.0]\n\n### Added\n\n- Added b (#2)`, - ); -}); + it('treats a long-link entry in the existing section as documented', () => { + expect( + getNewReleaseEntriesSection({ + existingSection: `## [1.0.0]\n\n### Added\n\n- Added a ([#1](https://github.com/MetaMask/metamask-mobile/pull/1))`, + generatedSection: `## [1.0.0]\n\n### Added\n\n- Added a (#1)\n- Added b (#2)`, + version: '1.0.0', + repositoryUrl: 'https://github.com/MetaMask/metamask-mobile', + }), + ).toBe(`## [1.0.0]\n\n### Added\n\n- Added b (#2)`); + }); -test('matches an existing entry that has trailing whitespace', () => { - assert.equal( - getNewReleaseEntriesSection({ - existingSection: '## [1.0.0]\n\n### Added\n\n- Added a \n', - generatedSection: '## [1.0.0]\n\n### Added\n\n- Added a\n- Added b (#2)', - version: '1.0.0', - }), - '## [1.0.0]\n\n### Added\n\n- Added b (#2)', - ); -}); + it('matches an existing entry that has trailing whitespace', () => { + expect( + getNewReleaseEntriesSection({ + existingSection: '## [1.0.0]\n\n### Added\n\n- Added a \n', + generatedSection: + '## [1.0.0]\n\n### Added\n\n- Added a\n- Added b (#2)', + version: '1.0.0', + }), + ).toBe('## [1.0.0]\n\n### Added\n\n- Added b (#2)'); + }); -test('leaves out a PR a reviewer deleted', () => { - assert.equal( - getNewReleaseEntriesSection({ - existingSection: '## [1.0.0]\n\n### Added\n\n- Added a (#1)', - generatedSection: - '## [1.0.0]\n\n### Added\n\n- Added a (#1)\n- Added b (#2)\n- Added c (#3)', - version: '1.0.0', - deletedPrNumbers: new Set(['2']), - }), - '## [1.0.0]\n\n### Added\n\n- Added c (#3)', - ); -}); + it('leaves out a PR a reviewer deleted', () => { + expect( + getNewReleaseEntriesSection({ + existingSection: '## [1.0.0]\n\n### Added\n\n- Added a (#1)', + generatedSection: + '## [1.0.0]\n\n### Added\n\n- Added a (#1)\n- Added b (#2)\n- Added c (#3)', + version: '1.0.0', + deletedPrNumbers: new Set(['2']), + }), + ).toBe('## [1.0.0]\n\n### Added\n\n- Added c (#3)'); + }); -test('keeps the existing line ending when merging new entries', () => { - assert.equal( - mergeNewReleaseEntries({ - existingSection: '## [1.0.0]\r\n\r\n### Fixed\r\n\r\n- Old (#1)\r\n', - newEntriesSection: '## [1.0.0]\n\n### Added\n\n- New (#2)', - version: '1.0.0', - }), - '## [1.0.0]\r\n\r\n### Added\r\n\r\n- New (#2)\r\n\r\n### Fixed\r\n\r\n- Old (#1)', - ); -}); + it('keeps the existing line ending when merging new entries', () => { + expect( + mergeNewReleaseEntries({ + existingSection: '## [1.0.0]\r\n\r\n### Fixed\r\n\r\n- Old (#1)\r\n', + newEntriesSection: '## [1.0.0]\n\n### Added\n\n- New (#2)', + version: '1.0.0', + }), + ).toBe( + '## [1.0.0]\r\n\r\n### Added\r\n\r\n- New (#2)\r\n\r\n### Fixed\r\n\r\n- Old (#1)', + ); + }); -test('finds no new release entries when every generated PR is already documented', () => { - assert.equal( - getNewReleaseEntriesSection({ - existingSection: `## [13.51.0] + it('finds no new release entries when every generated PR is already documented', () => { + expect( + getNewReleaseEntriesSection({ + existingSection: `## [13.51.0] ### Fixed - Fixed an existing issue (#101)`, - generatedSection: `## [13.51.0] + generatedSection: `## [13.51.0] ### Fixed - Reworded existing issue (#101)`, - version: '13.51.0', - }), - undefined, - ); -}); + version: '13.51.0', + }), + ).toBeUndefined(); + }); -test('judges a generated entry by its last PR reference and demotes earlier mentions', () => { - const existingSection = `## [13.51.0] + it('judges a generated entry by its last PR reference and demotes earlier mentions', () => { + const existingSection = `## [13.51.0] ### Fixed - Fixed an existing issue (#101)`; - assert.equal( - getNewReleaseEntriesSection({ - existingSection, - generatedSection: `## [13.51.0] + expect( + getNewReleaseEntriesSection({ + existingSection, + generatedSection: `## [13.51.0] ### Fixed - Fixed a regression from (#101) and #100 (#102) see also #101`, - version: '13.51.0', - }), - `## [13.51.0] + version: '13.51.0', + }), + ).toBe(`## [13.51.0] ### Fixed - Fixed a regression from PR 101 and PR 100 (#102) - see also PR 101`, - ); - assert.equal( - getNewReleaseEntriesSection({ - existingSection, - generatedSection: `## [13.51.0] + see also PR 101`); + expect( + getNewReleaseEntriesSection({ + existingSection, + generatedSection: `## [13.51.0] ### Fixed - Reworded a documented PR that mentions (#102) (#101)`, - version: '13.51.0', - }), - undefined, - ); -}); + version: '13.51.0', + }), + ).toBeUndefined(); + }); -test('keeps a multi-PR group intact and demotes mentions before it', () => { - const existingSection = `## [13.51.0] + it('keeps a multi-PR group intact and demotes mentions before it', () => { + const existingSection = `## [13.51.0] ### Fixed - Fixed an existing issue (#101)`; - const generatedSection = (entry: string) => - `## [13.51.0] + const generatedSection = (entry: string): string => + `## [13.51.0] ### Fixed ${entry}`; - assert.equal( - getNewReleaseEntriesSection({ - existingSection, - generatedSection: generatedSection( - '- Fixed a regression from #100 (#102, #103)', - ), - version: '13.51.0', - }), - generatedSection('- Fixed a regression from PR 100 (#102, #103)'), - ); - assert.equal( - getNewReleaseEntriesSection({ - existingSection, - generatedSection: generatedSection( - '- Fixed legacy groups (#102), (#103)', - ), - version: '13.51.0', - }), - generatedSection('- Fixed legacy groups (#102), (#103)'), - ); -}); + expect( + getNewReleaseEntriesSection({ + existingSection, + generatedSection: generatedSection( + '- Fixed a regression from #100 (#102, #103)', + ), + version: '13.51.0', + }), + ).toBe(generatedSection('- Fixed a regression from PR 100 (#102, #103)')); + expect( + getNewReleaseEntriesSection({ + existingSection, + generatedSection: generatedSection( + '- Fixed legacy groups (#102), (#103)', + ), + version: '13.51.0', + }), + ).toBe(generatedSection('- Fixed legacy groups (#102), (#103)')); + }); -test('skips a grouped generated entry when any PR in its group is documented', () => { - const existingSection = `## [13.51.0]\n\n### Fixed\n\n- Fixed an existing issue (#101)`; + it('skips a grouped generated entry when any PR in its group is documented', () => { + const existingSection = `## [13.51.0]\n\n### Fixed\n\n- Fixed an existing issue (#101)`; - assert.equal( - getNewReleaseEntriesSection({ - existingSection, - generatedSection: `## [13.51.0]\n\n### Fixed\n\n- Fixed an issue (#101, #102)`, - version: '13.51.0', - }), - undefined, - ); - assert.equal( - getNewReleaseEntriesSection({ - existingSection, - generatedSection: `## [13.51.0]\n\n### Fixed\n\n- Fixed an issue (#102, #103)`, - version: '13.51.0', - deletedPrNumbers: new Set(['103']), - }), - undefined, - ); -}); + expect( + getNewReleaseEntriesSection({ + existingSection, + generatedSection: `## [13.51.0]\n\n### Fixed\n\n- Fixed an issue (#101, #102)`, + version: '13.51.0', + }), + ).toBeUndefined(); + expect( + getNewReleaseEntriesSection({ + existingSection, + generatedSection: `## [13.51.0]\n\n### Fixed\n\n- Fixed an issue (#102, #103)`, + version: '13.51.0', + deletedPrNumbers: new Set(['103']), + }), + ).toBeUndefined(); + }); -test('preserves the reviewed release section above historical predecessor history', () => { - assert.equal( - mergeCurrentReleaseSection({ - changelog: `# Changelog + it('preserves the reviewed release section above historical predecessor history', () => { + expect( + mergeCurrentReleaseSection({ + changelog: `# Changelog ## [13.50.0] @@ -355,14 +343,14 @@ test('preserves the reviewed release section above historical predecessor histor - Fixed an earlier issue (#100) `, - currentReleaseSection: `## [13.51.0] + currentReleaseSection: `## [13.51.0] ### Added - Added a current release feature (#101)`, - version: '13.51.0', - }), - `# Changelog + version: '13.51.0', + }), + ).toBe(`# Changelog ## [13.51.0] @@ -375,14 +363,13 @@ test('preserves the reviewed release section above historical predecessor histor ### Fixed - Fixed an earlier issue (#100) -`, - ); -}); +`); + }); -test('inserts the reviewed release section after the preamble and Unreleased heading', () => { - assert.equal( - mergeCurrentReleaseSection({ - changelog: `# Changelog + it('inserts the reviewed release section after the preamble and Unreleased heading', () => { + expect( + mergeCurrentReleaseSection({ + changelog: `# Changelog All notable changes to this project will be documented in this file. @@ -394,14 +381,14 @@ All notable changes to this project will be documented in this file. - Fixed an earlier issue (#100) `, - currentReleaseSection: `## [13.51.0] + currentReleaseSection: `## [13.51.0] ### Added - Added a current release feature (#101)`, - version: '13.51.0', - }), - `# Changelog + version: '13.51.0', + }), + ).toBe(`# Changelog All notable changes to this project will be documented in this file. @@ -418,11 +405,10 @@ All notable changes to this project will be documented in this file. ### Fixed - Fixed an earlier issue (#100) -`, - ); -}); +`); + }); -const stableShapedChangelog = `# Changelog + const stableShapedChangelog = `# Changelog All notable changes to this project will be documented in this file. @@ -448,226 +434,219 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [13.49.0]: https://github.com/MetaMask/metamask-extension/releases/tag/v13.49.0 `; -const reviewedSection = `## [13.51.0] + const reviewedSection = `## [13.51.0] ### Added - Added a current release feature (#101)`; -test('merges into a stable-shaped changelog without disturbing history or link references', () => { - const merged = mergeCurrentReleaseSection({ - changelog: stableShapedChangelog, - currentReleaseSection: reviewedSection, - version: '13.51.0', + it('merges into a stable-shaped changelog without disturbing history or link references', () => { + const merged = mergeCurrentReleaseSection({ + changelog: stableShapedChangelog, + currentReleaseSection: reviewedSection, + version: '13.51.0', + }); + + expect(merged).toBe( + stableShapedChangelog.replace( + '## [13.50.0]', + `${reviewedSection}\n\n## [13.50.0]`, + ), + ); + expect(extractReleaseSection(merged, '13.51.0').section).toBe( + reviewedSection, + ); + expect(merged.indexOf('## [Unreleased]')).toBeLessThan( + merged.indexOf('## [13.51.0]'), + ); + expect(merged.indexOf('## [13.51.0]')).toBeLessThan( + merged.indexOf('## [13.50.0]'), + ); }); - assert.equal( - merged, - stableShapedChangelog.replace( - '## [13.50.0]', - `${reviewedSection}\n\n## [13.50.0]`, - ), - ); - assert.equal( - extractReleaseSection(merged, '13.51.0').section, - reviewedSection, - ); - assert.ok(merged.indexOf('## [Unreleased]') < merged.indexOf('## [13.51.0]')); - assert.ok(merged.indexOf('## [13.51.0]') < merged.indexOf('## [13.50.0]')); -}); + it('keeps CRLF line endings when merging into a CRLF changelog', () => { + const merged = mergeCurrentReleaseSection({ + changelog: stableShapedChangelog.replaceAll('\n', '\r\n'), + currentReleaseSection: reviewedSection, + version: '13.51.0', + }); -test('keeps CRLF line endings when merging into a CRLF changelog', () => { - const merged = mergeCurrentReleaseSection({ - changelog: stableShapedChangelog.replaceAll('\n', '\r\n'), - currentReleaseSection: reviewedSection, - version: '13.51.0', + expect(merged.replaceAll('\r\n', '')).not.toContain('\n'); + expect(merged).toContain('## [13.51.0]\r\n\r\n### Added'); }); - assert.equal(merged.replaceAll('\r\n', '').includes('\n'), false); - assert.ok(merged.includes('## [13.51.0]\r\n\r\n### Added')); -}); + it('replaces an existing current heading instead of duplicating it', () => { + const once = mergeCurrentReleaseSection({ + changelog: stableShapedChangelog, + currentReleaseSection: reviewedSection, + version: '13.51.0', + }); + const twice = mergeCurrentReleaseSection({ + changelog: once, + currentReleaseSection: reviewedSection.replace('(#101)', '(#102)'), + version: '13.51.0', + }); -test('replaces an existing current heading instead of duplicating it', () => { - const once = mergeCurrentReleaseSection({ - changelog: stableShapedChangelog, - currentReleaseSection: reviewedSection, - version: '13.51.0', - }); - const twice = mergeCurrentReleaseSection({ - changelog: once, - currentReleaseSection: reviewedSection.replace('(#101)', '(#102)'), - version: '13.51.0', + expect(twice.match(/^## \[13\.51\.0\]$/gmu)?.length).toBe(1); + expect(twice).toMatch(/\(#102\)/u); + expect(twice).not.toMatch(/\(#101\)/u); }); - assert.equal(twice.match(/^## \[13\.51\.0\]$/gmu)?.length, 1); - assert.match(twice, /\(#102\)/u); - assert.doesNotMatch(twice, /\(#101\)/u); -}); + it('appends the reviewed section when the changelog has no releases yet', () => { + const merged = mergeCurrentReleaseSection({ + changelog: '# Changelog\n\n## [Unreleased]\n', + currentReleaseSection: reviewedSection, + version: '13.51.0', + }); -test('appends the reviewed section when the changelog has no releases yet', () => { - const merged = mergeCurrentReleaseSection({ - changelog: '# Changelog\n\n## [Unreleased]\n', - currentReleaseSection: reviewedSection, - version: '13.51.0', + expect(merged).toBe( + `# Changelog\n\n## [Unreleased]\n\n${reviewedSection}\n`, + ); }); - assert.equal( - merged, - `# Changelog\n\n## [Unreleased]\n\n${reviewedSection}\n`, - ); -}); + it('does not double carriage returns when inserting a CRLF section into a CRLF changelog', () => { + const merged = mergeCurrentReleaseSection({ + changelog: '# Changelog\r\n\r\n## [Unreleased]\r\n\r\n## [13.50.0]\r\n', + currentReleaseSection: + '## [13.51.0]\r\n\r\n### Added\r\n\r\n- Added it (#1)', + version: '13.51.0', + }); -test('does not double carriage returns when inserting a CRLF section into a CRLF changelog', () => { - const merged = mergeCurrentReleaseSection({ - changelog: '# Changelog\r\n\r\n## [Unreleased]\r\n\r\n## [13.50.0]\r\n', - currentReleaseSection: - '## [13.51.0]\r\n\r\n### Added\r\n\r\n- Added it (#1)', - version: '13.51.0', + expect(merged).not.toContain('\r\r'); + expect(merged).toBe( + '# Changelog\r\n\r\n## [Unreleased]\r\n\r\n## [13.51.0]\r\n\r\n### Added\r\n\r\n- Added it (#1)\r\n\r\n## [13.50.0]\r\n', + ); }); - assert.equal(merged.includes('\r\r'), false); - assert.equal( - merged, - '# Changelog\r\n\r\n## [Unreleased]\r\n\r\n## [13.51.0]\r\n\r\n### Added\r\n\r\n- Added it (#1)\r\n\r\n## [13.50.0]\r\n', - ); -}); - -test('keeps a reviewer entry without a PR reference out of the new entries', () => { - const existingSection = [ - '## [1.0.0]', - '', - '### Added', - '', - '- Updated translations', - '- Added a thing (#1)', - '', - '### Fixed', - '', - '- Fixed a thing (#1)', - ].join('\n'); - const generatedSection = existingSection.replace( - '- Added a thing (#1)', - '- Added a thing (#1)\n- Added another thing (#2)', - ); - - assert.equal( - getNewReleaseEntriesSection({ - existingSection, - generatedSection, - version: '1.0.0', - }), - '## [1.0.0]\n\n### Added\n\n- Added another thing (#2)', - ); -}); + it('keeps a reviewer entry without a PR reference out of the new entries', () => { + const existingSection = [ + '## [1.0.0]', + '', + '### Added', + '', + '- Updated translations', + '- Added a thing (#1)', + '', + '### Fixed', + '', + '- Fixed a thing (#1)', + ].join('\n'); + const generatedSection = existingSection.replace( + '- Added a thing (#1)', + '- Added a thing (#1)\n- Added another thing (#2)', + ); + + expect( + getNewReleaseEntriesSection({ + existingSection, + generatedSection, + version: '1.0.0', + }), + ).toBe('## [1.0.0]\n\n### Added\n\n- Added another thing (#2)'); + }); -test('still rejects a generated entry without a PR reference', () => { - assert.throws( - () => + it('still rejects a generated entry without a PR reference', () => { + expect(() => getNewReleaseEntriesSection({ existingSection: '## [1.0.0]\n\n### Added\n\n- Added a thing (#1)', generatedSection: '## [1.0.0]\n\n### Added\n\n- Added a thing (#1)\n- Mystery entry', version: '1.0.0', }), - /lacks a PR reference/u, - ); -}); + ).toThrow(/lacks a PR reference/u); + }); -test('rejects a changelog without the Changelog heading', () => { - assert.throws( - () => + it('rejects a changelog without the Changelog heading', () => { + expect(() => mergeCurrentReleaseSection({ changelog: '## [13.50.0]\n', currentReleaseSection: reviewedSection, version: '13.51.0', }), - /must begin with a Changelog heading/u, - ); -}); + ).toThrow(/must begin with a Changelog heading/u); + }); -test('ends the oldest release section before the link references', () => { - const changelog = [ - '# Changelog', - '', - '## [Unreleased]', - '', - '## [13.51.0]', - '', - '### Fixed', - '', - '- Fixed an issue (#101)', - '', - '[Unreleased]: https://example.com/HEAD', - '[13.51.0]: https://example.com/13.51.0', - '', - ].join('\n'); - - assert.equal( - extractReleaseSection(changelog, '13.51.0').section, - '## [13.51.0]\n\n### Fixed\n\n- Fixed an issue (#101)', - ); - assert.equal( - replaceReleaseSection( - changelog, - '13.51.0', - '## [13.51.0]\n\n### Added\n\n- Added a feature (#102)', - ), - changelog - .replace('### Fixed', '### Added') - .replace('Fixed an issue (#101)', 'Added a feature (#102)'), - ); -}); + it('ends the oldest release section before the link references', () => { + const changelog = [ + '# Changelog', + '', + '## [Unreleased]', + '', + '## [13.51.0]', + '', + '### Fixed', + '', + '- Fixed an issue (#101)', + '', + '[Unreleased]: https://example.com/HEAD', + '[13.51.0]: https://example.com/13.51.0', + '', + ].join('\n'); + + expect(extractReleaseSection(changelog, '13.51.0').section).toBe( + '## [13.51.0]\n\n### Fixed\n\n- Fixed an issue (#101)', + ); + expect( + replaceReleaseSection( + changelog, + '13.51.0', + '## [13.51.0]\n\n### Added\n\n- Added a feature (#102)', + ), + ).toBe( + changelog + .replace('### Fixed', '### Added') + .replace('Fixed an issue (#101)', 'Added a feature (#102)'), + ); + }); -test('removes the entries owning the given PRs and drops emptied categories', () => { - const section = [ - '## [2.0.0]', - '', - '### Added', - '', - '- Added a thing (#1)', - '', - '### Fixed', - '', - '- Fixed one (#2)', - ' more detail', - '- Fixed two (#3)', - ].join('\n'); - - assert.equal( - removeReleaseEntries({ section, prNumbers: new Set(['1', '2']) }), - ['## [2.0.0]', '', '### Fixed', '', '- Fixed two (#3)'].join('\n'), - ); - assert.equal( - removeReleaseEntries({ section, prNumbers: new Set(['1', '2', '3']) }), - '## [2.0.0]', - ); -}); + it('removes the entries owning the given PRs and drops emptied categories', () => { + const section = [ + '## [2.0.0]', + '', + '### Added', + '', + '- Added a thing (#1)', + '', + '### Fixed', + '', + '- Fixed one (#2)', + ' more detail', + '- Fixed two (#3)', + ].join('\n'); + + expect( + removeReleaseEntries({ section, prNumbers: new Set(['1', '2']) }), + ).toBe(['## [2.0.0]', '', '### Fixed', '', '- Fixed two (#3)'].join('\n')); + expect( + removeReleaseEntries({ section, prNumbers: new Set(['1', '2', '3']) }), + ).toBe('## [2.0.0]'); + }); -test('keeps an entry that owns a PR outside the given PRs', () => { - const section = [ - '## [2.0.0]', - '', - '### Fixed', - '', - '- Fixed from (#1) (#2)', - '- Fixed together (#3, #4)', - ].join('\n'); - - assert.equal( - removeReleaseEntries({ section, prNumbers: new Set(['1', '3']) }), - section, - ); - assert.equal( - removeReleaseEntries({ section, prNumbers: new Set(['3', '4']) }), - ['## [2.0.0]', '', '### Fixed', '', '- Fixed from (#1) (#2)'].join('\n'), - ); -}); + it('keeps an entry that owns a PR outside the given PRs', () => { + const section = [ + '## [2.0.0]', + '', + '### Fixed', + '', + '- Fixed from (#1) (#2)', + '- Fixed together (#3, #4)', + ].join('\n'); + + expect( + removeReleaseEntries({ section, prNumbers: new Set(['1', '3']) }), + ).toBe(section); + expect( + removeReleaseEntries({ section, prNumbers: new Set(['3', '4']) }), + ).toBe( + ['## [2.0.0]', '', '### Fixed', '', '- Fixed from (#1) (#2)'].join('\n'), + ); + }); -test('leaves the section untouched when no entry matches', () => { - const section = '## [2.0.0]\n\n### Added\n\n- Added a thing (#1)'; + it('leaves the section untouched when no entry matches', () => { + const section = '## [2.0.0]\n\n### Added\n\n- Added a thing (#1)'; - assert.equal( - removeReleaseEntries({ section, prNumbers: new Set(['9']) }), - section, - ); + expect(removeReleaseEntries({ section, prNumbers: new Set(['9']) })).toBe( + section, + ); + }); }); diff --git a/.github/scripts/tests/release-version-utils.test.mts b/.github/scripts/tests/release-version-utils.test.mts index 272819bf..02a0f73f 100644 --- a/.github/scripts/tests/release-version-utils.test.mts +++ b/.github/scripts/tests/release-version-utils.test.mts @@ -1,5 +1,4 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; +import { describe, expect, it } from 'vitest'; import { compareSemver, @@ -7,47 +6,46 @@ import { selectHighestLowerVersion, } from '../release-version-utils.mts'; -test('parses supported native and OTA release branches', () => { - assert.deepEqual(parseReleaseBranch('release/13.50.3'), { - version: '13.50.3', - kind: 'native', - name: 'release/13.50.3', +describe('release-version-utils', () => { + it('parses supported native and OTA release branches', () => { + expect(parseReleaseBranch('release/13.50.3')).toStrictEqual({ + version: '13.50.3', + kind: 'native', + name: 'release/13.50.3', + }); + expect(parseReleaseBranch('release/13.50.3-ota')).toStrictEqual({ + version: '13.50.3', + kind: 'ota', + name: 'release/13.50.3-ota', + }); }); - assert.deepEqual(parseReleaseBranch('release/13.50.3-ota'), { - version: '13.50.3', - kind: 'ota', - name: 'release/13.50.3-ota', - }); -}); -test('rejects unsupported release branch names', () => { - assert.equal(parseReleaseBranch('release/13.50.3-fallback'), undefined); - assert.equal(parseReleaseBranch('release/13.50.3.1'), undefined); -}); + it('rejects unsupported release branch names', () => { + expect(parseReleaseBranch('release/13.50.3-fallback')).toBeUndefined(); + expect(parseReleaseBranch('release/13.50.3.1')).toBeUndefined(); + }); -test('compares all semantic version components numerically', () => { - assert.equal(compareSemver('13.50.3', '13.50.2'), 1); - assert.equal(compareSemver('13.50.3', '13.50.3'), 0); - assert.equal(compareSemver('13.50.3', '13.51.0'), -1); -}); + it('compares all semantic version components numerically', () => { + expect(compareSemver('13.50.3', '13.50.2')).toBe(1); + expect(compareSemver('13.50.3', '13.50.3')).toBe(0); + expect(compareSemver('13.50.3', '13.51.0')).toBe(-1); + }); -test('selects the highest strict predecessor', () => { - assert.equal( - selectHighestLowerVersion('13.51.0', [ - '13.49.0', - '13.50.0', + it('selects the highest strict predecessor', () => { + expect( + selectHighestLowerVersion('13.51.0', [ + '13.49.0', + '13.50.0', + '13.50.3', + '13.51.0', + '13.52.0', + ]), + ).toBe('13.50.3'); + expect(selectHighestLowerVersion('13.50.4', ['13.50.2', '13.50.3'])).toBe( '13.50.3', - '13.51.0', - '13.52.0', - ]), - '13.50.3', - ); - assert.equal( - selectHighestLowerVersion('13.50.4', ['13.50.2', '13.50.3']), - '13.50.3', - ); - assert.equal( - selectHighestLowerVersion('13.51.0', ['13.51.0', '13.51.1', '14.0.0']), - undefined, - ); + ); + expect( + selectHighestLowerVersion('13.51.0', ['13.51.0', '13.51.1', '14.0.0']), + ).toBeUndefined(); + }); }); diff --git a/.github/scripts/tests/retry.test.mts b/.github/scripts/tests/retry.test.mts index 75077519..0d5e359d 100644 --- a/.github/scripts/tests/retry.test.mts +++ b/.github/scripts/tests/retry.test.mts @@ -1,55 +1,43 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; +import { describe, expect, it, vi } from 'vitest'; import { retry } from '../shared/retry.mts'; -test('retries an operation with increasing delays', async () => { - let attempts = 0; - const delays: number[] = []; - const result = await retry( - async () => { - attempts += 1; - if (attempts < 3) { - throw new Error('Transient failure'); - } - return 'recovered'; - }, - { +describe('retry', () => { + it('retries an operation with increasing delays', async () => { + const operation = vi + .fn<() => Promise>() + .mockRejectedValueOnce(new Error('Transient failure')) + .mockRejectedValueOnce(new Error('Transient failure')) + .mockResolvedValue('recovered'); + const delays: number[] = []; + const result = await retry(operation, { delayMilliseconds: 100, sleep: async (milliseconds) => { delays.push(milliseconds); }, - }, - ); + }); - assert.equal(result, 'recovered'); - assert.equal(attempts, 3); - assert.deepEqual(delays, [100, 200]); -}); + expect(result).toBe('recovered'); + expect(operation).toHaveBeenCalledTimes(3); + expect(delays).toStrictEqual([100, 200]); + }); -test('does not retry a rejected error category', async () => { - let attempts = 0; - await assert.rejects( - async () => - retry( - async () => { - attempts += 1; - throw new Error('Permanent failure'); - }, - { shouldRetry: () => false }, - ), - /Permanent failure/u, - ); + it('does not retry a rejected error category', async () => { + const operation = vi + .fn<() => Promise>() + .mockRejectedValue(new Error('Permanent failure')); + await expect( + retry(operation, { shouldRetry: () => false }), + ).rejects.toThrow(/Permanent failure/u); - assert.equal(attempts, 1); -}); + expect(operation).toHaveBeenCalledTimes(1); + }); -test('reports retry details before delaying', async () => { - const retries: { attempt: number; delayMilliseconds: number }[] = []; - await assert.rejects( - async () => + it('reports retry details before delaying', async () => { + const retries: { attempt: number; delayMilliseconds: number }[] = []; + await expect( retry( - async () => { + async (): Promise => { throw new Error('Transient failure'); }, { @@ -60,8 +48,8 @@ test('reports retry details before delaying', async () => { sleep: async () => undefined, }, ), - /Transient failure/u, - ); + ).rejects.toThrow(/Transient failure/u); - assert.deepEqual(retries, [{ attempt: 1, delayMilliseconds: 1_000 }]); + expect(retries).toStrictEqual([{ attempt: 1, delayMilliseconds: 1_000 }]); + }); }); diff --git a/.github/scripts/tests/update-release-changelog-baseline.test.mts b/.github/scripts/tests/update-release-changelog-baseline.test.mts index de0dca36..80912df1 100644 --- a/.github/scripts/tests/update-release-changelog-baseline.test.mts +++ b/.github/scripts/tests/update-release-changelog-baseline.test.mts @@ -1,135 +1,140 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; +import { describe, expect, it } from 'vitest'; import { removeNewerReleases, selectChangelogBaseline, - type ChangelogBaselineDependencies, } from '../update-release-changelog-baseline.mts'; +import type { ChangelogBaselineDependencies } from '../update-release-changelog-baseline.mts'; -/** - * Builds fake Git lookups for the baseline tests. - * - * @param options0 - The options. - * @param options0.headings - The `ref:version` pairs that have a heading. - * @param options0.stableVersions - The versions in the `stable` changelog. - * @param options0.releaseBranches - The release branches on origin. - * @returns The fake dependencies. - */ -function createDependencies({ - headings = new Set(), - stableVersions = [], - releaseBranches = [], -}: { - headings?: Set; - stableVersions?: string[]; - releaseBranches?: { version: string; kind: 'native' | 'ota'; name: string }[]; -}): ChangelogBaselineDependencies { - return { - hasReleaseHeading: (ref, version) => headings.has(`${ref}:${version}`), - getStableVersions: () => stableVersions, - getReleaseBranches: () => releaseBranches, - }; -} +describe('update-release-changelog-baseline', () => { + /** + * Builds fake Git lookups for the baseline tests. + * + * @param options0 - The options. + * @param options0.headings - The `ref:version` pairs that have a heading. + * @param options0.stableVersions - The versions in the `stable` changelog. + * @param options0.releaseBranches - The release branches on origin. + * @returns The fake dependencies. + */ + function createDependencies({ + headings = new Set(), + stableVersions = [], + releaseBranches = [], + }: { + headings?: Set; + stableVersions?: string[]; + releaseBranches?: { + version: string; + kind: 'native' | 'ota'; + name: string; + }[]; + }): ChangelogBaselineDependencies { + return { + hasReleaseHeading: (ref, version) => headings.has(`${ref}:${version}`), + getStableVersions: () => stableVersions, + getReleaseBranches: () => releaseBranches, + }; + } -/** - * Selects the baseline for version 13.51.0 on its release branch. - * - * @param dependencies - The fake Git lookups. - * @returns The selected baseline. - */ -function selectBaseline(dependencies: ChangelogBaselineDependencies) { - return selectChangelogBaseline({ - version: '13.51.0', - releaseBranch: 'release/13.51.0', - dependencies, - }); -} + /** + * Selects the baseline for version 13.51.0 on its release branch. + * + * @param dependencies - The fake Git lookups. + * @returns The selected baseline. + */ + function selectBaseline( + dependencies: ChangelogBaselineDependencies, + ): ReturnType { + return selectChangelogBaseline({ + version: '13.51.0', + releaseBranch: 'release/13.51.0', + dependencies, + }); + } -test('uses the target release changelog after the changelog PR is merged', () => { - assert.deepEqual( - selectBaseline( - createDependencies({ - headings: new Set(['origin/release/13.51.0:13.51.0']), - }), - ), - { + it('uses the target release changelog after the changelog PR is merged', () => { + expect( + selectBaseline( + createDependencies({ + headings: new Set(['origin/release/13.51.0:13.51.0']), + }), + ), + ).toStrictEqual({ kind: 'target', ref: 'origin/release/13.51.0', version: '13.51.0', - }, - ); -}); + }); + }); -test('uses stable history even when an open changelog PR is reviewed', () => { - assert.deepEqual( - selectBaseline( - createDependencies({ - headings: new Set(['origin/stable:13.50.0']), - stableVersions: ['13.50.0'], - }), - ), - { + it('uses stable history even when an open changelog PR is reviewed', () => { + expect( + selectBaseline( + createDependencies({ + headings: new Set(['origin/stable:13.50.0']), + stableVersions: ['13.50.0'], + }), + ), + ).toStrictEqual({ kind: 'stable', ref: 'origin/stable', version: '13.50.0', - }, - ); -}); + }); + }); -test('prefers stable for the selected predecessor version', () => { - assert.deepEqual( - selectBaseline( - createDependencies({ - headings: new Set(['origin/stable:13.50.3']), - stableVersions: ['13.50.2', '13.50.3'], - releaseBranches: [ - { - version: '13.50.3', - kind: 'native', - name: 'release/13.50.3', - }, - ], - }), - ), - { kind: 'stable', ref: 'origin/stable', version: '13.50.3' }, - ); -}); + it('prefers stable for the selected predecessor version', () => { + expect( + selectBaseline( + createDependencies({ + headings: new Set(['origin/stable:13.50.3']), + stableVersions: ['13.50.2', '13.50.3'], + releaseBranches: [ + { + version: '13.50.3', + kind: 'native', + name: 'release/13.50.3', + }, + ], + }), + ), + ).toStrictEqual({ + kind: 'stable', + ref: 'origin/stable', + version: '13.50.3', + }); + }); -test('uses the highest predecessor release branch when stable is behind', () => { - assert.deepEqual( - selectBaseline( - createDependencies({ - headings: new Set([ - 'origin/stable:13.50.2', - 'origin/release/13.50.3:13.50.3', - ]), - stableVersions: ['13.50.2'], - releaseBranches: [ - { - version: '13.50.2', - kind: 'native', - name: 'release/13.50.2', - }, - { - version: '13.50.3', - kind: 'native', - name: 'release/13.50.3', - }, - ], - }), - ), - { + it('uses the highest predecessor release branch when stable is behind', () => { + expect( + selectBaseline( + createDependencies({ + headings: new Set([ + 'origin/stable:13.50.2', + 'origin/release/13.50.3:13.50.3', + ]), + stableVersions: ['13.50.2'], + releaseBranches: [ + { + version: '13.50.2', + kind: 'native', + name: 'release/13.50.2', + }, + { + version: '13.50.3', + kind: 'native', + name: 'release/13.50.3', + }, + ], + }), + ), + ).toStrictEqual({ kind: 'release', ref: 'origin/release/13.50.3', version: '13.50.3', - }, - ); -}); + }); + }); -test('rejects a predecessor release branch whose changelog lacks its own section', () => { - assert.throws( - () => + it('rejects a predecessor release branch whose changelog lacks its own section', () => { + expect(() => selectBaseline( createDependencies({ headings: new Set(['origin/stable:13.50.2']), @@ -143,79 +148,75 @@ test('rejects a predecessor release branch whose changelog lacks its own section ], }), ), - /origin\/release\/13\.50\.3 has no ## \[13\.50\.3\] changelog section/u, - ); -}); + ).toThrow( + /origin\/release\/13\.50\.3 has no ## \[13\.50\.3\] changelog section/u, + ); + }); -const stableChangelog = [ - '# Changelog', - '', - '## [Unreleased]', - '', - '## [13.51.0]', - '', - '### Added', - '', - '- Added c (#3)', - '', - '## [13.50.3]', - '', - '### Added', - '', - '- Added b (#2)', - '', - '[Unreleased]: https://example.com/compare/v13.51.0...HEAD', - '[13.51.0]: https://example.com/compare/v13.50.3...v13.51.0', - '[13.50.3]: https://example.com/releases/tag/v13.50.3', - '', -].join('\n'); + const stableChangelog = [ + '# Changelog', + '', + '## [Unreleased]', + '', + '## [13.51.0]', + '', + '### Added', + '', + '- Added c (#3)', + '', + '## [13.50.3]', + '', + '### Added', + '', + '- Added b (#2)', + '', + '[Unreleased]: https://example.com/compare/v13.51.0...HEAD', + '[13.51.0]: https://example.com/compare/v13.50.3...v13.51.0', + '[13.50.3]: https://example.com/releases/tag/v13.50.3', + '', + ].join('\n'); -test('drops releases newer than an older-line hotfix with their link references', () => { - assert.equal( - removeNewerReleases(stableChangelog, '13.50.4'), - [ - '# Changelog', - '', - '## [Unreleased]', - '', - '## [13.50.3]', - '', - '### Added', - '', - '- Added b (#2)', - '', - '[Unreleased]: https://example.com/compare/v13.51.0...HEAD', - '[13.50.3]: https://example.com/releases/tag/v13.50.3', - '', - ].join('\n'), - ); -}); + it('drops releases newer than an older-line hotfix with their link references', () => { + expect(removeNewerReleases(stableChangelog, '13.50.4')).toBe( + [ + '# Changelog', + '', + '## [Unreleased]', + '', + '## [13.50.3]', + '', + '### Added', + '', + '- Added b (#2)', + '', + '[Unreleased]: https://example.com/compare/v13.51.0...HEAD', + '[13.50.3]: https://example.com/releases/tag/v13.50.3', + '', + ].join('\n'), + ); + }); -test('leaves a changelog without newer releases byte for byte', () => { - assert.equal( - removeNewerReleases(stableChangelog, '13.51.0'), - stableChangelog, - ); - assert.equal(removeNewerReleases(stableChangelog, '14.0.0'), stableChangelog); -}); + it('leaves a changelog without newer releases byte for byte', () => { + expect(removeNewerReleases(stableChangelog, '13.51.0')).toBe( + stableChangelog, + ); + expect(removeNewerReleases(stableChangelog, '14.0.0')).toBe( + stableChangelog, + ); + }); -test('keeps CRLF line endings when dropping newer releases', () => { - const crlf = stableChangelog.replaceAll('\n', '\r\n'); + it('keeps CRLF line endings when dropping newer releases', () => { + const crlf = stableChangelog.replaceAll('\n', '\r\n'); - assert.equal(removeNewerReleases(crlf, '13.50.4').includes('\r\r'), false); - assert.equal( - removeNewerReleases(crlf, '13.50.4').includes('13.51.0]'), - false, - ); - assert.equal( - removeNewerReleases(crlf, '13.50.4').split('\r\n').length, - removeNewerReleases(crlf, '13.50.4').split('\n').length, - ); -}); + expect(removeNewerReleases(crlf, '13.50.4')).not.toContain('\r\r'); + expect(removeNewerReleases(crlf, '13.50.4')).not.toContain('13.51.0]'); + expect(removeNewerReleases(crlf, '13.50.4').split('\r\n')).toHaveLength( + removeNewerReleases(crlf, '13.50.4').split('\n').length, + ); + }); -test('rejects ambiguous native and OTA predecessor branches', () => { - assert.throws( - () => + it('rejects ambiguous native and OTA predecessor branches', () => { + expect(() => selectBaseline( createDependencies({ releaseBranches: [ @@ -232,6 +233,6 @@ test('rejects ambiguous native and OTA predecessor branches', () => { ], }), ), - /Expected exactly one release branch/u, - ); + ).toThrow(/Expected exactly one release branch/u); + }); }); diff --git a/.github/scripts/tests/update-release-changelog-git.test.mts b/.github/scripts/tests/update-release-changelog-git.test.mts index a26b7e30..79a664c3 100644 --- a/.github/scripts/tests/update-release-changelog-git.test.mts +++ b/.github/scripts/tests/update-release-changelog-git.test.mts @@ -1,4 +1,3 @@ -import assert from 'node:assert/strict'; import { mkdirSync, mkdtempSync, @@ -8,7 +7,7 @@ import { } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, it } from 'node:test'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { assertRemoteRefUnchanged, @@ -155,18 +154,15 @@ describe('release changelog Git behavior', () => { baseline: STABLE_BASELINE, }); - assert.equal(git(work, 'branch', '--show-current'), CHANGELOG_BRANCH); - assert.equal( - git(work, 'rev-parse', 'HEAD'), + expect(git(work, 'branch', '--show-current')).toBe(CHANGELOG_BRANCH); + expect(git(work, 'rev-parse', 'HEAD')).toBe( git(work, 'rev-parse', `origin/${TARGET}`), ); - assert.equal( - readFileSync(join(work, 'CHANGELOG.md'), 'utf8'), + expect(readFileSync(join(work, 'CHANGELOG.md'), 'utf8')).toBe( stableChangelog, ); - assert.equal(readFileSync(join(work, 'code.txt'), 'utf8'), 'target\n'); - assert.equal( - git(work, 'status', '--porcelain', '--untracked-files=no'), + expect(readFileSync(join(work, 'code.txt'), 'utf8')).toBe('target\n'); + expect(git(work, 'status', '--porcelain', '--untracked-files=no')).toBe( 'M CHANGELOG.md', ); }); @@ -179,7 +175,7 @@ describe('release changelog Git behavior', () => { CHANGELOG_BRANCH, `origin/${CHANGELOG_BRANCH}`, ); - assert.equal(readFileSync(join(work, 'code.txt'), 'utf8'), 'stale\n'); + expect(readFileSync(join(work, 'code.txt'), 'utf8')).toBe('stale\n'); rebuildChangelogBranch({ changelogBranch: CHANGELOG_BRANCH, @@ -187,7 +183,7 @@ describe('release changelog Git behavior', () => { baseline: STABLE_BASELINE, }); - assert.equal(readFileSync(join(work, 'code.txt'), 'utf8'), 'target\n'); + expect(readFileSync(join(work, 'code.txt'), 'utf8')).toBe('target\n'); }); it('does not leave the rebuilt branch tracking the remote', () => { @@ -197,25 +193,23 @@ describe('release changelog Git behavior', () => { baseline: STABLE_BASELINE, }); - assert.throws(() => + expect(() => git(work, 'config', '--get', `branch.${CHANGELOG_BRANCH}.remote`), - ); + ).toThrow(/Command failed/u); }); it('fails when the baseline has no CHANGELOG.md', () => { - assert.throws( - () => - rebuildChangelogBranch({ - changelogBranch: CHANGELOG_BRANCH, - releaseBranch: TARGET, - baseline: { - kind: 'release', - ref: 'origin/no-changelog', - version: '13.50.0', - }, - }), - /does not contain CHANGELOG\.md/u, - ); + expect(() => + rebuildChangelogBranch({ + changelogBranch: CHANGELOG_BRANCH, + releaseBranch: TARGET, + baseline: { + kind: 'release', + ref: 'origin/no-changelog', + version: '13.50.0', + }, + }), + ).toThrow(/does not contain CHANGELOG\.md/u); }); }); @@ -227,7 +221,7 @@ describe('release changelog Git behavior', () => { }; it('returns undefined on a first run', () => { - assert.equal( + expect( getReviewedCurrentReleaseSection({ ...input, changelogBranchSha: undefined, @@ -235,32 +229,28 @@ describe('release changelog Git behavior', () => { throw new Error('must not query PRs on a first run'); }, }), - undefined, - ); + ).toBeUndefined(); }); it('refuses a stale changelog branch that has no open PR', () => { - assert.throws( - () => - getReviewedCurrentReleaseSection({ - ...input, - changelogBranchSha: getRemoteBranchSha(CHANGELOG_BRANCH), - getOpenPrNumber: () => undefined, - }), - /exists without an open PR/u, - ); + expect(() => + getReviewedCurrentReleaseSection({ + ...input, + changelogBranchSha: getRemoteBranchSha(CHANGELOG_BRANCH), + getOpenPrNumber: () => undefined, + }), + ).toThrow(/exists without an open PR/u); }); it('regenerates a branch without an open PR when only the updater committed to it', () => { - assert.equal( + expect( getReviewedCurrentReleaseSection({ ...input, changelogBranchSha: getRemoteBranchSha(CHANGELOG_BRANCH), isUpdaterOnlyBranch: () => true, getOpenPrNumber: () => undefined, }), - undefined, - ); + ).toBeUndefined(); }); it('strips trailing whitespace from a reviewed section', () => { @@ -273,72 +263,66 @@ describe('release changelog Git behavior', () => { { from: TARGET }, ); git(work, 'fetch', 'origin', CHANGELOG_BRANCH); - assert.doesNotMatch( + expect( getReviewedCurrentReleaseSection({ ...input, changelogBranchSha: getRemoteBranchSha(CHANGELOG_BRANCH), getOpenPrNumber: () => '7', - }) ?? '', - /[ \t]$/mu, - ); + }), + ).not.toMatch(/[ \t]$/mu); }); it('ignores a branch without an open PR when the target already has the section', () => { - assert.equal( + expect( getReviewedCurrentReleaseSection({ ...input, changelogBranchSha: getRemoteBranchSha(CHANGELOG_BRANCH), allowMissingOpenPr: true, getOpenPrNumber: () => undefined, }), - undefined, - ); + ).toBeUndefined(); }); it('still preserves an open PR when the target already has the section', () => { git(work, 'fetch', 'origin', CHANGELOG_BRANCH); - assert.match( + expect( getReviewedCurrentReleaseSection({ ...input, changelogBranchSha: getRemoteBranchSha(CHANGELOG_BRANCH), allowMissingOpenPr: true, getOpenPrNumber: () => '7', - }) ?? '', - /Added a reviewed feature \(#101\)/u, - ); + }), + ).toMatch(/Added a reviewed feature \(#101\)/u); }); it('refuses an open changelog branch that lacks the current heading', () => { - assert.throws( - () => - getReviewedCurrentReleaseSection({ - ...input, - version: '13.52.0', - changelogBranchSha: getRemoteBranchSha(CHANGELOG_BRANCH), - getOpenPrNumber: () => '7', - }), - /lacks 13\.52\.0/u, - ); + expect(() => + getReviewedCurrentReleaseSection({ + ...input, + version: '13.52.0', + changelogBranchSha: getRemoteBranchSha(CHANGELOG_BRANCH), + getOpenPrNumber: () => '7', + }), + ).toThrow(/lacks 13\.52\.0/u); }); it('returns the reviewed section from an open changelog branch', () => { git(work, 'fetch', 'origin', CHANGELOG_BRANCH); - assert.equal( + expect( getReviewedCurrentReleaseSection({ ...input, changelogBranchSha: getRemoteBranchSha(CHANGELOG_BRANCH), getOpenPrNumber: (head, base) => { - assert.equal(head, CHANGELOG_BRANCH); - assert.equal(base, TARGET); + expect(head).toBe(CHANGELOG_BRANCH); + expect(base).toBe(TARGET); return '7'; }, }), - `## [13.51.0] + ).toBe(`## [13.51.0] ### Added -- Added a reviewed feature (#101)`, - ); +- Added a reviewed feature (#101)`); }); }); @@ -362,15 +346,13 @@ describe('release changelog Git behavior', () => { const movedSha = getRemoteBranchSha(CHANGELOG_BRANCH); startLocalBranch(); - assert.throws( - () => - pushChangelogBranch({ - changelogBranch: CHANGELOG_BRANCH, - expectedRemoteSha: leasedSha, - }), - /changed after this run began/u, - ); - assert.equal(getRemoteBranchSha(CHANGELOG_BRANCH), movedSha); + expect(() => + pushChangelogBranch({ + changelogBranch: CHANGELOG_BRANCH, + expectedRemoteSha: leasedSha, + }), + ).toThrow(/changed after this run began/u); + expect(getRemoteBranchSha(CHANGELOG_BRANCH)).toBe(movedSha); }); it('rewrites the branch when the lease still matches', () => { @@ -382,8 +364,7 @@ describe('release changelog Git behavior', () => { expectedRemoteSha: leasedSha, }); - assert.equal( - getRemoteBranchSha(CHANGELOG_BRANCH), + expect(getRemoteBranchSha(CHANGELOG_BRANCH)).toBe( git(work, 'rev-parse', 'HEAD'), ); }); @@ -399,20 +380,17 @@ describe('release changelog Git behavior', () => { changelogBranch: newBranch, expectedRemoteSha: undefined, }); - assert.equal( - getRemoteBranchSha(newBranch), + expect(getRemoteBranchSha(newBranch)).toBe( git(work, 'rev-parse', 'HEAD'), ); git(work, 'commit', '--allow-empty', '-m', 'second'); - assert.throws( - () => - pushChangelogBranch({ - changelogBranch: newBranch, - expectedRemoteSha: undefined, - }), - /may have been created concurrently/u, - ); + expect(() => + pushChangelogBranch({ + changelogBranch: newBranch, + expectedRemoteSha: undefined, + }), + ).toThrow(/may have been created concurrently/u); }); }); @@ -430,8 +408,7 @@ describe('release changelog Git behavior', () => { writeFileSync(join(work, 'code.txt'), 'release moved\n'); git(work, 'commit', '-am', 'same changelog, other file moved'); - assert.equal( - hasSameChangelogAsRemoteBranch(CHANGELOG_BRANCH, remoteSha), + expect(hasSameChangelogAsRemoteBranch(CHANGELOG_BRANCH, remoteSha)).toBe( true, ); }); @@ -448,9 +425,8 @@ describe('release changelog Git behavior', () => { ); git(work, 'commit', '--amend', '-m', 'rebuilt with a new hash'); - assert.notEqual(git(work, 'rev-parse', 'HEAD'), remoteSha); - assert.equal( - hasSameChangelogAsRemoteBranch(CHANGELOG_BRANCH, remoteSha), + expect(git(work, 'rev-parse', 'HEAD')).not.toBe(remoteSha); + expect(hasSameChangelogAsRemoteBranch(CHANGELOG_BRANCH, remoteSha)).toBe( true, ); }); @@ -466,15 +442,13 @@ describe('release changelog Git behavior', () => { `origin/${CHANGELOG_BRANCH}`, ); - assert.equal( + expect( hasSameChangelogAsRemoteBranch(CHANGELOG_BRANCH, 'f'.repeat(40)), - false, - ); + ).toBe(false); writeFileSync(join(work, 'CHANGELOG.md'), 'edited\n'); git(work, 'commit', '-am', 'edit'); - assert.equal( - hasSameChangelogAsRemoteBranch(CHANGELOG_BRANCH, remoteSha), + expect(hasSameChangelogAsRemoteBranch(CHANGELOG_BRANCH, remoteSha)).toBe( false, ); }); @@ -503,23 +477,23 @@ describe('release changelog Git behavior', () => { 'Changelog-Proofread: failed', ); - assert.deepEqual( + expect( getChangelogBranchCommits(CHANGELOG_BRANCH, TARGET).map( ({ subject, unproofread }) => ({ subject, unproofread }), ), - [{ subject: 'update changelog for 13.51.0', unproofread: true }], - ); + ).toStrictEqual([ + { subject: 'update changelog for 13.51.0', unproofread: true }, + ]); }); it('reports no marker on a commit without the trailer', () => { pushCommit('-m', 'update changelog for 13.51.0'); - assert.deepEqual( + expect( getChangelogBranchCommits(CHANGELOG_BRANCH, TARGET).map( ({ unproofread }) => unproofread, ), - [false], - ); + ).toStrictEqual([false]); }); it('reads the release tip a run generated through, next to the other trailer', () => { @@ -531,15 +505,14 @@ describe('release changelog Git behavior', () => { `Changelog-Generated-Through: ${tip}\nChangelog-Proofread: failed`, ); - assert.deepEqual( + expect( getChangelogBranchCommits(CHANGELOG_BRANCH, TARGET).map( ({ generatedThrough, unproofread }) => ({ generatedThrough, unproofread, }), ), - [{ generatedThrough: tip, unproofread: true }], - ); + ).toStrictEqual([{ generatedThrough: tip, unproofread: true }]); }); it('ignores a generated-through value that is not a commit SHA', () => { @@ -550,39 +523,36 @@ describe('release changelog Git behavior', () => { 'Changelog-Generated-Through: not-a-sha', ); - assert.equal( + expect( getChangelogBranchCommits(CHANGELOG_BRANCH, TARGET)[0] ?.generatedThrough, - undefined, - ); + ).toBeUndefined(); }); }); describe('assertRemoteRefUnchanged', () => { it('accepts an unchanged ref and rejects a moved one', () => { const sha = getRemoteBranchSha(TARGET); - assert.ok(sha); - assert.doesNotThrow(() => + expect(sha).toBeDefined(); + expect(() => assertRemoteRefUnchanged({ ref: `origin/${TARGET}`, - expectedSha: sha, + expectedSha: sha as string, description: 'Target release branch', }), - ); + ).not.toThrow(); git(seed, 'checkout', TARGET); git(seed, 'commit', '--allow-empty', '-m', 'move target'); git(seed, 'push', 'origin', TARGET); - assert.throws( - () => - assertRemoteRefUnchanged({ - ref: `origin/${TARGET}`, - expectedSha: sha, - description: 'Target release branch', - }), - /changed during changelog generation/u, - ); + expect(() => + assertRemoteRefUnchanged({ + ref: `origin/${TARGET}`, + expectedSha: sha as string, + description: 'Target release branch', + }), + ).toThrow(/changed during changelog generation/u); }); }); }); diff --git a/.github/scripts/tests/update-release-changelog-reachability.test.mts b/.github/scripts/tests/update-release-changelog-reachability.test.mts index 989cc7aa..e3d4835d 100644 --- a/.github/scripts/tests/update-release-changelog-reachability.test.mts +++ b/.github/scripts/tests/update-release-changelog-reachability.test.mts @@ -1,8 +1,7 @@ -import assert from 'node:assert/strict'; import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, it, mock } from 'node:test'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { isCommitReachableFrom } from '../update-release-changelog.mts'; import { git } from './git-test-environment.mts'; @@ -27,33 +26,28 @@ describe('isCommitReachableFrom', () => { }); afterEach(() => { - mock.restoreAll(); rmSync(directory, { recursive: true, force: true }); }); it('is true for a commit on the ref and false for one that is not', () => { - assert.equal(isCommitReachableFrom(shared, 'release', directory), true); - assert.equal( - isCommitReachableFrom(onlyOnMain, 'release', directory), - false, - ); + expect(isCommitReachableFrom(shared, 'release', directory)).toBe(true); + expect(isCommitReachableFrom(onlyOnMain, 'release', directory)).toBe(false); }); it('warns and returns false when Git cannot resolve the commit', () => { - const warn = mock.method(console, 'warn', () => undefined); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); - assert.equal( - isCommitReachableFrom('f'.repeat(40), 'release', directory), + expect(isCommitReachableFrom('f'.repeat(40), 'release', directory)).toBe( false, ); - assert.equal(warn.mock.callCount(), 1); + expect(warn).toHaveBeenCalledTimes(1); }); it('does not warn for an ordinary non-ancestor', () => { - const warn = mock.method(console, 'warn', () => undefined); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); isCommitReachableFrom(onlyOnMain, 'release', directory); - assert.equal(warn.mock.callCount(), 0); + expect(warn).toHaveBeenCalledTimes(0); }); }); diff --git a/.github/scripts/tests/update-release-changelog.test.mts b/.github/scripts/tests/update-release-changelog.test.mts index 2847a9ac..c798a254 100644 --- a/.github/scripts/tests/update-release-changelog.test.mts +++ b/.github/scripts/tests/update-release-changelog.test.mts @@ -1,8 +1,7 @@ -import assert from 'node:assert/strict'; import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import test from 'node:test'; +import { describe, expect, it, vi } from 'vitest'; import { assertReleaseSectionHasEntries, @@ -35,101 +34,95 @@ import { writeFailedProofreadingReport, } from '../update-release-changelog.mts'; -test('records the failure stage in the proofread report', () => { - const directory = mkdtempSync(join(tmpdir(), 'proofread-report-')); - try { - const reportPath = join(directory, 'nested', 'report.json'); - writeFailedProofreadingReport(reportPath, 'no key', 'authentication'); - assert.deepEqual(JSON.parse(readFileSync(reportPath, 'utf8')), { - status: 'failed', - stage: 'authentication', - error: 'no key', - }); - writeFailedProofreadingReport(reportPath, 'boom'); - assert.equal( - (JSON.parse(readFileSync(reportPath, 'utf8')) as { stage: string }).stage, - 'execution', - ); - } finally { - rmSync(directory, { force: true, recursive: true }); - } -}); +describe('update-release-changelog', () => { + it('records the failure stage in the proofread report', () => { + const directory = mkdtempSync(join(tmpdir(), 'proofread-report-')); + try { + const reportPath = join(directory, 'nested', 'report.json'); + writeFailedProofreadingReport(reportPath, 'no key', 'authentication'); + expect(JSON.parse(readFileSync(reportPath, 'utf8'))).toStrictEqual({ + status: 'failed', + stage: 'authentication', + error: 'no key', + }); + writeFailedProofreadingReport(reportPath, 'boom'); + expect( + (JSON.parse(readFileSync(reportPath, 'utf8')) as { stage: string }) + .stage, + ).toBe('execution'); + } finally { + rmSync(directory, { force: true, recursive: true }); + } + }); -test('collects historical skipped PRs from auto-changelog diagnostics', () => { - assert.deepEqual( - getHistoricalSkippedPrNumbers(`[auto-changelog] skipped pr=35695 reason=historical-pr + it('collects historical skipped PRs from auto-changelog diagnostics', () => { + expect( + getHistoricalSkippedPrNumbers(`[auto-changelog] skipped pr=35695 reason=historical-pr [auto-changelog] commit=abc accepted source-pr=1 canonical-pr=1 cherry-pick=false [auto-changelog] skipped pr=35716 reason=historical-pr [auto-changelog] skipped pr=35695 reason=historical-pr [auto-changelog] skipped pr=9 reason=cherry-pick-duplicate`), - ['35695', '35716'], - ); - assert.deepEqual(getHistoricalSkippedPrNumbers(''), []); -}); + ).toStrictEqual(['35695', '35716']); + expect(getHistoricalSkippedPrNumbers('')).toStrictEqual([]); + }); -const COMMIT_A = 'a'.repeat(40); -const COMMIT_B = 'b'.repeat(40); -const COMMIT_C = 'c'.repeat(40); + const COMMIT_A = 'a'.repeat(40); + const COMMIT_B = 'b'.repeat(40); + const COMMIT_C = 'c'.repeat(40); -test('collects the accepted commits of each canonical PR', () => { - assert.deepEqual( - [ + it('collects the accepted commits of each canonical PR', () => { + expect([ ...getAcceptedPrCommits(`[auto-changelog] commit=${COMMIT_A} accepted source-pr=1 canonical-pr=1 cherry-pick=false [auto-changelog] commit=${COMMIT_B} accepted source-pr=7 canonical-pr=1 cherry-pick=true [auto-changelog] commit=${COMMIT_C} accepted source-pr=2 canonical-pr=2 cherry-pick=false [auto-changelog] skipped pr=9 reason=cherry-pick-duplicate`), - ], - [ + ]).toStrictEqual([ ['1', [COMMIT_A, COMMIT_B]], ['2', [COMMIT_C]], - ], - ); -}); - -test('treats a PR generated before the last tip but missing from the section as deleted', () => { - const options = { - acceptedCommitsByPr: new Map([ - ['1', [COMMIT_A]], - ['2', [COMMIT_B]], - ['3', [COMMIT_C]], - ['4', [COMMIT_A, COMMIT_C]], - ]), - generatedThrough: 'd'.repeat(40), - listReachableCommits: () => [COMMIT_A, COMMIT_B], - }; - - assert.deepEqual( - getDeletedPrNumbers({ - ...options, - existingPrNumbers: new Set(['1']), - }), - new Set(['2']), - ); - assert.deepEqual( - getDeletedPrNumbers({ - ...options, - existingPrNumbers: new Set(['1', '2']), - }), - new Set(), - ); -}); + ]); + }); -test('treats nothing as deleted when the last tip cannot be read', () => { - assert.deepEqual( - getDeletedPrNumbers({ - acceptedCommitsByPr: new Map([['1', [COMMIT_A]]]), + it('treats a PR generated before the last tip but missing from the section as deleted', () => { + const options = { + acceptedCommitsByPr: new Map([ + ['1', [COMMIT_A]], + ['2', [COMMIT_B]], + ['3', [COMMIT_C]], + ['4', [COMMIT_A, COMMIT_C]], + ]), generatedThrough: 'd'.repeat(40), - existingPrNumbers: new Set(), - listReachableCommits: () => { - throw new Error('unknown revision'); - }, - }), - new Set(), - ); -}); + listReachableCommits: (): string[] => [COMMIT_A, COMMIT_B], + }; + + expect( + getDeletedPrNumbers({ + ...options, + existingPrNumbers: new Set(['1']), + }), + ).toStrictEqual(new Set(['2'])); + expect( + getDeletedPrNumbers({ + ...options, + existingPrNumbers: new Set(['1', '2']), + }), + ).toStrictEqual(new Set()); + }); -test('finds the releases that already list a PR, oldest first, excluding the target', () => { - const changelog = `# Changelog + it('treats nothing as deleted when the last tip cannot be read', () => { + expect( + getDeletedPrNumbers({ + acceptedCommitsByPr: new Map([['1', [COMMIT_A]]]), + generatedThrough: 'd'.repeat(40), + existingPrNumbers: new Set(), + listReachableCommits: () => { + throw new Error('unknown revision'); + }, + }), + ).toStrictEqual(new Set()); + }); + + it('finds the releases that already list a PR, oldest first, excluding the target', () => { + const changelog = `# Changelog ## [Unreleased] @@ -152,18 +145,16 @@ test('finds the releases that already list a PR, oldest first, excluding the tar - Unrelated (#1) `; - assert.deepEqual( - findReleaseVersionsContainingPrs(changelog, ['35695', '35716'], '8.10.3'), - ['8.9.0', '8.11.0'], - ); - assert.deepEqual( - findReleaseVersionsContainingPrs(changelog, ['35716'], '8.11.0'), - [], - ); -}); + expect( + findReleaseVersionsContainingPrs(changelog, ['35695', '35716'], '8.10.3'), + ).toStrictEqual(['8.9.0', '8.11.0']); + expect( + findReleaseVersionsContainingPrs(changelog, ['35716'], '8.11.0'), + ).toStrictEqual([]); + }); -test('finds versions that document a PR with this repository long link', () => { - const changelog = `# Changelog + it('finds versions that document a PR with this repository long link', () => { + const changelog = `# Changelog ## [8.9.0] @@ -173,394 +164,371 @@ test('finds versions that document a PR with this repository long link', () => { - Other repo ([#35695](https://github.com/MetaMask/core/pull/35695)) `; - const repositoryUrl = 'https://github.com/MetaMask/metamask-mobile'; - - assert.deepEqual( - findReleaseVersionsContainingPrs( - changelog, - ['35695'], - '8.10.3', - repositoryUrl, - ), - ['8.9.0'], - ); - assert.deepEqual( - findReleaseVersionsContainingPrs(changelog, ['35695'], '8.10.3'), - [], - ); -}); + const repositoryUrl = 'https://github.com/MetaMask/metamask-mobile'; -test('detects a release section without entries', () => { - assert.equal( - isReleaseSectionEmpty( - '# Changelog\n\n## [8.10.3]\n\n## [8.10.2]\n', - '8.10.3', - ), - true, - ); - assert.equal( - isReleaseSectionEmpty( - '# Changelog\n\n## [8.10.3]\n\n### Fixed\n\n- Fixed it (#1)\n\n## [8.10.2]\n', - '8.10.3', - ), - false, - ); -}); + expect( + findReleaseVersionsContainingPrs( + changelog, + ['35695'], + '8.10.3', + repositoryUrl, + ), + ).toStrictEqual(['8.9.0']); + expect( + findReleaseVersionsContainingPrs(changelog, ['35695'], '8.10.3'), + ).toStrictEqual([]); + }); + + it('detects a release section without entries', () => { + expect( + isReleaseSectionEmpty( + '# Changelog\n\n## [8.10.3]\n\n## [8.10.2]\n', + '8.10.3', + ), + ).toBe(true); + expect( + isReleaseSectionEmpty( + '# Changelog\n\n## [8.10.3]\n\n### Fixed\n\n- Fixed it (#1)\n\n## [8.10.2]\n', + '8.10.3', + ), + ).toBe(false); + }); -test('asks for a manual edit when an OTA release has no new PRs', () => { - assert.deepEqual( - getChangelogPrPresentation({ - version: '8.10.3', - changelogBranch: 'release-changelog/8.10.3', - proofreadingStatus: 'no-new-prs', - presentInVersions: ['8.11.0', '8.12.0'], - }), - { + it('asks for a manual edit when an OTA release has no new PRs', () => { + expect( + getChangelogPrPresentation({ + version: '8.10.3', + changelogBranch: 'release-changelog/8.10.3', + proofreadingStatus: 'no-new-prs', + presentInVersions: ['8.11.0', '8.12.0'], + }), + ).toStrictEqual({ title: 'release: release-changelog/8.10.3 (no new PRs, manual edit required)', body: 'This PR updates the change log for 8.10.3.\n\n> There are no brand new PRs in 8.10.3, there are only cherry-picks that were already present in 8.11.0, 8.12.0. Please decide how you want to handle this and edit the changelog manually.', - }, - ); - assert.match( - getChangelogPrPresentation({ - version: '8.10.3', - changelogBranch: 'release-changelog/8.10.3', - proofreadingStatus: 'no-new-prs', - }).body, - /There are no brand new PRs in 8\.10\.3\. Please decide/u, - ); -}); + }); + expect( + getChangelogPrPresentation({ + version: '8.10.3', + changelogBranch: 'release-changelog/8.10.3', + proofreadingStatus: 'no-new-prs', + }).body, + ).toMatch(/There are no brand new PRs in 8\.10\.3\. Please decide/u); + }); -test('parses dry-run without changing positional arguments', () => { - assert.deepEqual( - parseUpdateChangelogArguments([ - '--dry-run', - 'release/13.51.0', - 'extension', - 'https://github.com/MetaMask/metamask-extension', - ]), - { + it('parses dry-run without changing positional arguments', () => { + expect( + parseUpdateChangelogArguments([ + '--dry-run', + 'release/13.51.0', + 'extension', + 'https://github.com/MetaMask/metamask-extension', + ]), + ).toStrictEqual({ dryRun: true, positionalArguments: [ 'release/13.51.0', 'extension', 'https://github.com/MetaMask/metamask-extension', ], - }, - ); -}); + }); + }); -test('requires a pinned auto-changelog source CLI', () => { - assert.equal( - getAutoChangelogCli({ AUTO_CHANGELOG_CLI: '/tmp/auto-changelog.mjs' }), - '/tmp/auto-changelog.mjs', - ); - assert.throws( - () => getAutoChangelogCli({}), - /AUTO_CHANGELOG_CLI must point/u, - ); -}); + it('requires a pinned auto-changelog source CLI', () => { + expect( + getAutoChangelogCli({ AUTO_CHANGELOG_CLI: '/tmp/auto-changelog.mjs' }), + ).toBe('/tmp/auto-changelog.mjs'); + expect(() => getAutoChangelogCli({})).toThrow( + /AUTO_CHANGELOG_CLI must point/u, + ); + }); -test('uses the standard validator when clean-room proofreading fails', () => { - assert.deepEqual(getChangelogValidationArguments('failed', '13.51.0'), [ - 'validate', - '--prettier', - '--currentVersion', - '13.51.0', - ]); - assert.deepEqual(getChangelogValidationArguments('succeeded', '13.51.0'), [ - 'validate', - '--prettier', - '--currentVersion', - '13.51.0', - '--rc', - ]); -}); + it('uses the standard validator when clean-room proofreading fails', () => { + expect(getChangelogValidationArguments('failed', '13.51.0')).toStrictEqual([ + 'validate', + '--prettier', + '--currentVersion', + '13.51.0', + ]); + expect( + getChangelogValidationArguments('succeeded', '13.51.0'), + ).toStrictEqual([ + 'validate', + '--prettier', + '--currentVersion', + '13.51.0', + '--rc', + ]); + }); -test('protects first changelog branch creation with an empty lease', () => { - assert.deepEqual( - getChangelogPushArguments({ - changelogBranch: 'release-changelog/13.51.0', - expectedRemoteSha: undefined, - }), - [ + it('protects first changelog branch creation with an empty lease', () => { + expect( + getChangelogPushArguments({ + changelogBranch: 'release-changelog/13.51.0', + expectedRemoteSha: undefined, + }), + ).toStrictEqual([ 'push', '--force-with-lease=refs/heads/release-changelog/13.51.0:', '--set-upstream', 'origin', 'HEAD:refs/heads/release-changelog/13.51.0', - ], - ); -}); + ]); + }); -const RUN_ENVIRONMENT_NAMES = [ - 'GITHUB_SERVER_URL', - 'GITHUB_REPOSITORY', - 'GITHUB_RUN_ID', -] as const; - -/** - * Runs a callback with the GitHub Actions run variables set or removed, so the - * result does not depend on whether the tests run in CI. - * - * @param values - The values to set, or undefined to remove them. - * @param callback - The code to run. - * @returns The callback's result. - */ -function withRunEnvironment( - values: Record<(typeof RUN_ENVIRONMENT_NAMES)[number], string> | undefined, - callback: () => Result, -): Result { - const original = Object.fromEntries( - RUN_ENVIRONMENT_NAMES.map((name) => [name, process.env[name]]), - ); - try { - for (const name of RUN_ENVIRONMENT_NAMES) { - if (values) { - process.env[name] = values[name]; - } else { - delete process.env[name]; + const RUN_ENVIRONMENT_NAMES = [ + 'GITHUB_SERVER_URL', + 'GITHUB_REPOSITORY', + 'GITHUB_RUN_ID', + ] as const; + + /** + * Runs a callback with the GitHub Actions run variables set or removed, so the + * result does not depend on whether the tests run in CI. + * + * @param values - The values to set, or undefined to remove them. + * @param callback - The code to run. + * @returns The callback's result. + */ + function withRunEnvironment( + values: Record<(typeof RUN_ENVIRONMENT_NAMES)[number], string> | undefined, + callback: () => Result, + ): Result { + const original = Object.fromEntries( + RUN_ENVIRONMENT_NAMES.map((name) => [name, process.env[name]]), + ); + try { + for (const name of RUN_ENVIRONMENT_NAMES) { + if (values) { + process.env[name] = values[name]; + } else { + delete process.env[name]; + } } - } - return callback(); - } finally { - for (const name of RUN_ENVIRONMENT_NAMES) { - if (original[name] === undefined) { - delete process.env[name]; - } else { - process.env[name] = original[name]; + return callback(); + } finally { + for (const name of RUN_ENVIRONMENT_NAMES) { + if (original[name] === undefined) { + delete process.env[name]; + } else { + process.env[name] = original[name]; + } } } } -} -test('marks an unproofread changelog PR when AI proofreading fails', () => { - const presentation = withRunEnvironment(undefined, () => - getChangelogPrPresentation({ - version: '13.51.0', - changelogBranch: 'release-changelog/13.51.0', - proofreadingStatus: 'failed', - proofreadingStage: 'authentication', - }), - ); - - assert.deepEqual(presentation, { - title: - 'release: release-changelog/13.51.0 (AI automation failed, not proofread)', - body: 'This PR updates the change log for 13.51.0.\n\n> AI automation failed during authentication, not proofread. The deterministic changelog generation, reference validation, and changelog lint passed. Review the release section manually before merging.', - }); -}); - -test('links the proofreading report artifact when run in GitHub Actions', () => { - const { body } = withRunEnvironment( - { - GITHUB_SERVER_URL: 'https://github.com', - GITHUB_REPOSITORY: 'MetaMask/metamask-extension', - GITHUB_RUN_ID: '123', - }, - () => + it('marks an unproofread changelog PR when AI proofreading fails', () => { + const presentation = withRunEnvironment(undefined, () => getChangelogPrPresentation({ version: '13.51.0', changelogBranch: 'release-changelog/13.51.0', proofreadingStatus: 'failed', + proofreadingStage: 'authentication', }), - ); + ); - assert.match( - body, - /\[View the proofreading report artifact\.\]\(https:\/\/github\.com\/MetaMask\/metamask-extension\/actions\/runs\/123#artifacts\)/u, - ); -}); + expect(presentation).toStrictEqual({ + title: + 'release: release-changelog/13.51.0 (AI automation failed, not proofread)', + body: 'This PR updates the change log for 13.51.0.\n\n> AI automation failed during authentication, not proofread. The deterministic changelog generation, reference validation, and changelog lint passed. Review the release section manually before merging.', + }); + }); -test('preserves authentication failures for the unproofread PR warning', () => { - const authenticationFailure = { - status: 'failed' as const, - stage: 'authentication', - }; - assert.deepEqual( - getChangelogPrPresentation({ - version: '13.51.0', - changelogBranch: 'release-changelog/13.51.0', - proofreadingStatus: authenticationFailure.status, - proofreadingStage: authenticationFailure.stage, - }).title, - 'release: release-changelog/13.51.0 (AI automation failed, not proofread)', - ); -}); + it('links the proofreading report artifact when run in GitHub Actions', () => { + const { body } = withRunEnvironment( + { + GITHUB_SERVER_URL: 'https://github.com', + GITHUB_REPOSITORY: 'MetaMask/metamask-extension', + GITHUB_RUN_ID: '123', + }, + () => + getChangelogPrPresentation({ + version: '13.51.0', + changelogBranch: 'release-changelog/13.51.0', + proofreadingStatus: 'failed', + }), + ); -test('uses the plain presentation after a successful proofread', () => { - assert.deepEqual( - getChangelogPrPresentation({ - version: '13.51.0', - changelogBranch: 'release-changelog/13.51.0', - proofreadingStatus: 'succeeded', - }), - { + expect(body).toMatch( + /\[View the proofreading report artifact\.\]\(https:\/\/github\.com\/MetaMask\/metamask-extension\/actions\/runs\/123#artifacts\)/u, + ); + }); + + it('preserves authentication failures for the unproofread PR warning', () => { + const authenticationFailure = { + status: 'failed' as const, + stage: 'authentication', + }; + expect( + getChangelogPrPresentation({ + version: '13.51.0', + changelogBranch: 'release-changelog/13.51.0', + proofreadingStatus: authenticationFailure.status, + proofreadingStage: authenticationFailure.stage, + }).title, + ).toBe( + 'release: release-changelog/13.51.0 (AI automation failed, not proofread)', + ); + }); + + it('uses the plain presentation after a successful proofread', () => { + expect( + getChangelogPrPresentation({ + version: '13.51.0', + changelogBranch: 'release-changelog/13.51.0', + proofreadingStatus: 'succeeded', + }), + ).toStrictEqual({ title: 'release: release-changelog/13.51.0', body: 'This PR updates the change log for 13.51.0.', - }, - ); -}); + }); + }); -test('explains an empty release section instead of deferring to the validator', () => { - assert.throws( - () => + it('explains an empty release section instead of deferring to the validator', () => { + expect(() => assertReleaseSectionHasEntries( '# Changelog\n\n## [8.10.3]\n\n## [8.10.2]\n', '8.10.3', ), - /## \[8\.10\.3\] has no entries/u, - ); - assert.doesNotThrow(() => - assertReleaseSectionHasEntries( - '# Changelog\n\n## [8.10.3]\n\n### Fixed\n\n- Fixed it (#1)\n', - '8.10.3', - ), - ); -}); - -test('leaves an existing changelog PR alone when nothing changed', () => { - assert.equal( - shouldKeepChangelogPrPresentation({ - existingTitle: 'release: release-changelog/13.51.0', - proofreadingStatus: 'unchanged', - }), - true, - ); -}); + ).toThrow(/## \[8\.10\.3\] has no entries/u); + expect(() => + assertReleaseSectionHasEntries( + '# Changelog\n\n## [8.10.3]\n\n### Fixed\n\n- Fixed it (#1)\n', + '8.10.3', + ), + ).not.toThrow(); + }); -test('keeps the AI failure marker when a later run proofreads only new entries', () => { - const existingTitle = - 'release: release-changelog/13.51.0 (AI automation failed, not proofread)'; + it('leaves an existing changelog PR alone when nothing changed', () => { + expect( + shouldKeepChangelogPrPresentation({ + existingTitle: 'release: release-changelog/13.51.0', + proofreadingStatus: 'unchanged', + }), + ).toBe(true); + }); - assert.equal( - shouldKeepChangelogPrPresentation({ - existingTitle, - proofreadingStatus: 'succeeded', - }), - true, - ); - assert.equal( - shouldKeepChangelogPrPresentation({ - existingTitle, - proofreadingStatus: 'failed', - }), - false, - ); -}); + it('keeps the AI failure marker when a later run proofreads only new entries', () => { + const existingTitle = + 'release: release-changelog/13.51.0 (AI automation failed, not proofread)'; -test('rewrites the AI failure marker when the whole section was proofread again', () => { - assert.equal( - shouldKeepChangelogPrPresentation({ - existingTitle: - 'release: release-changelog/13.51.0 (AI automation failed, not proofread)', - proofreadingStatus: 'succeeded', - replacesWholeSection: true, - }), - false, - ); -}); + expect( + shouldKeepChangelogPrPresentation({ + existingTitle, + proofreadingStatus: 'succeeded', + }), + ).toBe(true); + expect( + shouldKeepChangelogPrPresentation({ + existingTitle, + proofreadingStatus: 'failed', + }), + ).toBe(false); + }); -test("regenerates only an unproofread PR whose sole commit is the updater's own", () => { - const options = { - title: - 'release: release-changelog/13.51.0 (AI automation failed, not proofread)', - version: '13.51.0', - authorEmail: 'bot@example.com', - commits: [ - { - authorEmail: 'bot@example.com', - subject: 'update changelog for 13.51.0', - unproofread: true, - }, - ], - }; + it('rewrites the AI failure marker when the whole section was proofread again', () => { + expect( + shouldKeepChangelogPrPresentation({ + existingTitle: + 'release: release-changelog/13.51.0 (AI automation failed, not proofread)', + proofreadingStatus: 'succeeded', + replacesWholeSection: true, + }), + ).toBe(false); + }); - assert.equal(isUntouchedUnproofreadChangelogPr(options), true); - assert.equal( - isUntouchedUnproofreadChangelogPr({ - ...options, + it("regenerates only an unproofread PR whose sole commit is the updater's own", () => { + const options = { + title: + 'release: release-changelog/13.51.0 (AI automation failed, not proofread)', + version: '13.51.0', + authorEmail: 'bot@example.com', commits: [ { authorEmail: 'bot@example.com', subject: 'update changelog for 13.51.0', + unproofread: true, }, ], - }), - false, - ); - assert.equal( - isUntouchedUnproofreadChangelogPr({ - ...options, - title: 'release: release-changelog/13.51.0', - }), - false, - ); - assert.equal( - isUntouchedUnproofreadChangelogPr({ - ...options, - commits: [ - ...options.commits, - { authorEmail: 'person@example.com', subject: 'fix wording' }, - ], - }), - false, - ); - assert.equal( - isUntouchedUnproofreadChangelogPr({ - ...options, - commits: [ - { - authorEmail: 'person@example.com', - subject: 'update changelog for 13.51.0', - }, - ], - }), - false, - ); - assert.equal( - isUntouchedUnproofreadChangelogPr({ ...options, commits: [] }), - false, - ); -}); + }; + + expect(isUntouchedUnproofreadChangelogPr(options)).toBe(true); + expect( + isUntouchedUnproofreadChangelogPr({ + ...options, + commits: [ + { + authorEmail: 'bot@example.com', + subject: 'update changelog for 13.51.0', + }, + ], + }), + ).toBe(false); + expect( + isUntouchedUnproofreadChangelogPr({ + ...options, + title: 'release: release-changelog/13.51.0', + }), + ).toBe(false); + expect( + isUntouchedUnproofreadChangelogPr({ + ...options, + commits: [ + ...options.commits, + { authorEmail: 'person@example.com', subject: 'fix wording' }, + ], + }), + ).toBe(false); + expect( + isUntouchedUnproofreadChangelogPr({ + ...options, + commits: [ + { + authorEmail: 'person@example.com', + subject: 'update changelog for 13.51.0', + }, + ], + }), + ).toBe(false); + expect(isUntouchedUnproofreadChangelogPr({ ...options, commits: [] })).toBe( + false, + ); + }); -test("recovers a branch only when every commit is the updater's own", () => { - const own = { - authorEmail: 'bot@example.com', - subject: 'update changelog for 13.51.0', - }; - const options = { - version: '13.51.0', - authorEmail: 'bot@example.com', - commits: [own], - }; - - assert.equal(hasOnlyUpdaterCommits(options), true); - assert.equal( - hasOnlyUpdaterCommits({ - ...options, - commits: [ - own, - { authorEmail: 'person@example.com', subject: 'fix wording' }, - ], - }), - false, - ); -}); + it("recovers a branch only when every commit is the updater's own", () => { + const own = { + authorEmail: 'bot@example.com', + subject: 'update changelog for 13.51.0', + }; + const options = { + version: '13.51.0', + authorEmail: 'bot@example.com', + commits: [own], + }; + + expect(hasOnlyUpdaterCommits(options)).toBe(true); + expect( + hasOnlyUpdaterCommits({ + ...options, + commits: [ + own, + { authorEmail: 'person@example.com', subject: 'fix wording' }, + ], + }), + ).toBe(false); + }); -test('rewrites the PR presentation after a normal successful run', () => { - assert.equal( - shouldKeepChangelogPrPresentation({ - existingTitle: 'release: release-changelog/13.51.0', - proofreadingStatus: 'succeeded', - }), - false, - ); -}); + it('rewrites the PR presentation after a normal successful run', () => { + expect( + shouldKeepChangelogPrPresentation({ + existingTitle: 'release: release-changelog/13.51.0', + proofreadingStatus: 'succeeded', + }), + ).toBe(false); + }); -test('rejects generated sections with missing or duplicate PR references', () => { - assert.throws( - () => + it('rejects generated sections with missing or duplicate PR references', () => { + expect(() => validateGeneratedReleaseSection( `## [13.51.0] @@ -569,10 +537,8 @@ test('rejects generated sections with missing or duplicate PR references', () => - Fixed an issue`, '13.51.0', ), - /without a PR reference/u, - ); - assert.throws( - () => + ).toThrow(/without a PR reference/u); + expect(() => validateGeneratedReleaseSection( `## [13.51.0] @@ -582,662 +548,631 @@ test('rejects generated sections with missing or duplicate PR references', () => - Fixed it again (#101)`, '13.51.0', ), - /duplicate PR references/u, - ); - assert.doesNotThrow(() => - validateGeneratedReleaseSection( - `## [13.51.0] + ).toThrow(/duplicate PR references/u); + expect(() => + validateGeneratedReleaseSection( + `## [13.51.0] ### Fixed - Fixed an issue (#101) - Fixed it again (#101)`, - '13.51.0', - true, - ), - ); -}); + '13.51.0', + true, + ), + ).not.toThrow(); + }); -test('collects the canonical PR of each accepted cherry-pick commit', () => { - assert.deepEqual( - [ + it('collects the canonical PR of each accepted cherry-pick commit', () => { + expect([ ...getCherryPickedPrsByCommit(`[auto-changelog] commit=${COMMIT_A} accepted source-pr=1 canonical-pr=1 cherry-pick=false [auto-changelog] commit=${COMMIT_B} accepted source-pr=7 canonical-pr=1 cherry-pick=true [auto-changelog] commit=${COMMIT_C} accepted source-pr=none canonical-pr=none cherry-pick=true`), - ], - [[COMMIT_B, '1']], - ); -}); + ]).toStrictEqual([[COMMIT_B, '1']]); + }); -test('finds the PRs cherry-picked onto the baseline branch', () => { - const cherryPickedPrsByCommit = new Map([ - [COMMIT_A, '1'], - [COMMIT_B, '2'], - ]); - - assert.deepEqual( - getPrsCherryPickedOntoBaseline({ - cherryPickedPrsByCommit, - baselineRef: 'origin/release/1.0.0', - isAncestor: (commit, ref) => - commit === COMMIT_A && ref === 'origin/release/1.0.0', - }), - new Set(['1']), - ); - assert.deepEqual( - getPrsCherryPickedOntoBaseline({ - cherryPickedPrsByCommit, - baselineRef: 'origin/stable', - isAncestor: () => false, - }), - new Set(), - ); -}); + it('finds the PRs cherry-picked onto the baseline branch', () => { + const cherryPickedPrsByCommit = new Map([ + [COMMIT_A, '1'], + [COMMIT_B, '2'], + ]); + + expect( + getPrsCherryPickedOntoBaseline({ + cherryPickedPrsByCommit, + baselineRef: 'origin/release/1.0.0', + isAncestor: (commit, ref) => + `${commit} ${ref}` === `${COMMIT_A} origin/release/1.0.0`, + }), + ).toStrictEqual(new Set(['1'])); + expect( + getPrsCherryPickedOntoBaseline({ + cherryPickedPrsByCommit, + baselineRef: 'origin/stable', + isAncestor: () => false, + }), + ).toStrictEqual(new Set()); + }); -test('maps each canonical PR to its cherry-pick PR numbers', () => { - assert.deepEqual( - [ + it('maps each canonical PR to its cherry-pick PR numbers', () => { + expect([ ...getCherryPickAliasesByPr(`[auto-changelog] commit=${COMMIT_A} accepted source-pr=1 canonical-pr=1 cherry-pick=false [auto-changelog] commit=${COMMIT_B} accepted source-pr=7 canonical-pr=1 cherry-pick=true [auto-changelog] commit=${COMMIT_C} accepted source-pr=8 canonical-pr=1 cherry-pick=true`), - ], - [['1', ['7', '8']]], - ); -}); - -test('reports PRs that no other section lists under any of their numbers', () => { - const changelog = [ - '## [2.0.0]', - '', - '### Fixed', - '', - '- Fixed one (#1)', - '', - '## [1.0.0]', - '', - '### Fixed', - '', - '- Fixed two (#2)', - '- Fixed three by its cherry-pick (#31)', - '', - ].join('\n'); + ]).toStrictEqual([['1', ['7', '8']]]); + }); - assert.deepEqual( - findPrsMissingFromChangelog({ - changelog, - prNumbers: ['1', '2', '3', '4'], - aliasesByPr: new Map([['3', ['31']]]), - version: '2.0.0', - repositoryUrl: 'https://github.com/MetaMask/example', - }), - ['1', '4'], - ); -}); + it('reports PRs that no other section lists under any of their numbers', () => { + const changelog = [ + '## [2.0.0]', + '', + '### Fixed', + '', + '- Fixed one (#1)', + '', + '## [1.0.0]', + '', + '### Fixed', + '', + '- Fixed two (#2)', + '- Fixed three by its cherry-pick (#31)', + '', + ].join('\n'); + + expect( + findPrsMissingFromChangelog({ + changelog, + prNumbers: ['1', '2', '3', '4'], + aliasesByPr: new Map([['3', ['31']]]), + version: '2.0.0', + repositoryUrl: 'https://github.com/MetaMask/example', + }), + ).toStrictEqual(['1', '4']); + }); -test('counts a pending section of the earlier release as listing a PR', () => { - const changelog = ['## [2.0.0]', '', '- Fixed one (#1)', ''].join('\n'); - const pendingSection = [ - '## [1.0.0]', - '', - '- Fixed two (#2)', - '- Fixed three by its cherry-pick (#31)', - ].join('\n'); + it('counts a pending section of the earlier release as listing a PR', () => { + const changelog = ['## [2.0.0]', '', '- Fixed one (#1)', ''].join('\n'); + const pendingSection = [ + '## [1.0.0]', + '', + '- Fixed two (#2)', + '- Fixed three by its cherry-pick (#31)', + ].join('\n'); + + expect( + findPrsMissingFromChangelog({ + changelog, + pendingSections: [pendingSection], + prNumbers: ['2', '3', '4'], + aliasesByPr: new Map([['3', ['31']]]), + version: '2.0.0', + repositoryUrl: 'https://github.com/MetaMask/example', + }), + ).toStrictEqual(['4']); + }); - assert.deepEqual( - findPrsMissingFromChangelog({ - changelog, - pendingSections: [pendingSection], - prNumbers: ['2', '3', '4'], - aliasesByPr: new Map([['3', ['31']]]), - version: '2.0.0', - repositoryUrl: 'https://github.com/MetaMask/example', - }), - ['4'], - ); -}); + const RELEASE_BASELINE = { + kind: 'release', + ref: 'origin/release/1.0.0', + version: '1.0.0', + } as const; -const RELEASE_BASELINE = { - kind: 'release', - ref: 'origin/release/1.0.0', - version: '1.0.0', -} as const; + it('reads the earlier release section from its open changelog PR', () => { + const lookups: string[][] = []; -test('reads the earlier release section from its open changelog PR', () => { - const lookups: string[][] = []; + expect( + getOpenBaselineChangelogSection({ + baseline: RELEASE_BASELINE, + determineBranch: (version) => `release-changelog/${version}`, + getSha: () => 'abc', + getOpenPrNumber: (...branches) => { + lookups.push(branches); + return '9'; + }, + readSection: (branch, version) => `${branch} ${version}`, + }), + ).toBe('release-changelog/1.0.0 1.0.0'); + expect(lookups).toStrictEqual([ + ['release-changelog/1.0.0', 'release/1.0.0'], + ]); + }); - assert.equal( - getOpenBaselineChangelogSection({ + it('ignores the earlier release changelog when no PR is open', () => { + const options = { baseline: RELEASE_BASELINE, - determineBranch: (version) => `release-changelog/${version}`, - getSha: () => 'abc', - getOpenPrNumber: (...branches) => { - lookups.push(branches); - return '9'; + determineBranch: (version: string): string => + `release-changelog/${version}`, + readSection: (): never => { + throw new Error('must not read'); }, - readSection: (branch, version) => `${branch} ${version}`, - }), - 'release-changelog/1.0.0 1.0.0', - ); - assert.deepEqual(lookups, [['release-changelog/1.0.0', 'release/1.0.0']]); -}); + }; -test('ignores the earlier release changelog when no PR is open', () => { - const options = { - baseline: RELEASE_BASELINE, - determineBranch: (version: string) => `release-changelog/${version}`, - readSection: () => { - throw new Error('must not read'); - }, - }; - - assert.equal( - getOpenBaselineChangelogSection({ - ...options, - getSha: () => undefined, - getOpenPrNumber: () => '9', - }), - undefined, - ); - assert.equal( - getOpenBaselineChangelogSection({ - ...options, - getSha: () => 'abc', - getOpenPrNumber: () => undefined, - }), - undefined, - ); -}); - -test('only reads an open changelog PR for a release baseline', () => { - for (const kind of ['stable', 'target'] as const) { - assert.equal( + expect( getOpenBaselineChangelogSection({ - baseline: { kind, ref: 'origin/stable', version: '1.0.0' }, - getSha: () => 'abc', + ...options, + getSha: () => undefined, getOpenPrNumber: () => '9', - readSection: () => 'section', }), - undefined, - ); - } -}); + ).toBeUndefined(); + expect( + getOpenBaselineChangelogSection({ + ...options, + getSha: () => 'abc', + getOpenPrNumber: () => undefined, + }), + ).toBeUndefined(); + }); -test('carries on when the open changelog branch lacks the section', (context) => { - context.mock.method(console, 'warn', () => undefined); + it('only reads an open changelog PR for a release baseline', () => { + for (const kind of ['stable', 'target'] as const) { + expect( + getOpenBaselineChangelogSection({ + baseline: { kind, ref: 'origin/stable', version: '1.0.0' }, + getSha: () => 'abc', + getOpenPrNumber: () => '9', + readSection: () => 'section', + }), + ).toBeUndefined(); + } + }); - assert.equal( - getOpenBaselineChangelogSection({ - baseline: RELEASE_BASELINE, - determineBranch: (version) => `release-changelog/${version}`, - getSha: () => 'abc', - getOpenPrNumber: () => '9', - readSection: () => { - throw new Error('Expected exactly one release heading for 1.0.0'); - }, - }), - undefined, - ); -}); + it('carries on when the open changelog branch lacks the section', () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); -const RELEASE_BRANCH_CHANGELOG = [ - '## [Unreleased]', - '', - '- Unreleased only (#9)', - '', - '## [2.0.0]', - '', - '### Fixed', - '', - '- Fixed one (#1)', - '- Fixed two (#2)', - ' - A sub-bullet', - '', - '## [1.0.0]', - '', - '- Fixed three (#3)', - '- Fixed four (#4)', - '', -].join('\n'); - -test('finds released entries a stale baseline restore drops', () => { - const restoredChangelog = [ - '## [2.0.0]', - '', - '- Fixed one (#1)', - '', - '## [1.0.0]', + expect( + getOpenBaselineChangelogSection({ + baseline: RELEASE_BASELINE, + determineBranch: (version) => `release-changelog/${version}`, + getSha: () => 'abc', + getOpenPrNumber: () => '9', + readSection: () => { + throw new Error('Expected exactly one release heading for 1.0.0'); + }, + }), + ).toBeUndefined(); + }); + + const RELEASE_BRANCH_CHANGELOG = [ + '## [Unreleased]', '', - '- Fixed three (#3)', - '- Fixed four (#4)', + '- Unreleased only (#9)', '', - ].join('\n'); - - assert.deepEqual( - findEntriesDroppedByRestore({ - restoredChangelog, - releaseChangelog: RELEASE_BRANCH_CHANGELOG, - }), - [{ version: '2.0.0', entryCount: 1, prNumbers: ['2'] }], - ); -}); - -test('counts an entry as dropped when only another version lists it', () => { - const restoredChangelog = [ '## [2.0.0]', '', + '### Fixed', + '', '- Fixed one (#1)', '- Fixed two (#2)', - '- Fixed three (#3)', + ' - A sub-bullet', '', '## [1.0.0]', '', + '- Fixed three (#3)', '- Fixed four (#4)', '', ].join('\n'); - assert.deepEqual( - findEntriesDroppedByRestore({ - restoredChangelog, - releaseChangelog: RELEASE_BRANCH_CHANGELOG, - }), - [{ version: '1.0.0', entryCount: 1, prNumbers: ['3'] }], - ); -}); - -test('reports nothing when the restore keeps every released entry', () => { - assert.deepEqual( - findEntriesDroppedByRestore({ - restoredChangelog: `${RELEASE_BRANCH_CHANGELOG}\n## [3.0.0]\n\n- New (#5)\n`, - releaseChangelog: RELEASE_BRANCH_CHANGELOG, - }), - [], - ); -}); + it('finds released entries a stale baseline restore drops', () => { + const restoredChangelog = [ + '## [2.0.0]', + '', + '- Fixed one (#1)', + '', + '## [1.0.0]', + '', + '- Fixed three (#3)', + '- Fixed four (#4)', + '', + ].join('\n'); -test('words the warning for entries the restore dropped', () => { - assert.equal( - getDroppedEntriesWarning('8.20.0', { - baselineVersion: '8.19.0', - releaseBranch: 'release/8.20.0', - versions: [ - { - version: '8.18.0', - entryCount: 5, - prNumbers: ['1', '2', '3', '4', '5'], - }, - { version: '8.17.0', entryCount: 1, prNumbers: ['6'] }, - ], - }), - '> Restoring the changelog from the 8.19.0 baseline dropped 6 entries that release/8.20.0 lists under earlier releases: 8.18.0 (5 entries: #1, #2, #3, +2 more); 8.17.0 (1 entry: #6). The 8.19.0 changelog may be stale for 8.20.0; fix it or merge its changelog PR first, then rerun.', - ); - assert.match( - getDroppedEntriesWarning('8.20.0', { - baselineVersion: '8.19.0', - releaseBranch: 'release/8.20.0', - versions: [{ version: '8.18.0', entryCount: 1, prNumbers: ['1'] }], - }), - /dropped 1 entry that release\/8\.20\.0 lists/u, - ); -}); + expect( + findEntriesDroppedByRestore({ + restoredChangelog, + releaseChangelog: RELEASE_BRANCH_CHANGELOG, + }), + ).toStrictEqual([{ version: '2.0.0', entryCount: 1, prNumbers: ['2'] }]); + }); -test('does not count a reworded entry as dropped', () => { - const releaseChangelog = '## [1.0.0]\n\n- Fixed a crash (#1, #2)\n'; - assert.deepEqual( - findEntriesDroppedByRestore({ - restoredChangelog: '## [1.0.0]\n\n- Fixed the crash on launch (#2)\n', - releaseChangelog, - }), - [], - ); -}); + it('counts an entry as dropped when only another version lists it', () => { + const restoredChangelog = [ + '## [2.0.0]', + '', + '- Fixed one (#1)', + '- Fixed two (#2)', + '- Fixed three (#3)', + '', + '## [1.0.0]', + '', + '- Fixed four (#4)', + '', + ].join('\n'); -test('reads long PR links when comparing dropped entries', () => { - const repositoryUrl = 'https://github.com/MetaMask/metamask-mobile'; - const link = (number: string): string => - `[#${number}](${repositoryUrl}/pull/${number})`; - const releaseChangelog = `## [1.0.0]\n\n- Fixed a crash (${link('1')})\n- Fixed a hang (${link('2')})\n`; - assert.deepEqual( - findEntriesDroppedByRestore({ - restoredChangelog: `## [1.0.0]\n\n- Fixed the crash on launch (${link('1')})\n`, - releaseChangelog, - repositoryUrl, - }), - [{ version: '1.0.0', entryCount: 1, prNumbers: ['2'] }], - ); -}); + expect( + findEntriesDroppedByRestore({ + restoredChangelog, + releaseChangelog: RELEASE_BRANCH_CHANGELOG, + }), + ).toStrictEqual([{ version: '1.0.0', entryCount: 1, prNumbers: ['3'] }]); + }); -test('compares an entry without a PR number by its text', () => { - const releaseChangelog = '## [1.0.0]\n\n- Manual note\n'; - assert.deepEqual( - findEntriesDroppedByRestore({ - restoredChangelog: '## [1.0.0]\n\n- Other note\n', - releaseChangelog, - }), - [{ version: '1.0.0', entryCount: 1, prNumbers: [] }], - ); - assert.deepEqual( - findEntriesDroppedByRestore({ - restoredChangelog: releaseChangelog, - releaseChangelog, - }), - [], - ); -}); + it('reports nothing when the restore keeps every released entry', () => { + expect( + findEntriesDroppedByRestore({ + restoredChangelog: `${RELEASE_BRANCH_CHANGELOG}\n## [3.0.0]\n\n- New (#5)\n`, + releaseChangelog: RELEASE_BRANCH_CHANGELOG, + }), + ).toStrictEqual([]); + }); -test('lists up to three dropped PRs before summarizing the rest', () => { - const warningFor = (prNumbers: string[]): string => - getDroppedEntriesWarning('8.20.0', { - baselineVersion: '8.19.0', - releaseBranch: 'release/8.20.0', - versions: [ - { version: '8.18.0', entryCount: prNumbers.length, prNumbers }, - ], - }); - assert.match(warningFor(['1', '2', '3']), /\(3 entries: #1, #2, #3\)/u); - assert.match( - warningFor(['1', '2', '3', '4']), - /\(4 entries: #1, #2, #3, \+1 more\)/u, - ); -}); + it('words the warning for entries the restore dropped', () => { + expect( + getDroppedEntriesWarning('8.20.0', { + baselineVersion: '8.19.0', + releaseBranch: 'release/8.20.0', + versions: [ + { + version: '8.18.0', + entryCount: 5, + prNumbers: ['1', '2', '3', '4', '5'], + }, + { version: '8.17.0', entryCount: 1, prNumbers: ['6'] }, + ], + }), + ).toBe( + '> Restoring the changelog from the 8.19.0 baseline dropped 6 entries that release/8.20.0 lists under earlier releases: 8.18.0 (5 entries: #1, #2, #3, +2 more); 8.17.0 (1 entry: #6). The 8.19.0 changelog may be stale for 8.20.0; fix it or merge its changelog PR first, then rerun.', + ); + expect( + getDroppedEntriesWarning('8.20.0', { + baselineVersion: '8.19.0', + releaseBranch: 'release/8.20.0', + versions: [{ version: '8.18.0', entryCount: 1, prNumbers: ['1'] }], + }), + ).toMatch(/dropped 1 entry that release\/8\.20\.0 lists/u); + }); -test('adds the dropped entries warning to the PR body', () => { - const { body } = getChangelogPrPresentation({ - version: '8.20.0', - changelogBranch: 'release-changelog/8.20.0', - proofreadingStatus: 'succeeded', - droppedEntries: { - baselineVersion: '8.19.0', - releaseBranch: 'release/8.20.0', - versions: [{ version: '8.18.0', entryCount: 1, prNumbers: ['1'] }], - }, + it('does not count a reworded entry as dropped', () => { + const releaseChangelog = '## [1.0.0]\n\n- Fixed a crash (#1, #2)\n'; + expect( + findEntriesDroppedByRestore({ + restoredChangelog: '## [1.0.0]\n\n- Fixed the crash on launch (#2)\n', + releaseChangelog, + }), + ).toStrictEqual([]); }); - assert.match(body, /^This PR updates the change log for 8\.20\.0\./u); - assert.match( - body, - /\n\n> Restoring the changelog from the 8\.19\.0 baseline/u, - ); -}); + it('reads long PR links when comparing dropped entries', () => { + const repositoryUrl = 'https://github.com/MetaMask/metamask-mobile'; + const link = (number: string): string => + `[#${number}](${repositoryUrl}/pull/${number})`; + const releaseChangelog = `## [1.0.0]\n\n- Fixed a crash (${link('1')})\n- Fixed a hang (${link('2')})\n`; + expect( + findEntriesDroppedByRestore({ + restoredChangelog: `## [1.0.0]\n\n- Fixed the crash on launch (${link('1')})\n`, + releaseChangelog, + repositoryUrl, + }), + ).toStrictEqual([{ version: '1.0.0', entryCount: 1, prNumbers: ['2'] }]); + }); -test('words the warning for PRs the earlier changelog lacks', () => { - assert.equal( - getUnlistedCherryPicksWarning('13.56.0', { - baselineVersion: '13.55.0', - prNumbers: ['47395', '47400'], - }), - '> #47395, #47400 were left out of 13.56.0 because their cherry-picks are already on the 13.55.0 branch, but the 13.55.0 changelog does not list them. Add an entry to the right release if one is needed.', - ); - assert.equal( - getUnlistedCherryPicksWarning('13.56.0', { - baselineVersion: '13.55.0', - prNumbers: ['47395'], - }), - '> #47395 was left out of 13.56.0 because its cherry-pick is already on the 13.55.0 branch, but the 13.55.0 changelog does not list it. Add an entry to the right release if one is needed.', - ); -}); + it('compares an entry without a PR number by its text', () => { + const releaseChangelog = '## [1.0.0]\n\n- Manual note\n'; + expect( + findEntriesDroppedByRestore({ + restoredChangelog: '## [1.0.0]\n\n- Other note\n', + releaseChangelog, + }), + ).toStrictEqual([{ version: '1.0.0', entryCount: 1, prNumbers: [] }]); + expect( + findEntriesDroppedByRestore({ + restoredChangelog: releaseChangelog, + releaseChangelog, + }), + ).toStrictEqual([]); + }); -test('removes a left-out warning that no longer holds', () => { - const existingBody = `This PR updates the change log for 8.20.0.\r\n\r\n${getUnlistedCherryPicksWarning('8.20.0', { baselineVersion: '8.19.0', prNumbers: ['1'] })}`; - assert.equal( - refreshGeneratedWarnings({ existingBody, version: '8.20.0' }), - 'This PR updates the change log for 8.20.0.', - ); -}); + it('lists up to three dropped PRs before summarizing the rest', () => { + const warningFor = (prNumbers: string[]): string => + getDroppedEntriesWarning('8.20.0', { + baselineVersion: '8.19.0', + releaseBranch: 'release/8.20.0', + versions: [ + { version: '8.18.0', entryCount: prNumbers.length, prNumbers }, + ], + }); + expect(warningFor(['1', '2', '3'])).toMatch(/\(3 entries: #1, #2, #3\)/u); + expect(warningFor(['1', '2', '3', '4'])).toMatch( + /\(4 entries: #1, #2, #3, \+1 more\)/u, + ); + }); -test('replaces a stale warning and keeps unrelated quotes', () => { - const kept = '> AI automation failed, not proofread.'; - const existingBody = `Intro.\n\n${kept}\n\n${getUnlistedCherryPicksWarning('8.20.0', { baselineVersion: '8.19.0', prNumbers: ['1', '2'] })}`; - const unlistedCherryPicks = { - baselineVersion: '8.19.0', - prNumbers: ['2'], - }; - assert.equal( - refreshGeneratedWarnings({ - existingBody, + it('adds the dropped entries warning to the PR body', () => { + const { body } = getChangelogPrPresentation({ version: '8.20.0', - unlistedCherryPicks, - }), - `Intro.\n\n${kept}\n\n${getUnlistedCherryPicksWarning('8.20.0', unlistedCherryPicks)}`, - ); -}); + changelogBranch: 'release-changelog/8.20.0', + proofreadingStatus: 'succeeded', + droppedEntries: { + baselineVersion: '8.19.0', + releaseBranch: 'release/8.20.0', + versions: [{ version: '8.18.0', entryCount: 1, prNumbers: ['1'] }], + }, + }); -test('leaves a body whose warnings still hold', () => { - const unlistedCherryPicks = { - baselineVersion: '8.19.0', - prNumbers: ['1'], - }; - const existingBody = `Intro.\n\n${getUnlistedCherryPicksWarning('8.20.0', unlistedCherryPicks)}`; - assert.equal( - refreshGeneratedWarnings({ - existingBody, - version: '8.20.0', - unlistedCherryPicks, - }), - undefined, - ); -}); + expect(body).toMatch(/^This PR updates the change log for 8\.20\.0\./u); + expect(body).toMatch( + /\n\n> Restoring the changelog from the 8\.19\.0 baseline/u, + ); + }); -const RUN_PATH = '.github/workflows/update-release-changelog.yml'; - -test('finds the run the moving push triggered', () => { - assert.equal( - hasWorkflowRunForSha({ - sha: 'abc', - workflowPath: RUN_PATH, - listRunPaths: () => ['.github/workflows/other.yml', RUN_PATH], - }), - true, - ); -}); + it('words the warning for PRs the earlier changelog lacks', () => { + expect( + getUnlistedCherryPicksWarning('13.56.0', { + baselineVersion: '13.55.0', + prNumbers: ['47395', '47400'], + }), + ).toBe( + '> #47395, #47400 were left out of 13.56.0 because their cherry-picks are already on the 13.55.0 branch, but the 13.55.0 changelog does not list them. Add an entry to the right release if one is needed.', + ); + expect( + getUnlistedCherryPicksWarning('13.56.0', { + baselineVersion: '13.55.0', + prNumbers: ['47395'], + }), + ).toBe( + '> #47395 was left out of 13.56.0 because its cherry-pick is already on the 13.55.0 branch, but the 13.55.0 changelog does not list it. Add an entry to the right release if one is needed.', + ); + }); -test('waits for the run of the moving push to appear', () => { - const waits: number[] = []; - let lookups = 0; - assert.equal( - hasWorkflowRunForSha({ - sha: 'abc', - workflowPath: RUN_PATH, - listRunPaths: () => { - lookups += 1; - return lookups < 3 ? [] : [RUN_PATH]; - }, - attempts: 5, - delayMs: 1000, - wait: (milliseconds) => waits.push(milliseconds), - }), - true, - ); - assert.deepEqual(waits, [1000, 1000]); -}); + it('removes a left-out warning that no longer holds', () => { + const existingBody = `This PR updates the change log for 8.20.0.\r\n\r\n${getUnlistedCherryPicksWarning('8.20.0', { baselineVersion: '8.19.0', prNumbers: ['1'] })}`; + expect(refreshGeneratedWarnings({ existingBody, version: '8.20.0' })).toBe( + 'This PR updates the change log for 8.20.0.', + ); + }); -test('gives up after the last attempt without a matching run', () => { - const waits: number[] = []; - assert.equal( - hasWorkflowRunForSha({ - sha: 'abc', - workflowPath: RUN_PATH, - listRunPaths: () => [], - attempts: 3, - delayMs: 1000, - wait: (milliseconds) => waits.push(milliseconds), - }), - false, - ); - assert.deepEqual(waits, [1000, 1000]); -}); + it('replaces a stale warning and keeps unrelated quotes', () => { + const kept = '> AI automation failed, not proofread.'; + const existingBody = `Intro.\n\n${kept}\n\n${getUnlistedCherryPicksWarning('8.20.0', { baselineVersion: '8.19.0', prNumbers: ['1', '2'] })}`; + const unlistedCherryPicks = { + baselineVersion: '8.19.0', + prNumbers: ['2'], + }; + expect( + refreshGeneratedWarnings({ + existingBody, + version: '8.20.0', + unlistedCherryPicks, + }), + ).toBe( + `Intro.\n\n${kept}\n\n${getUnlistedCherryPicksWarning('8.20.0', unlistedCherryPicks)}`, + ); + }); -test('does not assume a newer run when none matches or the lookup fails', () => { - assert.equal( - hasWorkflowRunForSha({ - sha: 'abc', - workflowPath: RUN_PATH, - listRunPaths: () => ['.github/workflows/other.yml'], - wait: () => undefined, - }), - false, - ); - assert.equal( - hasWorkflowRunForSha({ - sha: 'abc', - workflowPath: RUN_PATH, - listRunPaths: () => { - throw new Error('403'); - }, - }), - false, - ); - assert.equal( - hasWorkflowRunForSha({ - sha: 'abc', - workflowPath: undefined, - listRunPaths: () => [RUN_PATH], - }), - false, - ); -}); + it('leaves a body whose warnings still hold', () => { + const unlistedCherryPicks = { + baselineVersion: '8.19.0', + prNumbers: ['1'], + }; + const existingBody = `Intro.\n\n${getUnlistedCherryPicksWarning('8.20.0', unlistedCherryPicks)}`; + expect( + refreshGeneratedWarnings({ + existingBody, + version: '8.20.0', + unlistedCherryPicks, + }), + ).toBeUndefined(); + }); -test('reads the calling workflow path from the workflow ref', () => { - assert.equal( - getCallingWorkflowPath({ - GITHUB_REPOSITORY: 'MetaMask/metamask-mobile', - GITHUB_WORKFLOW_REF: `MetaMask/metamask-mobile/${RUN_PATH}@refs/heads/release/8.20.0`, - }), - RUN_PATH, - ); - assert.equal(getCallingWorkflowPath({}), undefined); -}); + const RUN_PATH = '.github/workflows/update-release-changelog.yml'; -const staleWarning = getUnlistedCherryPicksWarning('8.20.0', { - baselineVersion: '8.19.0', - prNumbers: ['1'], -}); + it('finds the run the moving push triggered', () => { + expect( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: RUN_PATH, + listRunPaths: () => ['.github/workflows/other.yml', RUN_PATH], + }), + ).toBe(true); + }); -test('keeps text written on the line after a stale warning', () => { - assert.equal( - refreshGeneratedWarnings({ - existingBody: `Intro.\n\n${staleWarning}\nChecked #1, fine.`, - version: '8.20.0', - }), - 'Intro.\n\nChecked #1, fine.', - ); -}); + it('waits for the run of the moving push to appear', () => { + const waits: number[] = []; + const listRunPaths = vi + .fn<(sha: string) => string[]>() + .mockReturnValueOnce([]) + .mockReturnValueOnce([]) + .mockReturnValue([RUN_PATH]); + expect( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: RUN_PATH, + listRunPaths, + attempts: 5, + delayMs: 1000, + wait: (milliseconds) => waits.push(milliseconds), + }), + ).toBe(true); + expect(waits).toStrictEqual([1000, 1000]); + }); -test('removes a stale warning separated by extra blank lines', () => { - assert.equal( - refreshGeneratedWarnings({ - existingBody: `Intro.\n\n\n${staleWarning}`, - version: '8.20.0', - }), - 'Intro.', - ); -}); + it('gives up after the last attempt without a matching run', () => { + const waits: number[] = []; + expect( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: RUN_PATH, + listRunPaths: () => [], + attempts: 3, + delayMs: 1000, + wait: (milliseconds) => waits.push(milliseconds), + }), + ).toBe(false); + expect(waits).toStrictEqual([1000, 1000]); + }); -test('adds a warning to an empty body without leading blank lines', () => { - const unlistedCherryPicks = { - baselineVersion: '8.19.0', - prNumbers: ['1'], - }; - assert.equal( - refreshGeneratedWarnings({ - existingBody: '', - version: '8.20.0', - unlistedCherryPicks, - }), - staleWarning, - ); -}); + it('does not assume a newer run when none matches or the lookup fails', () => { + expect( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: RUN_PATH, + listRunPaths: () => ['.github/workflows/other.yml'], + wait: () => undefined, + }), + ).toBe(false); + expect( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: RUN_PATH, + listRunPaths: () => { + throw new Error('403'); + }, + }), + ).toBe(false); + expect( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: undefined, + listRunPaths: () => [RUN_PATH], + }), + ).toBe(false); + }); -test('leaves a CRLF body whose warning sits mid-body', () => { - const unlistedCherryPicks = { + it('reads the calling workflow path from the workflow ref', () => { + expect( + getCallingWorkflowPath({ + GITHUB_REPOSITORY: 'MetaMask/metamask-mobile', + GITHUB_WORKFLOW_REF: `MetaMask/metamask-mobile/${RUN_PATH}@refs/heads/release/8.20.0`, + }), + ).toBe(RUN_PATH); + expect(getCallingWorkflowPath({})).toBeUndefined(); + }); + + const staleWarning = getUnlistedCherryPicksWarning('8.20.0', { baselineVersion: '8.19.0', prNumbers: ['1'], - }; - assert.equal( - refreshGeneratedWarnings({ - existingBody: `Intro.\r\n\r\n${staleWarning}\r\n\r\nTrailing note.`, - version: '8.20.0', - unlistedCherryPicks, - }), - undefined, - ); -}); + }); -const EXCLUSION_SECTION = [ - '## [2.0.0]', - '', - '### Fixed', - '', - '- Fixed one (#1)', - '- Fixed two (#2)', - '- Fixed three (#3, #7)', - '- Fixed the regression from (#4) (#5)', - '', -].join('\n'); - -test('excludes the entries of PRs already on the baseline branch', () => { - const result = excludePrsCherryPickedOntoBaseline({ - section: EXCLUSION_SECTION, - shippedEarlier: new Set(['1', '3']), - aliasesByPr: new Map([['3', ['7']]]), - reviewedPrNumbers: new Set(), + it('keeps text written on the line after a stale warning', () => { + expect( + refreshGeneratedWarnings({ + existingBody: `Intro.\n\n${staleWarning}\nChecked #1, fine.`, + version: '8.20.0', + }), + ).toBe('Intro.\n\nChecked #1, fine.'); }); - assert.deepEqual(result.excludedPrNumbers, ['1', '3']); - assert.equal( - result.section, - [ - '## [2.0.0]', - '', - '### Fixed', - '', - '- Fixed two (#2)', - '- Fixed the regression from (#4) (#5)', - ].join('\n'), - ); -}); + it('removes a stale warning separated by extra blank lines', () => { + expect( + refreshGeneratedWarnings({ + existingBody: `Intro.\n\n\n${staleWarning}`, + version: '8.20.0', + }), + ).toBe('Intro.'); + }); -test('keeps an entry that also owns a PR that is not excluded', () => { - const result = excludePrsCherryPickedOntoBaseline({ - section: EXCLUSION_SECTION, - shippedEarlier: new Set(['4']), - aliasesByPr: new Map(), - reviewedPrNumbers: new Set(), + it('adds a warning to an empty body without leading blank lines', () => { + const unlistedCherryPicks = { + baselineVersion: '8.19.0', + prNumbers: ['1'], + }; + expect( + refreshGeneratedWarnings({ + existingBody: '', + version: '8.20.0', + unlistedCherryPicks, + }), + ).toBe(staleWarning); }); - assert.equal(result.section, EXCLUSION_SECTION); - assert.deepEqual(result.excludedPrNumbers, []); -}); + it('leaves a CRLF body whose warning sits mid-body', () => { + const unlistedCherryPicks = { + baselineVersion: '8.19.0', + prNumbers: ['1'], + }; + expect( + refreshGeneratedWarnings({ + existingBody: `Intro.\r\n\r\n${staleWarning}\r\n\r\nTrailing note.`, + version: '8.20.0', + unlistedCherryPicks, + }), + ).toBeUndefined(); + }); -test('does not report PRs a reviewer already approved in the section', () => { - const result = excludePrsCherryPickedOntoBaseline({ - section: EXCLUSION_SECTION, - shippedEarlier: new Set(['1', '2']), - aliasesByPr: new Map(), - reviewedPrNumbers: new Set(['1']), + const EXCLUSION_SECTION = [ + '## [2.0.0]', + '', + '### Fixed', + '', + '- Fixed one (#1)', + '- Fixed two (#2)', + '- Fixed three (#3, #7)', + '- Fixed the regression from (#4) (#5)', + '', + ].join('\n'); + + it('excludes the entries of PRs already on the baseline branch', () => { + const result = excludePrsCherryPickedOntoBaseline({ + section: EXCLUSION_SECTION, + shippedEarlier: new Set(['1', '3']), + aliasesByPr: new Map([['3', ['7']]]), + reviewedPrNumbers: new Set(), + }); + + expect(result.excludedPrNumbers).toStrictEqual(['1', '3']); + expect(result.section).toBe( + [ + '## [2.0.0]', + '', + '### Fixed', + '', + '- Fixed two (#2)', + '- Fixed the regression from (#4) (#5)', + ].join('\n'), + ); }); - assert.deepEqual(result.excludedPrNumbers, ['2']); -}); + it('keeps an entry that also owns a PR that is not excluded', () => { + const result = excludePrsCherryPickedOntoBaseline({ + section: EXCLUSION_SECTION, + shippedEarlier: new Set(['4']), + aliasesByPr: new Map(), + reviewedPrNumbers: new Set(), + }); -test('does not report excluded PRs that the section never listed', () => { - const result = excludePrsCherryPickedOntoBaseline({ - section: EXCLUSION_SECTION, - shippedEarlier: new Set(['99']), - aliasesByPr: new Map(), - reviewedPrNumbers: new Set(), + expect(result.section).toBe(EXCLUSION_SECTION); + expect(result.excludedPrNumbers).toStrictEqual([]); }); - assert.equal(result.section, EXCLUSION_SECTION); - assert.deepEqual(result.excludedPrNumbers, []); -}); + it('does not report PRs a reviewer already approved in the section', () => { + const result = excludePrsCherryPickedOntoBaseline({ + section: EXCLUSION_SECTION, + shippedEarlier: new Set(['1', '2']), + aliasesByPr: new Map(), + reviewedPrNumbers: new Set(['1']), + }); + + expect(result.excludedPrNumbers).toStrictEqual(['2']); + }); + + it('does not report excluded PRs that the section never listed', () => { + const result = excludePrsCherryPickedOntoBaseline({ + section: EXCLUSION_SECTION, + shippedEarlier: new Set(['99']), + aliasesByPr: new Map(), + reviewedPrNumbers: new Set(), + }); -test('adds the unlisted cherry-pick warning to the PR body', () => { - const { body } = getChangelogPrPresentation({ - version: '2.0.0', - changelogBranch: 'release-changelog/2.0.0', - proofreadingStatus: 'succeeded', - unlistedCherryPicks: { baselineVersion: '1.0.0', prNumbers: ['5'] }, + expect(result.section).toBe(EXCLUSION_SECTION); + expect(result.excludedPrNumbers).toStrictEqual([]); }); - assert.match(body, /#5 was left out of 2\.0\.0/u); + it('adds the unlisted cherry-pick warning to the PR body', () => { + const { body } = getChangelogPrPresentation({ + version: '2.0.0', + changelogBranch: 'release-changelog/2.0.0', + proofreadingStatus: 'succeeded', + unlistedCherryPicks: { baselineVersion: '1.0.0', prNumbers: ['5'] }, + }); + + expect(body).toMatch(/#5 was left out of 2\.0\.0/u); + }); }); diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index 415c2866..61224d9f 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -1,9 +1,4 @@ { - ".github/actions/draft-segment-schema-pr/gate.test.mjs": { - "node/no-sync": { - "count": 1 - } - }, ".github/actions/playwright-test-health-report/create-playwright-test-health-report.mjs": { "n/hashbang": { "count": 1 @@ -28,11 +23,6 @@ "count": 9 } }, - ".github/actions/playwright-test-health-report/lib/report-health.test.mjs": { - "require-unicode-regexp": { - "count": 2 - } - }, ".github/actions/playwright-test-health-report/lib/slack-test-health-blocks.mjs": { "no-useless-escape": { "count": 1 @@ -288,128 +278,6 @@ "count": 3 } }, - ".github/scripts/tests/clean-release-changelog.test.mts": { - "node/no-process-env": { - "count": 4 - }, - "node/no-sync": { - "count": 12 - }, - "typescript/explicit-function-return-type": { - "count": 5 - }, - "typescript/no-base-to-string": { - "count": 2 - }, - "typescript/no-unnecessary-type-assertion": { - "count": 1 - }, - "typescript/return-await": { - "count": 9 - }, - "vitest/no-conditional-in-test": { - "count": 7 - }, - "vitest/no-import-node-test": { - "count": 1 - } - }, - ".github/scripts/tests/git-test-environment.mts": { - "node/no-process-env": { - "count": 1 - }, - "node/no-sync": { - "count": 1 - } - }, - ".github/scripts/tests/merge-previous-releases.test.mts": { - "node/no-process-env": { - "count": 1 - }, - "node/no-sync": { - "count": 10 - }, - "typescript/explicit-function-return-type": { - "count": 3 - }, - "vitest/no-import-node-test": { - "count": 1 - } - }, - ".github/scripts/tests/release-section.test.mts": { - "typescript/explicit-function-return-type": { - "count": 1 - }, - "vitest/no-conditional-in-test": { - "count": 1 - }, - "vitest/no-import-node-test": { - "count": 1 - } - }, - ".github/scripts/tests/release-version-utils.test.mts": { - "vitest/no-import-node-test": { - "count": 1 - } - }, - ".github/scripts/tests/retry.test.mts": { - "typescript/return-await": { - "count": 2 - }, - "vitest/no-conditional-in-test": { - "count": 1 - }, - "vitest/no-import-node-test": { - "count": 1 - } - }, - ".github/scripts/tests/update-release-changelog-baseline.test.mts": { - "import/consistent-type-specifier-style": { - "count": 1 - }, - "typescript/explicit-function-return-type": { - "count": 1 - }, - "vitest/no-import-node-test": { - "count": 1 - } - }, - ".github/scripts/tests/update-release-changelog-git.test.mts": { - "node/no-sync": { - "count": 14 - }, - "vitest/no-conditional-in-test": { - "count": 2 - }, - "vitest/no-import-node-test": { - "count": 1 - } - }, - ".github/scripts/tests/update-release-changelog-reachability.test.mts": { - "node/no-sync": { - "count": 3 - }, - "vitest/no-import-node-test": { - "count": 1 - } - }, - ".github/scripts/tests/update-release-changelog.test.mts": { - "node/no-process-env": { - "count": 5 - }, - "node/no-sync": { - "count": 4 - }, - "typescript/explicit-function-return-type": { - "count": 3 - }, - "vitest/no-conditional-in-test": { - "count": 2 - }, - "vitest/no-import-node-test": { - "count": 1 - } - }, ".github/scripts/update-release-changelog-baseline.mts": { "import/consistent-type-specifier-style": { "count": 1 diff --git a/oxlint.config.mts b/oxlint.config.mts index e2c2b756..cbae98fd 100644 --- a/oxlint.config.mts +++ b/oxlint.config.mts @@ -4,20 +4,6 @@ import nodejs from '@metamask/oxlint-config-nodejs'; import typescript from '@metamask/oxlint-config-typescript'; import vitest from '@metamask/oxlint-config-vitest'; -type Override = NonNullable< - Parameters[0]['overrides'] ->[number]; - -const nodeTestOverride: Override = { - files: ['.github/scripts/**/*.test.mts'], - extends: [nodejs, vitest], - rules: { - // The top level `test()` calls of the `node:test` tests return promises - // that the test runner tracks, so they are not floating. - 'typescript/no-floating-promises': 'off', - }, -}; - export default createConfig({ extends: [base], @@ -50,18 +36,32 @@ export default createConfig({ }, { - // The workflow scripts read their inputs from the environment. + files: [ + 'src/**/*.test.ts', + '.github/**/*.test.{mjs,mts}', + '.github/scripts/tests/**', + ], + extends: [ + nodejs, + vitest, + { + // Tests read the environment and use synchronous APIs for fixtures. + rules: { + 'node/no-process-env': 'off', + 'node/no-sync': 'off', + }, + }, + ], + }, + + { + // The workflow scripts are command line programs: they read their inputs + // from the environment and can use synchronous APIs. files: ['.github/**'], rules: { 'node/no-process-env': 'off', + 'node/no-sync': 'off', }, }, - - { - files: ['src/**/*.test.ts'], - extends: [nodejs, vitest], - }, - - nodeTestOverride, ], }); diff --git a/package.json b/package.json index 70d45545..d27d62f2 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "lint:tsc": "tsc", "segment-schema:draft-pr": "ts-node src/segment-schema-draft-pr/cli.ts", "slack:release-testing": "node .github/scripts/slack-release-testing.mjs", - "test": "vitest run --coverage && node --test '.github/**/*.test.{mjs,mts}'", + "test": "vitest run --coverage", "test:watch": "vitest --watch", "update-release-sheet": "node .github/scripts/update-release-sheet.mjs" }, diff --git a/vitest.config.mts b/vitest.config.mts index dfbe4073..33b3ca06 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -5,32 +5,54 @@ export default defineConfig({ // Opt in with `yarn test:watch`. watch: false, - include: ['src/**/*.test.ts'], - testTimeout: 2500, - // Keep mocks from leaking between tests. mockReset: true, restoreMocks: true, passWithNoTests: true, + projects: [ + { + extends: true, + test: { + name: 'src', + include: ['src/**/*.test.ts'], + testTimeout: 2500, + }, + }, + + { + extends: true, + test: { + name: 'workflow-scripts', + include: ['.github/**/*.test.{mjs,mts}'], + + // Many of these tests build real git repositories in temporary + // directories and shell out to `git`, which is slower than the + // default. + testTimeout: 30_000, + }, + }, + ], + coverage: { // Enabled with `--coverage` in the `test` script. enabled: false, provider: 'v8', - include: ['src/**/*.ts'], - exclude: ['src/**/*.test.ts'], + + include: ['src/**/*.ts', '.github/**/*.{js,mjs,mts,ts}'], + exclude: ['**/*.test.*', '.github/scripts/tests/**'], reporter: ['text', 'html', 'json-summary'], reportsDirectory: 'coverage', thresholds: { // Raises the thresholds in this file when coverage improves. autoUpdate: true, - branches: 62.31, - functions: 62.25, - lines: 65.55, - statements: 65.73, + branches: 41.72, + functions: 50.63, + lines: 41.61, + statements: 41.5, }, }, },