From 9f894efc88e40d1c54bca2a4c74c104c8fe66505 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Wed, 11 Nov 2026 22:09:13 +0100 Subject: [PATCH 1/4] chore: migrate node:test tests to vitest --- .../draft-segment-schema-pr/gate.test.mjs | 107 ++-- .../lib/report-health.test.mjs | 54 +- .../tests/clean-release-changelog.test.mts | 432 +++++++-------- .../tests/merge-previous-releases.test.mts | 19 +- .../scripts/tests/release-section.test.mts | 210 ++++---- .../tests/release-version-utils.test.mts | 30 +- .github/scripts/tests/retry.test.mts | 31 +- ...update-release-changelog-baseline.test.mts | 135 +++-- .../update-release-changelog-git.test.mts | 216 ++++---- ...te-release-changelog-reachability.test.mts | 22 +- .../tests/update-release-changelog.test.mts | 494 ++++++++---------- oxlint-suppressions.json | 93 +++- oxlint.config.mts | 18 +- package.json | 2 +- vitest.config.mts | 30 +- 15 files changed, 870 insertions(+), 1023 deletions(-) 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..95bc57cb 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, @@ -52,10 +51,10 @@ 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); + expect(test.latestClassification).toBe('passed'); + expect(test.historicalBrokenCount).toBe(1); + expect(test.historicalFlakyCount).toBe(1); + expect(test.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.length).toBe(1); + expect(flakyItems.length).toBe(0); + expect(brokenItems.length).toBe(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/); + expect(text).toMatch(/flaky 3\/8 runs/); }); }); 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', ); }); @@ -202,8 +197,7 @@ describe('createSlackBlocks path links', () => { (element) => element.type === 'link' && element.text === 'toggles sync', ); - assert.equal( - link?.url, + expect(link?.url).toBe( '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..9fb5f579 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 { expect, test, vi } from 'vitest'; import { assertPrEvidenceAvailable, @@ -42,13 +41,12 @@ const generatedSection = `## [13.51.0] - Fixed an issue (#102)`; test('removes LiteLLM credentials from evidence subprocesses', () => { - assert.deepEqual( + expect( getEnvironmentWithoutAiKey({ GH_TOKEN: 'github-token', AI_ANALYZER_LITELLM_KEY: 'litellm-key', }), - { GH_TOKEN: 'github-token' }, - ); + ).toStrictEqual({ GH_TOKEN: 'github-token' }); }); test('retries transient GitHub API failures before returning evidence', async () => { @@ -68,15 +66,15 @@ test('retries transient GitHub API failures before returning evidence', async () }, ); - assert.equal(response, '{"title":"Recovered"}'); - assert.equal(attempts, 3); - assert.deepEqual(retryDelays, [1_000, 2_000]); + expect(response).toBe('{"title":"Recovered"}'); + expect(attempts).toBe(3); + expect(retryDelays).toStrictEqual([1_000, 2_000]); }); test('does not retry permanent GitHub API failures', async () => { let attempts = 0; - await assert.rejects( - async () => + await expect( + (async () => requestGhApiWithRetry( ['repos/MetaMask/metamask-extension/pulls/1'], async () => { @@ -86,23 +84,18 @@ test('does not retry permanent GitHub API failures', async () => { async () => { throw new Error('Unexpected retry'); }, - ), - /HTTP 404/u, - ); - assert.equal(attempts, 1); - assert.equal( - isRetryableGhApiFailure(new Error('HTTP 404: Not Found')), - false, - ); + ))(), + ).rejects.toThrow(/HTTP 404/u); + expect(attempts).toBe(1); + expect(isRetryableGhApiFailure(new Error('HTTP 404: Not Found'))).toBe(false); // The command line names the PR, which is not an HTTP status. - assert.equal( + 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 () => { @@ -122,12 +115,11 @@ test('uses PR title and body when local evidence is unavailable', async () => { }, ); - assert.deepEqual(evidence.unavailablePrEvidence, []); - assert.match( - evidence.evidence[0] ?? '', + expect(evidence.unavailablePrEvidence).toStrictEqual([]); + expect(evidence.evidence[0] ?? '').toMatch( /#37469: fix: match the recurring every sheet/u, ); - assert.equal(requests.length, 1); + expect(requests.length).toBe(1); }); test('collects local evidence only from mainline squash commits', async () => { @@ -157,7 +149,7 @@ test('collects local evidence only from mainline squash commits', async () => { 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(), [ + 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'], ]); @@ -167,15 +159,15 @@ test('collects local evidence only from mainline squash commits', async () => { } }); -test('falls back to GitHub when local history cannot be read', async (context) => { +test('falls back to GitHub when local history cannot be read', async () => { const directory = mkdtempSync(join(tmpdir(), 'no-repo-')); const originalDirectory = process.cwd(); - const warn = context.mock.method(console, 'warn', () => undefined); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); try { process.chdir(directory); - assert.deepEqual([...(await getLocalPrEvidence(['1']))], []); - assert.equal(warn.mock.callCount(), 1); + expect([...(await getLocalPrEvidence(['1']))]).toStrictEqual([]); + expect(warn).toHaveBeenCalledTimes(1); } finally { process.chdir(originalDirectory); rmSync(directory, { force: true, recursive: true }); @@ -197,15 +189,17 @@ test('does not query GitHub when local mainline evidence exists', async () => { ]), ); - assert.deepEqual(evidence.unavailablePrEvidence, []); - assert.deepEqual(evidence.evidence, [ + 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('limits local evidence history to referenced PR numbers', () => { - assert.deepEqual(getLocalEvidenceLogArguments([]), undefined); - assert.deepEqual(getLocalEvidenceLogArguments(['37469', '37522', '37469']), [ + expect(getLocalEvidenceLogArguments([])).toStrictEqual(undefined); + expect( + getLocalEvidenceLogArguments(['37469', '37522', '37469']), + ).toStrictEqual([ 'log', 'HEAD', '--extended-regexp', @@ -216,10 +210,10 @@ test('limits local evidence history to referenced PR numbers', () => { 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(error.name).toBe('LiteLlmAuthenticationError'); + expect(error.message).toMatch(/HTTP 401/u); + expect(isLiteLlmAuthenticationError(error)).toBe(true); + expect(isLiteLlmAuthenticationError(new Error('HTTP 401'))).toBe(false); }); test('cleans large release sections in reference-preserving chunks', () => { @@ -233,7 +227,7 @@ test('cleans large release sections in reference-preserving chunks', () => { ### Fixed - Improved a flow (#103)`; - assert.deepEqual(splitReleaseSectionIntoChunks(section, '13.51.0', 2), [ + expect(splitReleaseSectionIntoChunks(section, '13.51.0', 2)).toStrictEqual([ { section: `## [13.51.0] @@ -272,14 +266,14 @@ test('cleans large release sections in reference-preserving chunks', () => { ], '13.51.0', ); - assert.doesNotThrow(() => + expect(() => validateReplacement(merged, '13.51.0', ['101', '102', '103']), - ); - assert.doesNotMatch(merged, /\)\n\n- /u); + ).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); +test('warns about and skips an identical repeat of an entry', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); const chunks = splitReleaseSectionIntoChunks( `## [13.51.0] @@ -293,25 +287,23 @@ test('warns about and skips an identical repeat of an entry', (context) => { '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( - () => - splitReleaseSectionIntoChunks( - `## [13.51.0] + expect(() => + splitReleaseSectionIntoChunks( + `## [13.51.0] ### Fixed - Fixed an issue (#101) - Fixed another issue (#101)`, - '13.51.0', - ), - /different entries for PR 101/u, - ); + '13.51.0', + ), + ).toThrow(/different entries for PR 101/u); }); test('extracts exactly one release section', () => { @@ -326,15 +318,14 @@ ${generatedSection} - An earlier fix (#100) `; - assert.equal( - extractReleaseSection(changelog, '13.51.0').section, + expect(extractReleaseSection(changelog, '13.51.0').section).toBe( generatedSection, ); - assert.deepEqual(getPrNumbers(generatedSection), ['101', '102']); + expect(getPrNumbers(generatedSection)).toStrictEqual(['101', '102']); }); test('counts the PR groups auto-changelog counts', () => { - assert.deepEqual( + expect( getPrNumbers(`## [1.0.0] ### Fixed @@ -342,30 +333,26 @@ test('counts the PR groups auto-changelog counts', () => { - Fixed issue #4521 in the send flow (#101, #102). - Reverted "Fixed it (#67)" (#69) - Added a flow with no reference`), - ['101', '102', '67', '69'], - ); + ).toStrictEqual(['101', '102', '67', '69']); // auto-changelog reads the first line, wherever the group sits on it. - assert.deepEqual( + expect( 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)'), [ + ).toStrictEqual(['7']); + expect(getEntryPrNumbers('- Fixed it (#7), (#8)')).toStrictEqual(['7', '8']); + expect(getEntryPrNumbers('- Fixed swap from (#46000) (#101)')).toStrictEqual([ '46000', '101', ]); - assert.deepEqual(getEntryPrNumbers('- (#101)'), ['101']); + expect(getEntryPrNumbers('- (#101)')).toStrictEqual(['101']); }); test('rejects a duplicate release heading', () => { - assert.throws( - () => - extractReleaseSection( - `${generatedSection}\n\n${generatedSection}`, - '13.51.0', - ), - /Expected exactly one release heading/u, - ); + expect(() => + extractReleaseSection( + `${generatedSection}\n\n${generatedSection}`, + '13.51.0', + ), + ).toThrow(/Expected exactly one release heading/u); }); test('replaces only the release section without changing its surrounding whitespace', () => { @@ -389,14 +376,13 @@ ${generatedSection} - Fixed an issue (#102)`; - assert.equal( - replaceReleaseSection(changelog, '13.51.0', 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(() => + expect(() => validateReplacement( `## [13.51.0] @@ -410,125 +396,106 @@ test('accepts a categorized replacement that preserves every PR once', () => { '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( - () => - validateReplacement( - `## [13.51.0] + expect(() => + validateReplacement(generatedSection, '13.51.0', ['101', '102']), + ).toThrow(/Uncategorized/u); + expect(() => + validateReplacement( + `## [13.51.0] ### Fixed - Fixed an issue (#101)`, - '13.51.0', - ['101', '102'], - ), - /references do not match/u, - ); - assert.throws( - () => - validateReplacement( - `## [13.51.0] + '13.51.0', + ['101', '102'], + ), + ).toThrow(/references do not match/u); + expect(() => + validateReplacement( + `## [13.51.0] ### Fixed - Fixed an issue (#101, #102, #103)`, - '13.51.0', - ['101', '102'], - ), - /references do not match/u, - ); - assert.throws( - () => - validateReplacement( - `## [13.51.0] + '13.51.0', + ['101', '102'], + ), + ).toThrow(/references do not match/u); + expect(() => + validateReplacement( + `## [13.51.0] ### Fixed - Fixed an issue (#101) - Fixed it again (#101) - Fixed another issue (#102)`, - '13.51.0', - ['101', '102'], - ), - /duplicate PR references/u, - ); - assert.throws( - () => - validateReplacement( - `## [13.51.0] + '13.51.0', + ['101', '102'], + ), + ).toThrow(/duplicate PR references/u); + expect(() => + validateReplacement( + `## [13.51.0] Here is the cleaned section: ### Fixed - Fixed an issue (#101, #102)`, - '13.51.0', - ['101', '102'], - ), - /unexpected Markdown/u, - ); - assert.throws( - () => - validateReplacement( - `## [13.51.0] + '13.51.0', + ['101', '102'], + ), + ).toThrow(/unexpected Markdown/u); + expect(() => + validateReplacement( + `## [13.51.0] ### Fixed - Fixed an issue (#101)- Fixed another issue (#102)`, - '13.51.0', - ['101', '102'], - ), - /adjacent list items/u, - ); + '13.51.0', + ['101', '102'], + ), + ).toThrow(/adjacent list items/u); }); test('rejects an entry without a trailing PR reference', () => { - assert.throws( - () => - validateReplacement( - `## [13.51.0] + expect(() => + validateReplacement( + `## [13.51.0] ### Fixed - Fixed an issue (#101) - Improved performance across the app`, - '13.51.0', - ['101'], - ), - /must be text followed by its PR reference/u, - ); + '13.51.0', + ['101'], + ), + ).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( - () => - validateReplacement( - entry('- Fixed swap from (#46000) (#101)'), - '13.51.0', - ['101'], - ), - /references do not match/u, - ); + 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', + ]), + ).toThrow(/references do not match/u); }); test('accepts dashes and parentheses inside an entry', () => { - assert.doesNotThrow(() => + expect(() => validateReplacement( `## [13.51.0] @@ -538,7 +505,7 @@ test('accepts dashes and parentheses inside an entry', () => { '13.51.0', ['101'], ), - ); + ).not.toThrow(); }); type FetchResponse = Awaited>; @@ -622,14 +589,13 @@ for (const invalidTimeout of ['soon', '0', '3000000000']) { const originalTimeout = process.env.CHANGELOG_AI_TIMEOUT_MS; restoreEnvironmentVariable('CHANGELOG_AI_TIMEOUT_MS', invalidTimeout); try { - await assert.rejects( - async () => + await expect( + (async () => requestCleanRoomRewrite({ ...rewriteInput, fetchImpl: createFetch([]), - }), - /CHANGELOG_AI_TIMEOUT_MS must be a positive integer/u, - ); + }))(), + ).rejects.toThrow(/CHANGELOG_AI_TIMEOUT_MS must be a positive integer/u); } finally { restoreEnvironmentVariable('CHANGELOG_AI_TIMEOUT_MS', originalTimeout); } @@ -645,29 +611,29 @@ test('sends the pinned model with the bearer credential to chat completions', as 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'); + expect(result).toBe('## [13.51.0]'); + expect(requests.length).toBe(1); + expect(requests[0]?.url ?? '').toMatch(/\/chat\/completions$/u); + expect(requests[0]?.init.method).toBe('POST'); const headers = requests[0]?.init.headers as Record; - assert.equal(headers.Authorization, 'Bearer litellm-key'); + expect(headers.Authorization).toBe('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); + 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); }); test('does not retry a rejected LiteLLM credential', async () => { for (const status of [401, 403]) { const requests: RecordedRequest[] = []; const sleeps: number[] = []; - await assert.rejects( - async () => + await expect( + (async () => requestCleanRoomRewrite({ ...rewriteInput, fetchImpl: createFetch([fakeResponse(status)], requests), @@ -675,13 +641,14 @@ test('does not retry a rejected LiteLLM credential', async () => { sleeps.push(milliseconds); }, timeoutMs: 1_000, - }), + }))(), + ).rejects.toSatisfy( (error: unknown) => isLiteLlmAuthenticationError(error) && error.message.includes(`HTTP ${String(status)}`), ); - assert.equal(requests.length, 1); - assert.deepEqual(sleeps, []); + expect(requests.length).toBe(1); + expect(sleeps).toStrictEqual([]); } }); @@ -700,15 +667,15 @@ test('retries one transient LiteLLM failure and then succeeds', async () => { 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.length).toBe(2); + expect(sleeps).toStrictEqual([1_000]); }); test('stops after the retry budget for persistent LiteLLM failures', async () => { const requests: RecordedRequest[] = []; - await assert.rejects( - async () => + await expect( + (async () => requestCleanRoomRewrite({ ...rewriteInput, fetchImpl: createFetch( @@ -717,27 +684,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.length).toBe(2); }); test('rejects an empty LiteLLM message after the retry budget', async () => { - await assert.rejects( - async () => + await expect( + (async () => 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); +test('requests another response when one fails validation', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); const requests: RecordedRequest[] = []; const valid = `## [13.51.0] @@ -762,17 +727,17 @@ test('requests another response when one fails validation', async (context) => { ['101', '102'], ); - assert.equal(section, valid); - assert.equal(requests.length, 2); + expect(section).toBe(valid); + expect(requests.length).toBe(2); }); -test('gives up after the last response fails validation', async (context) => { - context.mock.method(console, 'warn', () => undefined); +test('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( + (async () => requestValidatedRewrite( { ...rewriteInput, @@ -783,17 +748,16 @@ 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.length).toBe(3); }); test('does not request again after a rejected key', async () => { const requests: RecordedRequest[] = []; - await assert.rejects( - async () => + await expect( + (async () => requestValidatedRewrite( { ...rewriteInput, @@ -801,10 +765,9 @@ 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.length).toBe(1); }); test('aborts a LiteLLM request that exceeds the timeout', async () => { @@ -818,33 +781,29 @@ test('aborts a LiteLLM request that exceeds the timeout', async () => { }); }) as typeof fetch; - await assert.rejects( - async () => + await expect( + (async () => 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.length).toBe(2); + expect(signals.every((signal) => signal?.aborted)).toBe(true); }); test('rejects a proofread when any source PR lacks evidence', () => { - assert.throws( - () => - assertPrEvidenceAvailable([ - { prNumber: '101', error: 'HTTP 404: Not Found' }, - { prNumber: '102', error: 'HTTP 500: Internal Server Error' }, - ]), + expect(() => + assertPrEvidenceAvailable([ + { prNumber: '101', error: 'HTTP 404: Not Found' }, + { prNumber: '102', error: 'HTTP 500: Internal Server Error' }, + ]), + ).toThrow( /PR evidence unavailable: #101 \(HTTP 404: Not Found\), #102 \(HTTP 500: Internal Server Error\)/u, ); - assert.doesNotThrow(() => assertPrEvidenceAvailable([])); + expect(() => assertPrEvidenceAvailable([])).not.toThrow(); }); const execFileAsync = promisify(execFile); @@ -971,10 +930,9 @@ test('writes the validated section and reports success', async () => { - Fixed an issue (#102)`; const result = await runProofreader(respondWithContent(section)); - assert.equal(result.exitCode, 0); - assert.equal(result.report.status, 'succeeded'); - assert.equal( - result.changelog, + expect(result.exitCode).toBe(0); + expect(result.report.status).toBe('succeeded'); + expect(result.changelog).toBe( result.original.replace(generatedSection, section), ); }); @@ -993,11 +951,13 @@ test('leaves the changelog untouched when the model invents an entry', async () - 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); + 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); }); test('leaves the changelog untouched when LiteLLM rejects the key', async () => { @@ -1006,7 +966,7 @@ test('leaves the changelog untouched when LiteLLM rejects the key', async () => response.end('{}'); }); - assert.equal(result.exitCode, 1); - assert.equal(result.report.stage, 'authentication'); - assert.equal(result.changelog, result.original); + 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..ff5fec6a 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,7 +9,7 @@ import { } from 'node:fs'; import { tmpdir } from 'node:os'; import { delimiter, join } from 'node:path'; -import test, { after } from 'node:test'; +import { afterAll, expect, test } from 'vitest'; import { getGitTestEnvironment, git } from './git-test-environment.mts'; @@ -24,7 +23,7 @@ const SCRIPT_PATH = join( const TEMPORARY_DIRECTORY = mkdtempSync( join(tmpdir(), 'previous-release-merge-'), ); -after(() => rmSync(TEMPORARY_DIRECTORY, { force: true, recursive: true })); +afterAll(() => rmSync(TEMPORARY_DIRECTORY, { force: true, recursive: true })); /** * Creates an origin repository with a `main`, an older active release, and a @@ -115,11 +114,10 @@ test('preserves changelog history from an older active release branch', () => { fixture.run(); - assert.equal( - fixture.readChangelog(), + 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', ); - assert.doesNotThrow(() => + expect(() => git( fixture.workDirectory, 'merge-base', @@ -127,7 +125,7 @@ test('preserves changelog history from an older active release branch', () => { 'origin/release/13.54.0', 'HEAD', ), - ); + ).not.toThrow(); }); test('preserves changelog history when the source changelog exceeds the default process buffer', () => { @@ -141,8 +139,7 @@ test('preserves changelog history when the source changelog exceeds the default fixture.run(); - assert.equal( - fixture.readChangelog(), + 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', ); }); @@ -158,7 +155,7 @@ test('preserves destination changelog when the source section is ambiguous', () fixture.run(); - assert.equal(fixture.readChangelog(), destinationChangelog); + expect(fixture.readChangelog()).toBe(destinationChangelog); }); test('preserves destination changelog when it already has the release section', () => { @@ -171,7 +168,7 @@ test('preserves destination changelog when it already has the release section', fixture.run(); - assert.equal(fixture.readChangelog(), destinationChangelog); + expect(fixture.readChangelog()).toBe(destinationChangelog); }); test('moves the Unreleased link to the restored release', () => { diff --git a/.github/scripts/tests/release-section.test.mts b/.github/scripts/tests/release-section.test.mts index e49bcd90..595f2ea2 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 { expect, test } from 'vitest'; import { extractReleaseSection, @@ -16,8 +15,7 @@ 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'; - assert.equal( - extractReleaseSection(changelog, '1.0.0').section, + expect(extractReleaseSection(changelog, '1.0.0').section).toBe( '## [1.0.0]\n\n- Real entry (#1)', ); }); @@ -25,10 +23,9 @@ test('finds the heading line even when its text appears earlier', () => { 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'; - assert.equal( + expect( 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', - ); + ).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', () => { @@ -58,21 +55,18 @@ test('isolates newly generated entries without changing the existing release sec version: '13.51.0', }); - assert.equal( - newEntriesSection, - `## [13.51.0] + expect(newEntriesSection).toBe(`## [13.51.0] ### Added -- Added a new feature (#103)`, - ); - assert.equal( +- Added a new feature (#103)`); + expect( mergeNewReleaseEntries({ existingSection, newEntriesSection: newEntriesSection ?? '', version: '13.51.0', }), - `## [13.51.0] + ).toBe(`## [13.51.0] ### Added @@ -81,8 +75,7 @@ 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', () => { @@ -97,7 +90,7 @@ test('merges new entries into matching categories and inserts missing ones in ca - Fixed an existing issue (#102) with a continuation line`; - assert.equal( + expect( mergeNewReleaseEntries({ existingSection, newEntriesSection: `## [13.51.0] @@ -115,7 +108,7 @@ test('merges new entries into matching categories and inserts missing ones in ca - Hardened a thing (#105)`, version: '13.51.0', }), - `## [13.51.0] + ).toBe(`## [13.51.0] ### Added @@ -133,35 +126,36 @@ 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( + 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( + 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( + expect( normalizeRepositoryPrLinks( [ '- Own link ([#1](https://github.com/MetaMask/metamask-mobile/pull/1))', @@ -172,6 +166,7 @@ test("shortens only this repository's long PR links", () => { ].join('\r\n'), repositoryUrl, ), + ).toBe( [ '- Own link (#1)', '- Two links (#2, #3)', @@ -183,30 +178,28 @@ test("shortens only this repository's long PR links", () => { }); test('treats a long-link entry in the existing section as documented', () => { - assert.equal( + 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', }), - `## [1.0.0]\n\n### Added\n\n- Added b (#2)`, - ); + ).toBe(`## [1.0.0]\n\n### Added\n\n- Added b (#2)`); }); test('matches an existing entry that has trailing whitespace', () => { - assert.equal( + 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', }), - '## [1.0.0]\n\n### Added\n\n- Added b (#2)', - ); + ).toBe('## [1.0.0]\n\n### Added\n\n- Added b (#2)'); }); test('leaves out a PR a reviewer deleted', () => { - assert.equal( + expect( getNewReleaseEntriesSection({ existingSection: '## [1.0.0]\n\n### Added\n\n- Added a (#1)', generatedSection: @@ -214,23 +207,23 @@ test('leaves out a PR a reviewer deleted', () => { version: '1.0.0', deletedPrNumbers: new Set(['2']), }), - '## [1.0.0]\n\n### Added\n\n- Added c (#3)', - ); + ).toBe('## [1.0.0]\n\n### Added\n\n- Added c (#3)'); }); test('keeps the existing line ending when merging new entries', () => { - assert.equal( + 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( + expect( getNewReleaseEntriesSection({ existingSection: `## [13.51.0] @@ -244,8 +237,7 @@ test('finds no new release entries when every generated PR is already documented - Reworded existing issue (#101)`, version: '13.51.0', }), - undefined, - ); + ).toBe(undefined); }); test('judges a generated entry by its last PR reference and demotes earlier mentions', () => { @@ -255,7 +247,7 @@ test('judges a generated entry by its last PR reference and demotes earlier ment - Fixed an existing issue (#101)`; - assert.equal( + expect( getNewReleaseEntriesSection({ existingSection, generatedSection: `## [13.51.0] @@ -266,14 +258,13 @@ test('judges a generated entry by its last PR reference and demotes earlier ment see also #101`, version: '13.51.0', }), - `## [13.51.0] + ).toBe(`## [13.51.0] ### Fixed - Fixed a regression from PR 101 and PR 100 (#102) - see also PR 101`, - ); - assert.equal( + see also PR 101`); + expect( getNewReleaseEntriesSection({ existingSection, generatedSection: `## [13.51.0] @@ -283,8 +274,7 @@ test('judges a generated entry by its last PR reference and demotes earlier ment - Reworded a documented PR that mentions (#102) (#101)`, version: '13.51.0', }), - undefined, - ); + ).toBe(undefined); }); test('keeps a multi-PR group intact and demotes mentions before it', () => { @@ -300,7 +290,7 @@ test('keeps a multi-PR group intact and demotes mentions before it', () => { ${entry}`; - assert.equal( + expect( getNewReleaseEntriesSection({ existingSection, generatedSection: generatedSection( @@ -308,9 +298,8 @@ ${entry}`; ), version: '13.51.0', }), - generatedSection('- Fixed a regression from PR 100 (#102, #103)'), - ); - assert.equal( + ).toBe(generatedSection('- Fixed a regression from PR 100 (#102, #103)')); + expect( getNewReleaseEntriesSection({ existingSection, generatedSection: generatedSection( @@ -318,34 +307,31 @@ ${entry}`; ), version: '13.51.0', }), - generatedSection('- Fixed legacy groups (#102), (#103)'), - ); + ).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)`; - assert.equal( + expect( getNewReleaseEntriesSection({ existingSection, generatedSection: `## [13.51.0]\n\n### Fixed\n\n- Fixed an issue (#101, #102)`, version: '13.51.0', }), - undefined, - ); - assert.equal( + ).toBe(undefined); + 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']), }), - undefined, - ); + ).toBe(undefined); }); test('preserves the reviewed release section above historical predecessor history', () => { - assert.equal( + expect( mergeCurrentReleaseSection({ changelog: `# Changelog @@ -362,7 +348,7 @@ test('preserves the reviewed release section above historical predecessor histor - Added a current release feature (#101)`, version: '13.51.0', }), - `# Changelog + ).toBe(`# Changelog ## [13.51.0] @@ -375,12 +361,11 @@ 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( + expect( mergeCurrentReleaseSection({ changelog: `# Changelog @@ -401,7 +386,7 @@ All notable changes to this project will be documented in this file. - Added a current release feature (#101)`, version: '13.51.0', }), - `# Changelog + ).toBe(`# Changelog All notable changes to this project will be documented in this file. @@ -418,8 +403,7 @@ All notable changes to this project will be documented in this file. ### Fixed - Fixed an earlier issue (#100) -`, - ); +`); }); const stableShapedChangelog = `# Changelog @@ -461,19 +445,21 @@ test('merges into a stable-shaped changelog without disturbing history or link r version: '13.51.0', }); - assert.equal( - merged, + expect(merged).toBe( stableShapedChangelog.replace( '## [13.50.0]', `${reviewedSection}\n\n## [13.50.0]`, ), ); - assert.equal( - extractReleaseSection(merged, '13.51.0').section, + expect(extractReleaseSection(merged, '13.51.0').section).toBe( reviewedSection, ); - assert.ok(merged.indexOf('## [Unreleased]') < merged.indexOf('## [13.51.0]')); - assert.ok(merged.indexOf('## [13.51.0]') < merged.indexOf('## [13.50.0]')); + expect( + merged.indexOf('## [Unreleased]') < merged.indexOf('## [13.51.0]'), + ).toBeTruthy(); + expect( + merged.indexOf('## [13.51.0]') < merged.indexOf('## [13.50.0]'), + ).toBeTruthy(); }); test('keeps CRLF line endings when merging into a CRLF changelog', () => { @@ -483,8 +469,8 @@ test('keeps CRLF line endings when merging into a CRLF changelog', () => { version: '13.51.0', }); - assert.equal(merged.replaceAll('\r\n', '').includes('\n'), false); - assert.ok(merged.includes('## [13.51.0]\r\n\r\n### Added')); + expect(merged.replaceAll('\r\n', '').includes('\n')).toBe(false); + expect(merged.includes('## [13.51.0]\r\n\r\n### Added')).toBeTruthy(); }); test('replaces an existing current heading instead of duplicating it', () => { @@ -499,9 +485,9 @@ test('replaces an existing current heading instead of duplicating it', () => { version: '13.51.0', }); - assert.equal(twice.match(/^## \[13\.51\.0\]$/gmu)?.length, 1); - assert.match(twice, /\(#102\)/u); - assert.doesNotMatch(twice, /\(#101\)/u); + expect(twice.match(/^## \[13\.51\.0\]$/gmu)?.length).toBe(1); + expect(twice).toMatch(/\(#102\)/u); + expect(twice).not.toMatch(/\(#101\)/u); }); test('appends the reviewed section when the changelog has no releases yet', () => { @@ -511,10 +497,7 @@ test('appends the reviewed section when the changelog has no releases yet', () = version: '13.51.0', }); - assert.equal( - merged, - `# Changelog\n\n## [Unreleased]\n\n${reviewedSection}\n`, - ); + expect(merged).toBe(`# Changelog\n\n## [Unreleased]\n\n${reviewedSection}\n`); }); test('does not double carriage returns when inserting a CRLF section into a CRLF changelog', () => { @@ -525,9 +508,8 @@ test('does not double carriage returns when inserting a CRLF section into a CRLF version: '13.51.0', }); - assert.equal(merged.includes('\r\r'), false); - assert.equal( - merged, + expect(merged.includes('\r\r')).toBe(false); + 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', ); }); @@ -550,39 +532,34 @@ test('keeps a reviewer entry without a PR reference out of the new entries', () '- Added a thing (#1)\n- Added another thing (#2)', ); - assert.equal( + expect( getNewReleaseEntriesSection({ existingSection, generatedSection, version: '1.0.0', }), - '## [1.0.0]\n\n### Added\n\n- Added another thing (#2)', - ); + ).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( - () => - 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, - ); + 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', + }), + ).toThrow(/lacks a PR reference/u); }); test('rejects a changelog without the Changelog heading', () => { - assert.throws( - () => - mergeCurrentReleaseSection({ - changelog: '## [13.50.0]\n', - currentReleaseSection: reviewedSection, - version: '13.51.0', - }), - /must begin with a Changelog heading/u, - ); + expect(() => + mergeCurrentReleaseSection({ + changelog: '## [13.50.0]\n', + currentReleaseSection: reviewedSection, + version: '13.51.0', + }), + ).toThrow(/must begin with a Changelog heading/u); }); test('ends the oldest release section before the link references', () => { @@ -602,16 +579,16 @@ test('ends the oldest release section before the link references', () => { '', ].join('\n'); - assert.equal( - extractReleaseSection(changelog, '13.51.0').section, + expect(extractReleaseSection(changelog, '13.51.0').section).toBe( '## [13.51.0]\n\n### Fixed\n\n- Fixed an issue (#101)', ); - assert.equal( + 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)'), @@ -633,14 +610,12 @@ test('removes the entries owning the given PRs and drops emptied categories', () '- Fixed two (#3)', ].join('\n'); - assert.equal( + expect( removeReleaseEntries({ section, prNumbers: new Set(['1', '2']) }), - ['## [2.0.0]', '', '### Fixed', '', '- Fixed two (#3)'].join('\n'), - ); - assert.equal( + ).toBe(['## [2.0.0]', '', '### Fixed', '', '- Fixed two (#3)'].join('\n')); + expect( removeReleaseEntries({ section, prNumbers: new Set(['1', '2', '3']) }), - '## [2.0.0]', - ); + ).toBe('## [2.0.0]'); }); test('keeps an entry that owns a PR outside the given PRs', () => { @@ -653,12 +628,12 @@ test('keeps an entry that owns a PR outside the given PRs', () => { '- Fixed together (#3, #4)', ].join('\n'); - assert.equal( + expect( removeReleaseEntries({ section, prNumbers: new Set(['1', '3']) }), - section, - ); - assert.equal( + ).toBe(section); + expect( removeReleaseEntries({ section, prNumbers: new Set(['3', '4']) }), + ).toBe( ['## [2.0.0]', '', '### Fixed', '', '- Fixed from (#1) (#2)'].join('\n'), ); }); @@ -666,8 +641,7 @@ test('keeps an entry that owns a PR outside the given PRs', () => { test('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']) }), + 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..a9d201a7 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 { expect, test } from 'vitest'; import { compareSemver, @@ -8,12 +7,12 @@ import { } from '../release-version-utils.mts'; test('parses supported native and OTA release branches', () => { - assert.deepEqual(parseReleaseBranch('release/13.50.3'), { + expect(parseReleaseBranch('release/13.50.3')).toStrictEqual({ version: '13.50.3', kind: 'native', name: 'release/13.50.3', }); - assert.deepEqual(parseReleaseBranch('release/13.50.3-ota'), { + expect(parseReleaseBranch('release/13.50.3-ota')).toStrictEqual({ version: '13.50.3', kind: 'ota', name: 'release/13.50.3-ota', @@ -21,18 +20,18 @@ test('parses supported native and OTA release branches', () => { }); test('rejects unsupported release branch names', () => { - assert.equal(parseReleaseBranch('release/13.50.3-fallback'), undefined); - assert.equal(parseReleaseBranch('release/13.50.3.1'), undefined); + expect(parseReleaseBranch('release/13.50.3-fallback')).toBe(undefined); + expect(parseReleaseBranch('release/13.50.3.1')).toBe(undefined); }); 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); + 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( + expect( selectHighestLowerVersion('13.51.0', [ '13.49.0', '13.50.0', @@ -40,14 +39,11 @@ test('selects the highest strict predecessor', () => { '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', ); - assert.equal( - selectHighestLowerVersion('13.50.4', ['13.50.2', '13.50.3']), - '13.50.3', - ); - assert.equal( + expect( selectHighestLowerVersion('13.51.0', ['13.51.0', '13.51.1', '14.0.0']), - undefined, - ); + ).toBe(undefined); }); diff --git a/.github/scripts/tests/retry.test.mts b/.github/scripts/tests/retry.test.mts index 75077519..65db6b0c 100644 --- a/.github/scripts/tests/retry.test.mts +++ b/.github/scripts/tests/retry.test.mts @@ -1,5 +1,4 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; +import { expect, test } from 'vitest'; import { retry } from '../shared/retry.mts'; @@ -22,32 +21,31 @@ test('retries an operation with increasing delays', async () => { }, ); - assert.equal(result, 'recovered'); - assert.equal(attempts, 3); - assert.deepEqual(delays, [100, 200]); + expect(result).toBe('recovered'); + expect(attempts).toBe(3); + expect(delays).toStrictEqual([100, 200]); }); test('does not retry a rejected error category', async () => { let attempts = 0; - await assert.rejects( - async () => + await expect( + (async () => retry( async () => { attempts += 1; throw new Error('Permanent failure'); }, { shouldRetry: () => false }, - ), - /Permanent failure/u, - ); + ))(), + ).rejects.toThrow(/Permanent failure/u); - assert.equal(attempts, 1); + expect(attempts).toBe(1); }); test('reports retry details before delaying', async () => { const retries: { attempt: number; delayMilliseconds: number }[] = []; - await assert.rejects( - async () => + await expect( + (async () => retry( async () => { throw new Error('Transient failure'); @@ -59,9 +57,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..8f107535 100644 --- a/.github/scripts/tests/update-release-changelog-baseline.test.mts +++ b/.github/scripts/tests/update-release-changelog-baseline.test.mts @@ -1,5 +1,4 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; +import { expect, test } from 'vitest'; import { removeNewerReleases, @@ -47,38 +46,36 @@ function selectBaseline(dependencies: ChangelogBaselineDependencies) { } test('uses the target release changelog after the changelog PR is merged', () => { - assert.deepEqual( + expect( selectBaseline( createDependencies({ headings: new Set(['origin/release/13.51.0:13.51.0']), }), ), - { - kind: 'target', - ref: 'origin/release/13.51.0', - version: '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( + expect( selectBaseline( createDependencies({ headings: new Set(['origin/stable:13.50.0']), stableVersions: ['13.50.0'], }), ), - { - kind: 'stable', - ref: 'origin/stable', - version: '13.50.0', - }, - ); + ).toStrictEqual({ + kind: 'stable', + ref: 'origin/stable', + version: '13.50.0', + }); }); test('prefers stable for the selected predecessor version', () => { - assert.deepEqual( + expect( selectBaseline( createDependencies({ headings: new Set(['origin/stable:13.50.3']), @@ -92,12 +89,11 @@ test('prefers stable for the selected predecessor version', () => { ], }), ), - { kind: 'stable', ref: 'origin/stable', version: '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( + expect( selectBaseline( createDependencies({ headings: new Set([ @@ -119,30 +115,29 @@ test('uses the highest predecessor release branch when stable is behind', () => ], }), ), - { - kind: 'release', - ref: 'origin/release/13.50.3', - version: '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( - () => - selectBaseline( - createDependencies({ - headings: new Set(['origin/stable:13.50.2']), - stableVersions: ['13.50.2'], - releaseBranches: [ - { - version: '13.50.3', - kind: 'native', - name: 'release/13.50.3', - }, - ], - }), - ), + expect(() => + selectBaseline( + createDependencies({ + headings: new Set(['origin/stable:13.50.2']), + stableVersions: ['13.50.2'], + releaseBranches: [ + { + version: '13.50.3', + kind: 'native', + name: 'release/13.50.3', + }, + ], + }), + ), + ).toThrow( /origin\/release\/13\.50\.3 has no ## \[13\.50\.3\] changelog section/u, ); }); @@ -171,8 +166,7 @@ const stableChangelog = [ ].join('\n'); test('drops releases newer than an older-line hotfix with their link references', () => { - assert.equal( - removeNewerReleases(stableChangelog, '13.50.4'), + expect(removeNewerReleases(stableChangelog, '13.50.4')).toBe( [ '# Changelog', '', @@ -192,46 +186,37 @@ test('drops releases newer than an older-line hotfix with their link references' }); 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); + 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'); - 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, + expect(removeNewerReleases(crlf, '13.50.4').includes('\r\r')).toBe(false); + expect(removeNewerReleases(crlf, '13.50.4').includes('13.51.0]')).toBe(false); + expect(removeNewerReleases(crlf, '13.50.4').split('\r\n').length).toBe( removeNewerReleases(crlf, '13.50.4').split('\n').length, ); }); test('rejects ambiguous native and OTA predecessor branches', () => { - assert.throws( - () => - selectBaseline( - createDependencies({ - releaseBranches: [ - { - version: '13.50.3', - kind: 'native', - name: 'release/13.50.3', - }, - { - version: '13.50.3', - kind: 'ota', - name: 'release/13.50.3-ota', - }, - ], - }), - ), - /Expected exactly one release branch/u, - ); + expect(() => + selectBaseline( + createDependencies({ + releaseBranches: [ + { + version: '13.50.3', + kind: 'native', + name: 'release/13.50.3', + }, + { + version: '13.50.3', + kind: 'ota', + name: 'release/13.50.3-ota', + }, + ], + }), + ), + ).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..0c4a0732 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(); }); 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, - ); + ).toBe(undefined); }); 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, - ); + ).toBe(undefined); }); 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, - ); + ).toBe(undefined); }); 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,38 @@ describe('release changelog Git behavior', () => { 'Changelog-Generated-Through: not-a-sha', ); - assert.equal( + expect( getChangelogBranchCommits(CHANGELOG_BRANCH, TARGET)[0] ?.generatedThrough, - undefined, - ); + ).toBe(undefined); }); }); describe('assertRemoteRefUnchanged', () => { it('accepts an unchanged ref and rejects a moved one', () => { const sha = getRemoteBranchSha(TARGET); - assert.ok(sha); - assert.doesNotThrow(() => + if (sha === undefined) { + throw new Error('Expected the target release branch to exist'); + } + expect(() => assertRemoteRefUnchanged({ ref: `origin/${TARGET}`, expectedSha: sha, 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, + 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..ee5651e0 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 { expect, test, vi } from 'vitest'; import { assertReleaseSectionHasEntries, @@ -40,31 +39,29 @@ test('records the failure stage in the proofread report', () => { try { const reportPath = join(directory, 'nested', 'report.json'); writeFailedProofreadingReport(reportPath, 'no key', 'authentication'); - assert.deepEqual(JSON.parse(readFileSync(reportPath, 'utf8')), { + expect(JSON.parse(readFileSync(reportPath, 'utf8'))).toStrictEqual({ status: 'failed', stage: 'authentication', error: 'no key', }); writeFailedProofreadingReport(reportPath, 'boom'); - assert.equal( + expect( (JSON.parse(readFileSync(reportPath, 'utf8')) as { stage: string }).stage, - 'execution', - ); + ).toBe('execution'); } finally { rmSync(directory, { force: true, recursive: true }); } }); test('collects historical skipped PRs from auto-changelog diagnostics', () => { - assert.deepEqual( + 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); @@ -72,18 +69,15 @@ const COMMIT_B = 'b'.repeat(40); const COMMIT_C = 'c'.repeat(40); test('collects the accepted commits of each canonical PR', () => { - assert.deepEqual( - [ - ...getAcceptedPrCommits(`[auto-changelog] commit=${COMMIT_A} accepted source-pr=1 canonical-pr=1 cherry-pick=false + 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`), - ], - [ - ['1', [COMMIT_A, COMMIT_B]], - ['2', [COMMIT_C]], - ], - ); + ]).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', () => { @@ -98,24 +92,22 @@ test('treats a PR generated before the last tip but missing from the section as listReachableCommits: () => [COMMIT_A, COMMIT_B], }; - assert.deepEqual( + expect( getDeletedPrNumbers({ ...options, existingPrNumbers: new Set(['1']), }), - new Set(['2']), - ); - assert.deepEqual( + ).toStrictEqual(new Set(['2'])); + expect( getDeletedPrNumbers({ ...options, existingPrNumbers: new Set(['1', '2']), }), - new Set(), - ); + ).toStrictEqual(new Set()); }); test('treats nothing as deleted when the last tip cannot be read', () => { - assert.deepEqual( + expect( getDeletedPrNumbers({ acceptedCommitsByPr: new Map([['1', [COMMIT_A]]]), generatedThrough: 'd'.repeat(40), @@ -124,8 +116,7 @@ test('treats nothing as deleted when the last tip cannot be read', () => { throw new Error('unknown revision'); }, }), - new Set(), - ); + ).toStrictEqual(new Set()); }); test('finds the releases that already list a PR, oldest first, excluding the target', () => { @@ -152,14 +143,12 @@ test('finds the releases that already list a PR, oldest first, excluding the tar - Unrelated (#1) `; - assert.deepEqual( + expect( findReleaseVersionsContainingPrs(changelog, ['35695', '35716'], '8.10.3'), - ['8.9.0', '8.11.0'], - ); - assert.deepEqual( + ).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', () => { @@ -175,122 +164,108 @@ test('finds versions that document a PR with this repository long link', () => { `; const repositoryUrl = 'https://github.com/MetaMask/metamask-mobile'; - assert.deepEqual( + expect( findReleaseVersionsContainingPrs( changelog, ['35695'], '8.10.3', repositoryUrl, ), - ['8.9.0'], - ); - assert.deepEqual( + ).toStrictEqual(['8.9.0']); + expect( findReleaseVersionsContainingPrs(changelog, ['35695'], '8.10.3'), - [], - ); + ).toStrictEqual([]); }); test('detects a release section without entries', () => { - assert.equal( + expect( isReleaseSectionEmpty( '# Changelog\n\n## [8.10.3]\n\n## [8.10.2]\n', '8.10.3', ), - true, - ); - assert.equal( + ).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', ), - false, - ); + ).toBe(false); }); test('asks for a manual edit when an OTA release has no new PRs', () => { - assert.deepEqual( + expect( getChangelogPrPresentation({ version: '8.10.3', changelogBranch: 'release-changelog/8.10.3', proofreadingStatus: 'no-new-prs', presentInVersions: ['8.11.0', '8.12.0'], }), - { - 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( + ).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.', + }); + expect( 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, - ); + ).toMatch(/There are no brand new PRs in 8\.10\.3\. Please decide/u); }); test('parses dry-run without changing positional arguments', () => { - assert.deepEqual( + expect( parseUpdateChangelogArguments([ '--dry-run', 'release/13.51.0', 'extension', 'https://github.com/MetaMask/metamask-extension', ]), - { - dryRun: true, - positionalArguments: [ - '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( + expect( getAutoChangelogCli({ AUTO_CHANGELOG_CLI: '/tmp/auto-changelog.mjs' }), - '/tmp/auto-changelog.mjs', - ); - assert.throws( - () => getAutoChangelogCli({}), + ).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'), [ + expect(getChangelogValidationArguments('failed', '13.51.0')).toStrictEqual([ 'validate', '--prettier', '--currentVersion', '13.51.0', - '--rc', ]); + 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( + expect( getChangelogPushArguments({ changelogBranch: 'release-changelog/13.51.0', expectedRemoteSha: undefined, }), - [ - 'push', - '--force-with-lease=refs/heads/release-changelog/13.51.0:', - '--set-upstream', - 'origin', - 'HEAD:refs/heads/release-changelog/13.51.0', - ], - ); + ).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 = [ @@ -344,7 +319,7 @@ test('marks an unproofread changelog PR when AI proofreading fails', () => { }), ); - assert.deepEqual(presentation, { + 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.', @@ -366,8 +341,7 @@ test('links the proofreading report artifact when run in GitHub Actions', () => }), ); - assert.match( - body, + expect(body).toMatch( /\[View the proofreading report artifact\.\]\(https:\/\/github\.com\/MetaMask\/metamask-extension\/actions\/runs\/123#artifacts\)/u, ); }); @@ -377,88 +351,82 @@ test('preserves authentication failures for the unproofread PR warning', () => { status: 'failed' as const, stage: 'authentication', }; - assert.deepEqual( + expect( getChangelogPrPresentation({ version: '13.51.0', changelogBranch: 'release-changelog/13.51.0', proofreadingStatus: authenticationFailure.status, proofreadingStage: authenticationFailure.stage, }).title, + ).toStrictEqual( 'release: release-changelog/13.51.0 (AI automation failed, not proofread)', ); }); test('uses the plain presentation after a successful proofread', () => { - assert.deepEqual( + expect( getChangelogPrPresentation({ version: '13.51.0', changelogBranch: 'release-changelog/13.51.0', proofreadingStatus: 'succeeded', }), - { - title: 'release: release-changelog/13.51.0', - body: 'This PR updates the change log for 13.51.0.', - }, - ); + ).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( - () => - 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(() => + expect(() => + assertReleaseSectionHasEntries( + '# Changelog\n\n## [8.10.3]\n\n## [8.10.2]\n', + '8.10.3', + ), + ).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('leaves an existing changelog PR alone when nothing changed', () => { - assert.equal( + expect( shouldKeepChangelogPrPresentation({ existingTitle: 'release: release-changelog/13.51.0', proofreadingStatus: 'unchanged', }), - true, - ); + ).toBe(true); }); 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)'; - assert.equal( + expect( shouldKeepChangelogPrPresentation({ existingTitle, proofreadingStatus: 'succeeded', }), - true, - ); - assert.equal( + ).toBe(true); + expect( shouldKeepChangelogPrPresentation({ existingTitle, proofreadingStatus: 'failed', }), - false, - ); + ).toBe(false); }); test('rewrites the AI failure marker when the whole section was proofread again', () => { - assert.equal( + expect( shouldKeepChangelogPrPresentation({ existingTitle: 'release: release-changelog/13.51.0 (AI automation failed, not proofread)', proofreadingStatus: 'succeeded', replacesWholeSection: true, }), - false, - ); + ).toBe(false); }); test("regenerates only an unproofread PR whose sole commit is the updater's own", () => { @@ -476,8 +444,8 @@ test("regenerates only an unproofread PR whose sole commit is the updater's own" ], }; - assert.equal(isUntouchedUnproofreadChangelogPr(options), true); - assert.equal( + expect(isUntouchedUnproofreadChangelogPr(options)).toBe(true); + expect( isUntouchedUnproofreadChangelogPr({ ...options, commits: [ @@ -487,16 +455,14 @@ test("regenerates only an unproofread PR whose sole commit is the updater's own" }, ], }), - false, - ); - assert.equal( + ).toBe(false); + expect( isUntouchedUnproofreadChangelogPr({ ...options, title: 'release: release-changelog/13.51.0', }), - false, - ); - assert.equal( + ).toBe(false); + expect( isUntouchedUnproofreadChangelogPr({ ...options, commits: [ @@ -504,9 +470,8 @@ test("regenerates only an unproofread PR whose sole commit is the updater's own" { authorEmail: 'person@example.com', subject: 'fix wording' }, ], }), - false, - ); - assert.equal( + ).toBe(false); + expect( isUntouchedUnproofreadChangelogPr({ ...options, commits: [ @@ -516,10 +481,8 @@ test("regenerates only an unproofread PR whose sole commit is the updater's own" }, ], }), - false, - ); - assert.equal( - isUntouchedUnproofreadChangelogPr({ ...options, commits: [] }), + ).toBe(false); + expect(isUntouchedUnproofreadChangelogPr({ ...options, commits: [] })).toBe( false, ); }); @@ -535,8 +498,8 @@ test("recovers a branch only when every commit is the updater's own", () => { commits: [own], }; - assert.equal(hasOnlyUpdaterCommits(options), true); - assert.equal( + expect(hasOnlyUpdaterCommits(options)).toBe(true); + expect( hasOnlyUpdaterCommits({ ...options, commits: [ @@ -544,47 +507,41 @@ test("recovers a branch only when every commit is the updater's own", () => { { authorEmail: 'person@example.com', subject: 'fix wording' }, ], }), - false, - ); + ).toBe(false); }); test('rewrites the PR presentation after a normal successful run', () => { - assert.equal( + expect( shouldKeepChangelogPrPresentation({ existingTitle: 'release: release-changelog/13.51.0', proofreadingStatus: 'succeeded', }), - false, - ); + ).toBe(false); }); test('rejects generated sections with missing or duplicate PR references', () => { - assert.throws( - () => - validateGeneratedReleaseSection( - `## [13.51.0] + expect(() => + validateGeneratedReleaseSection( + `## [13.51.0] ### Fixed - Fixed an issue`, - '13.51.0', - ), - /without a PR reference/u, - ); - assert.throws( - () => - validateGeneratedReleaseSection( - `## [13.51.0] + '13.51.0', + ), + ).toThrow(/without a PR reference/u); + expect(() => + validateGeneratedReleaseSection( + `## [13.51.0] ### Fixed - Fixed an issue (#101) - Fixed it again (#101)`, - '13.51.0', - ), - /duplicate PR references/u, - ); - assert.doesNotThrow(() => + '13.51.0', + ), + ).toThrow(/duplicate PR references/u); + expect(() => validateGeneratedReleaseSection( `## [13.51.0] @@ -595,18 +552,15 @@ test('rejects generated sections with missing or duplicate PR references', () => '13.51.0', true, ), - ); + ).not.toThrow(); }); test('collects the canonical PR of each accepted cherry-pick commit', () => { - assert.deepEqual( - [ - ...getCherryPickedPrsByCommit(`[auto-changelog] commit=${COMMIT_A} accepted source-pr=1 canonical-pr=1 cherry-pick=false + 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', () => { @@ -615,34 +569,29 @@ test('finds the PRs cherry-picked onto the baseline branch', () => { [COMMIT_B, '2'], ]); - assert.deepEqual( + expect( 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( + ).toStrictEqual(new Set(['1'])); + expect( getPrsCherryPickedOntoBaseline({ cherryPickedPrsByCommit, baselineRef: 'origin/stable', isAncestor: () => false, }), - new Set(), - ); + ).toStrictEqual(new Set()); }); test('maps each canonical PR to its cherry-pick PR numbers', () => { - assert.deepEqual( - [ - ...getCherryPickAliasesByPr(`[auto-changelog] commit=${COMMIT_A} accepted source-pr=1 canonical-pr=1 cherry-pick=false + 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']]], - ); + ]).toStrictEqual([['1', ['7', '8']]]); }); test('reports PRs that no other section lists under any of their numbers', () => { @@ -662,7 +611,7 @@ test('reports PRs that no other section lists under any of their numbers', () => '', ].join('\n'); - assert.deepEqual( + expect( findPrsMissingFromChangelog({ changelog, prNumbers: ['1', '2', '3', '4'], @@ -670,8 +619,7 @@ test('reports PRs that no other section lists under any of their numbers', () => version: '2.0.0', repositoryUrl: 'https://github.com/MetaMask/example', }), - ['1', '4'], - ); + ).toStrictEqual(['1', '4']); }); test('counts a pending section of the earlier release as listing a PR', () => { @@ -683,7 +631,7 @@ test('counts a pending section of the earlier release as listing a PR', () => { '- Fixed three by its cherry-pick (#31)', ].join('\n'); - assert.deepEqual( + expect( findPrsMissingFromChangelog({ changelog, pendingSections: [pendingSection], @@ -692,8 +640,7 @@ test('counts a pending section of the earlier release as listing a PR', () => { version: '2.0.0', repositoryUrl: 'https://github.com/MetaMask/example', }), - ['4'], - ); + ).toStrictEqual(['4']); }); const RELEASE_BASELINE = { @@ -705,7 +652,7 @@ const RELEASE_BASELINE = { test('reads the earlier release section from its open changelog PR', () => { const lookups: string[][] = []; - assert.equal( + expect( getOpenBaselineChangelogSection({ baseline: RELEASE_BASELINE, determineBranch: (version) => `release-changelog/${version}`, @@ -716,9 +663,8 @@ test('reads the earlier release section from its open changelog PR', () => { }, 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']]); + ).toBe('release-changelog/1.0.0 1.0.0'); + expect(lookups).toStrictEqual([['release-changelog/1.0.0', 'release/1.0.0']]); }); test('ignores the earlier release changelog when no PR is open', () => { @@ -730,42 +676,39 @@ test('ignores the earlier release changelog when no PR is open', () => { }, }; - assert.equal( + expect( getOpenBaselineChangelogSection({ ...options, getSha: () => undefined, getOpenPrNumber: () => '9', }), - undefined, - ); - assert.equal( + ).toBe(undefined); + expect( getOpenBaselineChangelogSection({ ...options, getSha: () => 'abc', getOpenPrNumber: () => undefined, }), - undefined, - ); + ).toBe(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', getOpenPrNumber: () => '9', readSection: () => 'section', }), - undefined, - ); + ).toBe(undefined); } }); -test('carries on when the open changelog branch lacks the section', (context) => { - context.mock.method(console, 'warn', () => undefined); +test('carries on when the open changelog branch lacks the section', () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); - assert.equal( + expect( getOpenBaselineChangelogSection({ baseline: RELEASE_BASELINE, determineBranch: (version) => `release-changelog/${version}`, @@ -775,8 +718,7 @@ test('carries on when the open changelog branch lacks the section', (context) => throw new Error('Expected exactly one release heading for 1.0.0'); }, }), - undefined, - ); + ).toBe(undefined); }); const RELEASE_BRANCH_CHANGELOG = [ @@ -812,13 +754,12 @@ test('finds released entries a stale baseline restore drops', () => { '', ].join('\n'); - assert.deepEqual( + expect( findEntriesDroppedByRestore({ restoredChangelog, releaseChangelog: RELEASE_BRANCH_CHANGELOG, }), - [{ version: '2.0.0', entryCount: 1, prNumbers: ['2'] }], - ); + ).toStrictEqual([{ version: '2.0.0', entryCount: 1, prNumbers: ['2'] }]); }); test('counts an entry as dropped when only another version lists it', () => { @@ -835,27 +776,25 @@ test('counts an entry as dropped when only another version lists it', () => { '', ].join('\n'); - assert.deepEqual( + expect( findEntriesDroppedByRestore({ restoredChangelog, releaseChangelog: RELEASE_BRANCH_CHANGELOG, }), - [{ version: '1.0.0', entryCount: 1, prNumbers: ['3'] }], - ); + ).toStrictEqual([{ version: '1.0.0', entryCount: 1, prNumbers: ['3'] }]); }); test('reports nothing when the restore keeps every released entry', () => { - assert.deepEqual( + expect( findEntriesDroppedByRestore({ restoredChangelog: `${RELEASE_BRANCH_CHANGELOG}\n## [3.0.0]\n\n- New (#5)\n`, releaseChangelog: RELEASE_BRANCH_CHANGELOG, }), - [], - ); + ).toStrictEqual([]); }); test('words the warning for entries the restore dropped', () => { - assert.equal( + expect( getDroppedEntriesWarning('8.20.0', { baselineVersion: '8.19.0', releaseBranch: 'release/8.20.0', @@ -868,27 +807,26 @@ test('words the warning for entries the restore dropped', () => { { 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.', ); - assert.match( + expect( 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, - ); + ).toMatch(/dropped 1 entry that release\/8\.20\.0 lists/u); }); test('does not count a reworded entry as dropped', () => { const releaseChangelog = '## [1.0.0]\n\n- Fixed a crash (#1, #2)\n'; - assert.deepEqual( + expect( findEntriesDroppedByRestore({ restoredChangelog: '## [1.0.0]\n\n- Fixed the crash on launch (#2)\n', releaseChangelog, }), - [], - ); + ).toStrictEqual([]); }); test('reads long PR links when comparing dropped entries', () => { @@ -896,32 +834,29 @@ test('reads long PR links when comparing dropped entries', () => { 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( + expect( 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'] }], - ); + ).toStrictEqual([{ version: '1.0.0', entryCount: 1, prNumbers: ['2'] }]); }); test('compares an entry without a PR number by its text', () => { const releaseChangelog = '## [1.0.0]\n\n- Manual note\n'; - assert.deepEqual( + expect( findEntriesDroppedByRestore({ restoredChangelog: '## [1.0.0]\n\n- Other note\n', releaseChangelog, }), - [{ version: '1.0.0', entryCount: 1, prNumbers: [] }], - ); - assert.deepEqual( + ).toStrictEqual([{ version: '1.0.0', entryCount: 1, prNumbers: [] }]); + expect( findEntriesDroppedByRestore({ restoredChangelog: releaseChangelog, releaseChangelog, }), - [], - ); + ).toStrictEqual([]); }); test('lists up to three dropped PRs before summarizing the rest', () => { @@ -933,9 +868,8 @@ test('lists up to three dropped PRs before summarizing the rest', () => { { 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']), + 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, ); }); @@ -952,34 +886,34 @@ test('adds the dropped entries warning to the PR body', () => { }, }); - assert.match(body, /^This PR updates the change log for 8\.20\.0\./u); - assert.match( - body, + 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, ); }); test('words the warning for PRs the earlier changelog lacks', () => { - assert.equal( + 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.', ); - assert.equal( + 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('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' }), + expect(refreshGeneratedWarnings({ existingBody, version: '8.20.0' })).toBe( 'This PR updates the change log for 8.20.0.', ); }); @@ -991,12 +925,13 @@ test('replaces a stale warning and keeps unrelated quotes', () => { baselineVersion: '8.19.0', prNumbers: ['2'], }; - assert.equal( + expect( refreshGeneratedWarnings({ existingBody, version: '8.20.0', unlistedCherryPicks, }), + ).toBe( `Intro.\n\n${kept}\n\n${getUnlistedCherryPicksWarning('8.20.0', unlistedCherryPicks)}`, ); }); @@ -1007,33 +942,31 @@ test('leaves a body whose warnings still hold', () => { prNumbers: ['1'], }; const existingBody = `Intro.\n\n${getUnlistedCherryPicksWarning('8.20.0', unlistedCherryPicks)}`; - assert.equal( + expect( refreshGeneratedWarnings({ existingBody, version: '8.20.0', unlistedCherryPicks, }), - undefined, - ); + ).toBe(undefined); }); const RUN_PATH = '.github/workflows/update-release-changelog.yml'; test('finds the run the moving push triggered', () => { - assert.equal( + expect( hasWorkflowRunForSha({ sha: 'abc', workflowPath: RUN_PATH, listRunPaths: () => ['.github/workflows/other.yml', RUN_PATH], }), - true, - ); + ).toBe(true); }); test('waits for the run of the moving push to appear', () => { const waits: number[] = []; let lookups = 0; - assert.equal( + expect( hasWorkflowRunForSha({ sha: 'abc', workflowPath: RUN_PATH, @@ -1045,14 +978,13 @@ test('waits for the run of the moving push to appear', () => { delayMs: 1000, wait: (milliseconds) => waits.push(milliseconds), }), - true, - ); - assert.deepEqual(waits, [1000, 1000]); + ).toBe(true); + expect(waits).toStrictEqual([1000, 1000]); }); test('gives up after the last attempt without a matching run', () => { const waits: number[] = []; - assert.equal( + expect( hasWorkflowRunForSha({ sha: 'abc', workflowPath: RUN_PATH, @@ -1061,22 +993,20 @@ test('gives up after the last attempt without a matching run', () => { delayMs: 1000, wait: (milliseconds) => waits.push(milliseconds), }), - false, - ); - assert.deepEqual(waits, [1000, 1000]); + ).toBe(false); + expect(waits).toStrictEqual([1000, 1000]); }); test('does not assume a newer run when none matches or the lookup fails', () => { - assert.equal( + expect( hasWorkflowRunForSha({ sha: 'abc', workflowPath: RUN_PATH, listRunPaths: () => ['.github/workflows/other.yml'], wait: () => undefined, }), - false, - ); - assert.equal( + ).toBe(false); + expect( hasWorkflowRunForSha({ sha: 'abc', workflowPath: RUN_PATH, @@ -1084,27 +1014,24 @@ test('does not assume a newer run when none matches or the lookup fails', () => throw new Error('403'); }, }), - false, - ); - assert.equal( + ).toBe(false); + expect( hasWorkflowRunForSha({ sha: 'abc', workflowPath: undefined, listRunPaths: () => [RUN_PATH], }), - false, - ); + ).toBe(false); }); test('reads the calling workflow path from the workflow ref', () => { - assert.equal( + expect( 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); + ).toBe(RUN_PATH); + expect(getCallingWorkflowPath({})).toBe(undefined); }); const staleWarning = getUnlistedCherryPicksWarning('8.20.0', { @@ -1113,23 +1040,21 @@ const staleWarning = getUnlistedCherryPicksWarning('8.20.0', { }); test('keeps text written on the line after a stale warning', () => { - assert.equal( + expect( refreshGeneratedWarnings({ existingBody: `Intro.\n\n${staleWarning}\nChecked #1, fine.`, version: '8.20.0', }), - 'Intro.\n\nChecked #1, fine.', - ); + ).toBe('Intro.\n\nChecked #1, fine.'); }); test('removes a stale warning separated by extra blank lines', () => { - assert.equal( + expect( refreshGeneratedWarnings({ existingBody: `Intro.\n\n\n${staleWarning}`, version: '8.20.0', }), - 'Intro.', - ); + ).toBe('Intro.'); }); test('adds a warning to an empty body without leading blank lines', () => { @@ -1137,14 +1062,13 @@ test('adds a warning to an empty body without leading blank lines', () => { baselineVersion: '8.19.0', prNumbers: ['1'], }; - assert.equal( + expect( refreshGeneratedWarnings({ existingBody: '', version: '8.20.0', unlistedCherryPicks, }), - staleWarning, - ); + ).toBe(staleWarning); }); test('leaves a CRLF body whose warning sits mid-body', () => { @@ -1152,14 +1076,13 @@ test('leaves a CRLF body whose warning sits mid-body', () => { baselineVersion: '8.19.0', prNumbers: ['1'], }; - assert.equal( + expect( refreshGeneratedWarnings({ existingBody: `Intro.\r\n\r\n${staleWarning}\r\n\r\nTrailing note.`, version: '8.20.0', unlistedCherryPicks, }), - undefined, - ); + ).toBe(undefined); }); const EXCLUSION_SECTION = [ @@ -1182,9 +1105,8 @@ test('excludes the entries of PRs already on the baseline branch', () => { reviewedPrNumbers: new Set(), }); - assert.deepEqual(result.excludedPrNumbers, ['1', '3']); - assert.equal( - result.section, + expect(result.excludedPrNumbers).toStrictEqual(['1', '3']); + expect(result.section).toBe( [ '## [2.0.0]', '', @@ -1204,8 +1126,8 @@ test('keeps an entry that also owns a PR that is not excluded', () => { reviewedPrNumbers: new Set(), }); - assert.equal(result.section, EXCLUSION_SECTION); - assert.deepEqual(result.excludedPrNumbers, []); + expect(result.section).toBe(EXCLUSION_SECTION); + expect(result.excludedPrNumbers).toStrictEqual([]); }); test('does not report PRs a reviewer already approved in the section', () => { @@ -1216,7 +1138,7 @@ test('does not report PRs a reviewer already approved in the section', () => { reviewedPrNumbers: new Set(['1']), }); - assert.deepEqual(result.excludedPrNumbers, ['2']); + expect(result.excludedPrNumbers).toStrictEqual(['2']); }); test('does not report excluded PRs that the section never listed', () => { @@ -1227,8 +1149,8 @@ test('does not report excluded PRs that the section never listed', () => { reviewedPrNumbers: new Set(), }); - assert.equal(result.section, EXCLUSION_SECTION); - assert.deepEqual(result.excludedPrNumbers, []); + expect(result.section).toBe(EXCLUSION_SECTION); + expect(result.excludedPrNumbers).toStrictEqual([]); }); test('adds the unlisted cherry-pick warning to the PR body', () => { @@ -1239,5 +1161,5 @@ test('adds the unlisted cherry-pick warning to the PR body', () => { unlistedCherryPicks: { baselineVersion: '1.0.0', prNumbers: ['5'] }, }); - assert.match(body, /#5 was left out of 2\.0\.0/u); + expect(body).toMatch(/#5 was left out of 2\.0\.0/u); }); diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index 415c2866..6c547f6f 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -31,6 +31,12 @@ ".github/actions/playwright-test-health-report/lib/report-health.test.mjs": { "require-unicode-regexp": { "count": 2 + }, + "vitest/no-conditional-in-test": { + "count": 3 + }, + "vitest/prefer-to-have-length": { + "count": 3 } }, ".github/actions/playwright-test-health-report/lib/slack-test-health-blocks.mjs": { @@ -296,7 +302,7 @@ "count": 12 }, "typescript/explicit-function-return-type": { - "count": 5 + "count": 13 }, "typescript/no-base-to-string": { "count": 2 @@ -307,11 +313,20 @@ "typescript/return-await": { "count": 9 }, + "vitest/consistent-test-it": { + "count": 35 + }, "vitest/no-conditional-in-test": { "count": 7 }, - "vitest/no-import-node-test": { + "vitest/prefer-to-be": { "count": 1 + }, + "vitest/prefer-to-have-length": { + "count": 9 + }, + "vitest/require-top-level-describe": { + "count": 34 } }, ".github/scripts/tests/git-test-environment.mts": { @@ -332,35 +347,62 @@ "typescript/explicit-function-return-type": { "count": 3 }, - "vitest/no-import-node-test": { - "count": 1 + "vitest/consistent-test-it": { + "count": 4 + }, + "vitest/require-top-level-describe": { + "count": 5 } }, ".github/scripts/tests/release-section.test.mts": { "typescript/explicit-function-return-type": { "count": 1 }, + "vitest/consistent-test-it": { + "count": 29 + }, "vitest/no-conditional-in-test": { "count": 1 }, - "vitest/no-import-node-test": { - "count": 1 + "vitest/no-restricted-matchers": { + "count": 3 + }, + "vitest/prefer-to-be": { + "count": 4 + }, + "vitest/prefer-to-contain": { + "count": 2 + }, + "vitest/require-top-level-describe": { + "count": 29 } }, ".github/scripts/tests/release-version-utils.test.mts": { - "vitest/no-import-node-test": { - "count": 1 + "vitest/consistent-test-it": { + "count": 4 + }, + "vitest/prefer-to-be": { + "count": 3 + }, + "vitest/require-top-level-describe": { + "count": 4 } }, ".github/scripts/tests/retry.test.mts": { + "typescript/explicit-function-return-type": { + "count": 2 + }, "typescript/return-await": { "count": 2 }, + "vitest/consistent-test-it": { + "count": 3 + }, "vitest/no-conditional-in-test": { "count": 1 }, - "vitest/no-import-node-test": { - "count": 1 + "vitest/require-top-level-describe": { + "count": 3 } }, ".github/scripts/tests/update-release-changelog-baseline.test.mts": { @@ -370,8 +412,17 @@ "typescript/explicit-function-return-type": { "count": 1 }, - "vitest/no-import-node-test": { + "vitest/consistent-test-it": { + "count": 9 + }, + "vitest/prefer-to-contain": { + "count": 2 + }, + "vitest/prefer-to-have-length": { "count": 1 + }, + "vitest/require-top-level-describe": { + "count": 9 } }, ".github/scripts/tests/update-release-changelog-git.test.mts": { @@ -379,18 +430,18 @@ "count": 14 }, "vitest/no-conditional-in-test": { - "count": 2 + "count": 3 + }, + "vitest/prefer-to-be": { + "count": 4 }, - "vitest/no-import-node-test": { + "vitest/require-to-throw-message": { "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": { @@ -403,11 +454,17 @@ "typescript/explicit-function-return-type": { "count": 3 }, + "vitest/consistent-test-it": { + "count": 61 + }, "vitest/no-conditional-in-test": { "count": 2 }, - "vitest/no-import-node-test": { - "count": 1 + "vitest/prefer-to-be": { + "count": 8 + }, + "vitest/require-top-level-describe": { + "count": 61 } }, ".github/scripts/update-release-changelog-baseline.mts": { diff --git a/oxlint.config.mts b/oxlint.config.mts index e2c2b756..a4051147 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], @@ -58,10 +44,8 @@ export default createConfig({ }, { - files: ['src/**/*.test.ts'], + files: ['src/**/*.test.ts', '.github/**/*.test.{mjs,mts}'], 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..ae1d192c 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -5,20 +5,44 @@ 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', + + // Only `src` counts towards the coverage thresholds. The scripts under + // `.github` are not part of the coverage report. include: ['src/**/*.ts'], exclude: ['src/**/*.test.ts'], reporter: ['text', 'html', 'json-summary'], From bf1bffacdf6f0548404a08bacc637e186aabb8b8 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Mon, 16 Nov 2026 14:50:31 +0100 Subject: [PATCH 2/4] chore: convert the new merge previous releases tests to vitest --- .github/scripts/tests/merge-previous-releases.test.mts | 9 +++------ oxlint-suppressions.json | 4 ++-- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/.github/scripts/tests/merge-previous-releases.test.mts b/.github/scripts/tests/merge-previous-releases.test.mts index ff5fec6a..f3fb460b 100644 --- a/.github/scripts/tests/merge-previous-releases.test.mts +++ b/.github/scripts/tests/merge-previous-releases.test.mts @@ -180,8 +180,7 @@ test('moves the Unreleased link to the restored release', () => { fixture.run(); - assert.equal( - fixture.readChangelog(), + 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`, ); }); @@ -196,9 +195,7 @@ test('keeps an Unreleased link that already starts from a newer release', () => fixture.run(); - assert.ok( - fixture - .readChangelog() - .includes(`[Unreleased]: ${compare}v13.55.0...HEAD\n`), + expect(fixture.readChangelog()).toContain( + `[Unreleased]: ${compare}v13.55.0...HEAD\n`, ); }); diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index 6c547f6f..fda10a3f 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -348,10 +348,10 @@ "count": 3 }, "vitest/consistent-test-it": { - "count": 4 + "count": 6 }, "vitest/require-top-level-describe": { - "count": 5 + "count": 7 } }, ".github/scripts/tests/release-section.test.mts": { From 675c5066dcbd9508402e90df8cf36f3c04d17ad7 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Mon, 16 Nov 2026 17:22:01 +0100 Subject: [PATCH 3/4] chore: include the workflow scripts in coverage --- vitest.config.mts | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/vitest.config.mts b/vitest.config.mts index ae1d192c..33b3ca06 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -41,20 +41,18 @@ export default defineConfig({ provider: 'v8', - // Only `src` counts towards the coverage thresholds. The scripts under - // `.github` are not part of the coverage report. - 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, }, }, }, From b6b3dfa30020be09e73634f922bb971e4330676a Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Tue, 17 Nov 2026 11:02:15 +0100 Subject: [PATCH 4/4] chore: fix the vitest lint violations in the migrated tests instead of suppressing them --- .../lib/report-health.test.mjs | 37 +- .../tests/clean-release-changelog.test.mts | 1371 ++++++------ .../tests/merge-previous-releases.test.mts | 330 +-- .../scripts/tests/release-section.test.mts | 797 +++---- .../tests/release-version-utils.test.mts | 74 +- .github/scripts/tests/retry.test.mts | 73 +- ...update-release-changelog-baseline.test.mts | 416 ++-- .../update-release-changelog-git.test.mts | 22 +- .../tests/update-release-changelog.test.mts | 1919 +++++++++-------- oxlint-suppressions.json | 189 -- oxlint.config.mts | 28 +- 11 files changed, 2569 insertions(+), 2687 deletions(-) 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 95bc57cb..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 @@ -50,11 +50,11 @@ describe('summarizeTestHealth', () => { }, ]); - const test = summary[0]; - expect(test.latestClassification).toBe('passed'); - expect(test.historicalBrokenCount).toBe(1); - expect(test.historicalFlakyCount).toBe(1); - expect(test.totalRuns).toBe(3); + const [first] = summary; + expect(first.latestClassification).toBe('passed'); + expect(first.historicalBrokenCount).toBe(1); + expect(first.historicalFlakyCount).toBe(1); + expect(first.totalRuns).toBe(3); }); }); @@ -72,9 +72,9 @@ describe('partitionSummary', () => { }, ]); - expect(watchItems.length).toBe(1); - expect(flakyItems.length).toBe(0); - expect(brokenItems.length).toBe(0); + expect(watchItems).toHaveLength(1); + expect(flakyItems).toHaveLength(0); + expect(brokenItems).toHaveLength(0); }); }); @@ -103,8 +103,8 @@ describe('formatWatchHistory', () => { totalRuns: 8, }); - expect(text).toMatch(/failed 2\/8 runs/); - expect(text).toMatch(/flaky 3\/8 runs/); + expect(text).toMatch(/failed 2\/8 runs/u); + expect(text).toMatch(/flaky 3\/8 runs/u); }); }); @@ -190,15 +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); - expect(link?.url).toBe( - '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 9fb5f579..f869e567 100644 --- a/.github/scripts/tests/clean-release-changelog.test.mts +++ b/.github/scripts/tests/clean-release-changelog.test.mts @@ -7,7 +7,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { promisify } from 'node:util'; -import { expect, test, vi } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { assertPrEvidenceAvailable, @@ -33,191 +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', () => { - expect( - getEnvironmentWithoutAiKey({ - GH_TOKEN: 'github-token', - AI_ANALYZER_LITELLM_KEY: 'litellm-key', - }), - ).toStrictEqual({ 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); + }, + ); - expect(response).toBe('{"title":"Recovered"}'); - expect(attempts).toBe(3); - expect(retryDelays).toStrictEqual([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 expect( - (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'); }, - ))(), - ).rejects.toThrow(/HTTP 404/u); - expect(attempts).toBe(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)', ), - ), - ).toBe(false); -}); + ).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)', + ), + ), + ).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'); - }, - ); + }, + ); - expect(evidence.unavailablePrEvidence).toStrictEqual([]); - expect(evidence.evidence[0] ?? '').toMatch( - /#37469: fix: match the recurring every sheet/u, - ); - expect(requests.length).toBe(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. - 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 }); - } -}); + 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 () => { - const directory = mkdtempSync(join(tmpdir(), 'no-repo-')); - const originalDirectory = process.cwd(); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + 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 }); + } + }); - try { - process.chdir(directory); - expect([...(await getLocalPrEvidence(['1']))]).toStrictEqual([]); - expect(warn).toHaveBeenCalledTimes(1); - } finally { - process.chdir(originalDirectory); - rmSync(directory, { force: true, recursive: true }); - } -}); + 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); -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.', - ], - ]), - ); + try { + process.chdir(directory); + expect([...(await getLocalPrEvidence(['1']))]).toStrictEqual([]); + expect(warn).toHaveBeenCalledTimes(1); + } finally { + process.chdir(originalDirectory); + rmSync(directory, { force: true, recursive: true }); + } + }); - 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.', - ]); -}); + 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('limits local evidence history to referenced PR numbers', () => { - expect(getLocalEvidenceLogArguments([])).toStrictEqual(undefined); - expect( - getLocalEvidenceLogArguments(['37469', '37522', '37469']), - ).toStrictEqual([ - 'log', - 'HEAD', - '--extended-regexp', - '--grep=\\(#(37469|37522)\\)', - '--format=%H%x1f%s%x1f%b%x1e', - ]); -}); + 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('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('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', + ]); + }); -test('cleans large release sections in reference-preserving chunks', () => { - const section = `## [13.51.0] + 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 @@ -227,29 +229,29 @@ test('cleans large release sections in reference-preserving chunks', () => { ### Fixed - Improved a flow (#103)`; - expect(splitReleaseSectionIntoChunks(section, '13.51.0', 2)).toStrictEqual([ - { - 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 @@ -258,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', - ); - expect(() => - validateReplacement(merged, '13.51.0', ['101', '102', '103']), - ).not.toThrow(); - expect(merged).not.toMatch(/\)\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', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => 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 @@ -284,30 +286,30 @@ test('warns about and skips an identical repeat of an entry', () => { ### Changed - Fixed an issue (#101)`, - '13.51.0', - ); + '13.51.0', + ); - expect(chunks[0]?.prNumbers).toStrictEqual(['101']); - expect(warn).toHaveBeenCalledTimes(1); - expect(String(warn.mock.calls[0]?.[0])).toMatch(/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', () => { - expect(() => - splitReleaseSectionIntoChunks( - `## [13.51.0] + it('rejects different entries for the same PR instead of dropping one', () => { + expect(() => + splitReleaseSectionIntoChunks( + `## [13.51.0] ### Fixed - Fixed an issue (#101) - Fixed another issue (#101)`, - '13.51.0', - ), - ).toThrow(/different entries for PR 101/u); -}); + '13.51.0', + ), + ).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} @@ -318,45 +320,47 @@ ${generatedSection} - An earlier fix (#100) `; - expect(extractReleaseSection(changelog, '13.51.0').section).toBe( - generatedSection, - ); - expect(getPrNumbers(generatedSection)).toStrictEqual(['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', () => { - expect( - 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`), - ).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']); -}); + ).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', () => { - expect(() => - extractReleaseSection( - `${generatedSection}\n\n${generatedSection}`, - '13.51.0', - ), - ).toThrow(/Expected exactly one release heading/u); -}); + it('rejects a duplicate release heading', () => { + expect(() => + extractReleaseSection( + `${generatedSection}\n\n${generatedSection}`, + '13.51.0', + ), + ).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} @@ -366,7 +370,7 @@ ${generatedSection} - An earlier fix (#100) `; - const replacement = `## [13.51.0] + const replacement = `## [13.51.0] ### Added @@ -376,15 +380,15 @@ ${generatedSection} - Fixed an issue (#102)`; - expect(replaceReleaseSection(changelog, '13.51.0', replacement)).toBe( - 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', () => { - expect(() => - validateReplacement( - `## [13.51.0] + it('accepts a categorized replacement that preserves every PR once', () => { + expect(() => + validateReplacement( + `## [13.51.0] ### Added @@ -393,289 +397,303 @@ test('accepts a categorized replacement that preserves every PR once', () => { ### Fixed - Fixed an issue (#102)`, - '13.51.0', - ['101', '102'], - ), - ).not.toThrow(); -}); + '13.51.0', + ['101', '102'], + ), + ).not.toThrow(); + }); -test('rejects uncategorized, omitted, invented, and duplicate PR references', () => { - expect(() => - validateReplacement(generatedSection, '13.51.0', ['101', '102']), - ).toThrow(/Uncategorized/u); - expect(() => - validateReplacement( - `## [13.51.0] + 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] ### Fixed - Fixed an issue (#101)`, - '13.51.0', - ['101', '102'], - ), - ).toThrow(/references do not match/u); - expect(() => - validateReplacement( - `## [13.51.0] + '13.51.0', + ['101', '102'], + ), + ).toThrow(/references do not match/u); + expect(() => + validateReplacement( + `## [13.51.0] ### Fixed - Fixed an issue (#101, #102, #103)`, - '13.51.0', - ['101', '102'], - ), - ).toThrow(/references do not match/u); - expect(() => - validateReplacement( - `## [13.51.0] + '13.51.0', + ['101', '102'], + ), + ).toThrow(/references do not match/u); + expect(() => + validateReplacement( + `## [13.51.0] ### Fixed - Fixed an issue (#101) - Fixed it again (#101) - Fixed another issue (#102)`, - '13.51.0', - ['101', '102'], - ), - ).toThrow(/duplicate PR references/u); - expect(() => - validateReplacement( - `## [13.51.0] + '13.51.0', + ['101', '102'], + ), + ).toThrow(/duplicate PR references/u); + expect(() => + validateReplacement( + `## [13.51.0] Here is the cleaned section: ### Fixed - Fixed an issue (#101, #102)`, - '13.51.0', - ['101', '102'], - ), - ).toThrow(/unexpected Markdown/u); - expect(() => - validateReplacement( - `## [13.51.0] + '13.51.0', + ['101', '102'], + ), + ).toThrow(/unexpected Markdown/u); + expect(() => + validateReplacement( + `## [13.51.0] ### Fixed - Fixed an issue (#101)- Fixed another issue (#102)`, - '13.51.0', - ['101', '102'], - ), - ).toThrow(/adjacent list items/u); -}); + '13.51.0', + ['101', '102'], + ), + ).toThrow(/adjacent list items/u); + }); -test('rejects an entry without a trailing PR reference', () => { - expect(() => - validateReplacement( - `## [13.51.0] + it('rejects an entry without a trailing PR reference', () => { + expect(() => + validateReplacement( + `## [13.51.0] ### Fixed - Fixed an issue (#101) - Improved performance across the app`, - '13.51.0', - ['101'], - ), - ).toThrow(/must be text followed by its PR reference/u); -}); + '13.51.0', + ['101'], + ), + ).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}`; - 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', - ]), - ).toThrow(/references do not match/u); -}); + 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'], + ), + ).toThrow(/references do not match/u); + }); -test('accepts dashes and parentheses inside an entry', () => { - expect(() => - 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'], - ), - ).not.toThrow(); -}); + '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; + } -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'); + /** + * 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 expect( - (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([]), - }))(), - ).rejects.toThrow(/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, - }); - - expect(result).toBe('## [13.51.0]'); - expect(requests.length).toBe(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(String(requests[0]?.init.body)) 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); -}); -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 expect( - (async () => - requestCleanRoomRewrite({ - ...rewriteInput, - fetchImpl: createFetch([fakeResponse(status)], requests), - sleep: async (milliseconds) => { - sleeps.push(milliseconds); - }, - timeoutMs: 1_000, - }))(), - ).rejects.toSatisfy( - (error: unknown) => - isLiteLlmAuthenticationError(error) && - error.message.includes(`HTTP ${String(status)}`), - ); - expect(requests.length).toBe(1); - expect(sleeps).toStrictEqual([]); - } -}); + 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, - }); - - expect(result).toBe('## [13.51.0]'); - expect(requests.length).toBe(2); - expect(sleeps).toStrictEqual([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 expect( - (async () => + it('stops after the retry budget for persistent LiteLLM failures', async () => { + const requests: RecordedRequest[] = []; + await expect( requestCleanRoomRewrite({ ...rewriteInput, fetchImpl: createFetch( @@ -684,27 +702,26 @@ test('stops after the retry budget for persistent LiteLLM failures', async () => ), sleep: async () => undefined, timeoutMs: 1_000, - }))(), - ).rejects.toThrow(/LiteLLM returned HTTP 500/u); - expect(requests.length).toBe(2); -}); + }), + ).rejects.toThrow(/LiteLLM returned HTTP 500/u); + expect(requests).toHaveLength(2); + }); -test('rejects an empty LiteLLM message after the retry budget', async () => { - await expect( - (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, - }))(), - ).rejects.toThrow(/no message content/u); -}); + }), + ).rejects.toThrow(/no message content/u); + }); -test('requests another response when one fails validation', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => 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 @@ -713,31 +730,33 @@ test('requests another response when one fails validation', async () => { ### 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'], + ); - expect(section).toBe(valid); - expect(requests.length).toBe(2); -}); + expect(section).toBe(valid); + expect(requests).toHaveLength(2); + }); -test('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)'; + 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 expect( - (async () => + await expect( requestValidatedRewrite( { ...rewriteInput, @@ -748,16 +767,15 @@ test('gives up after the last response fails validation', async () => { }, '13.51.0', ['101', '102'], - ))(), - ).rejects.toThrow(/references do not match/u); - expect(requests.length).toBe(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 expect( - (async () => + await expect( requestValidatedRewrite( { ...rewriteInput, @@ -765,161 +783,165 @@ test('does not request again after a rejected key', async () => { }, '13.51.0', ['101', '102'], - ))(), - ).rejects.toThrow(LiteLlmAuthenticationError); - expect(requests.length).toBe(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 expect( - (async () => + await expect( requestCleanRoomRewrite({ ...rewriteInput, fetchImpl: hangingFetch, sleep: async () => undefined, timeoutMs: 5, - }))(), - ).rejects.toThrow(/aborted by timeout/u); - expect(signals.length).toBe(2); - expect(signals.every((signal) => signal?.aborted)).toBe(true); -}); - -test('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' }, - ]), - ).toThrow( - /PR evidence unavailable: #101 \(HTTP 404: Not Found\), #102 \(HTTP 500: Internal Server Error\)/u, - ); - expect(() => assertPrEvidenceAvailable([])).not.toThrow(); -}); - -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(), - }); + }), + ).rejects.toThrow(/aborted by timeout/u); + expect(signals).toHaveLength(2); + expect(signals.every((signal) => signal?.aborted)).toBe(true); + }); - 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', + 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' }, + ]), + ).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), + ); + + type ProofreadResult = { + exitCode: number; + original: string; + changelog: string; + report: Record; + }; - await new Promise((resolve) => { - server.listen(0, '127.0.0.1', resolve); + /** + * 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 @@ -928,18 +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)); - expect(result.exitCode).toBe(0); - expect(result.report.status).toBe('succeeded'); - expect(result.changelog).toBe( - 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 @@ -949,24 +971,25 @@ test('leaves the changelog untouched when the model invents an entry', async () ### Fixed - Fixed an issue (#102)`), - ); - - 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); -}); + ); -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); }); - expect(result.exitCode).toBe(1); - expect(result.report.stage).toBe('authentication'); - expect(result.changelog).toBe(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 f3fb460b..e1898559 100644 --- a/.github/scripts/tests/merge-previous-releases.test.mts +++ b/.github/scripts/tests/merge-previous-releases.test.mts @@ -9,193 +9,199 @@ import { } from 'node:fs'; import { tmpdir } from 'node:os'; import { delimiter, join } from 'node:path'; -import { afterAll, expect, test } from 'vitest'; +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-'), -); -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; -}) { - 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(); - - 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', + const TEMPORARY_DIRECTORY = mkdtempSync( + join(tmpdir(), 'previous-release-merge-'), ); - expect(() => + 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', - ), - ).not.toThrow(); -}); + 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', + }); - 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(); -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, + }); - expect(fixture.readChangelog()).toBe(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, + }); - expect(fixture.readChangelog()).toBe(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`, + }); - 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(); -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}`, + }); - expect(fixture.readChangelog()).toContain( - `[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 595f2ea2..e28dc5d4 100644 --- a/.github/scripts/tests/release-section.test.mts +++ b/.github/scripts/tests/release-section.test.mts @@ -1,4 +1,4 @@ -import { expect, test } from 'vitest'; +import { describe, expect, it } from 'vitest'; import { extractReleaseSection, @@ -11,25 +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'; - expect(extractReleaseSection(changelog, '1.0.0').section).toBe( - '## [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'; - 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'); -}); + 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 @@ -38,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 @@ -49,24 +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', + }); - expect(newEntriesSection).toBe(`## [13.51.0] + expect(newEntriesSection).toBe(`## [13.51.0] ### Added - Added a new feature (#103)`); - expect( - mergeNewReleaseEntries({ - existingSection, - newEntriesSection: newEntriesSection ?? '', - version: '13.51.0', - }), - ).toBe(`## [13.51.0] + expect( + mergeNewReleaseEntries({ + existingSection, + newEntriesSection: newEntriesSection as string, + version: '13.51.0', + }), + ).toBe(`## [13.51.0] ### Added @@ -76,10 +77,10 @@ test('isolates newly generated entries without changing the existing release sec ### Fixed - 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 @@ -90,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`; - expect( - mergeNewReleaseEntries({ - existingSection, - newEntriesSection: `## [13.51.0] + expect( + mergeNewReleaseEntries({ + existingSection, + newEntriesSection: `## [13.51.0] ### Changed @@ -106,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', - }), - ).toBe(`## [13.51.0] + version: '13.51.0', + }), + ).toBe(`## [13.51.0] ### Added @@ -127,213 +128,214 @@ test('merges new entries into matching categories and inserts missing ones in ca ### Security - Hardened a thing (#105)`); -}); + }); -test('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)`, - ); -}); + 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', () => { - 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)`, - ); -}); + 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'; - expect( - 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, - ), - ).toBe( - [ - '- 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', () => { - 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)`); -}); + 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', () => { - 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)'); -}); + 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', () => { - 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)'); -}); + 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', () => { - 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)', - ); -}); + 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', () => { - expect( - 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', - }), - ).toBe(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)`; - expect( - 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', - }), - ).toBe(`## [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`); - expect( - getNewReleaseEntriesSection({ - existingSection, - generatedSection: `## [13.51.0] + expect( + getNewReleaseEntriesSection({ + existingSection, + generatedSection: `## [13.51.0] ### Fixed - Reworded a documented PR that mentions (#102) (#101)`, - version: '13.51.0', - }), - ).toBe(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}`; - 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)`; + 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)')); + }); - expect( - getNewReleaseEntriesSection({ - existingSection, - generatedSection: `## [13.51.0]\n\n### Fixed\n\n- Fixed an issue (#101, #102)`, - version: '13.51.0', - }), - ).toBe(undefined); - 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']), - }), - ).toBe(undefined); -}); + 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)`; + + 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', () => { - expect( - mergeCurrentReleaseSection({ - changelog: `# Changelog + it('preserves the reviewed release section above historical predecessor history', () => { + expect( + mergeCurrentReleaseSection({ + changelog: `# Changelog ## [13.50.0] @@ -341,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', - }), - ).toBe(`# Changelog + version: '13.51.0', + }), + ).toBe(`# Changelog ## [13.51.0] @@ -362,12 +364,12 @@ test('preserves the reviewed release section above historical predecessor histor - Fixed an earlier issue (#100) `); -}); + }); -test('inserts the reviewed release section after the preamble and Unreleased heading', () => { - expect( - 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. @@ -379,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', - }), - ).toBe(`# Changelog + version: '13.51.0', + }), + ).toBe(`# Changelog All notable changes to this project will be documented in this file. @@ -404,9 +406,9 @@ All notable changes to this project will be documented in this file. - Fixed an earlier issue (#100) `); -}); + }); -const stableShapedChangelog = `# Changelog + const stableShapedChangelog = `# Changelog All notable changes to this project will be documented in this file. @@ -432,216 +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]'), + ); }); - 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]') < merged.indexOf('## [13.51.0]'), - ).toBeTruthy(); - expect( - merged.indexOf('## [13.51.0]') < merged.indexOf('## [13.50.0]'), - ).toBeTruthy(); -}); + 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'); }); - expect(merged.replaceAll('\r\n', '').includes('\n')).toBe(false); - expect(merged.includes('## [13.51.0]\r\n\r\n### Added')).toBeTruthy(); -}); + 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); }); - expect(twice.match(/^## \[13\.51\.0\]$/gmu)?.length).toBe(1); - expect(twice).toMatch(/\(#102\)/u); - expect(twice).not.toMatch(/\(#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`, + ); }); - expect(merged).toBe(`# 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', + ); }); - expect(merged.includes('\r\r')).toBe(false); - 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', - ); -}); - -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)', - ); - - expect( - getNewReleaseEntriesSection({ - existingSection, - generatedSection, - version: '1.0.0', - }), - ).toBe('## [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', () => { - 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', - }), - ).toThrow(/lacks a PR reference/u); -}); + 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', + }), + ).toThrow(/lacks a PR reference/u); + }); -test('rejects a changelog without the Changelog heading', () => { - expect(() => - mergeCurrentReleaseSection({ - changelog: '## [13.50.0]\n', - currentReleaseSection: reviewedSection, - version: '13.51.0', - }), - ).toThrow(/must begin with a Changelog heading/u); -}); + it('rejects a changelog without the Changelog heading', () => { + expect(() => + mergeCurrentReleaseSection({ + changelog: '## [13.50.0]\n', + currentReleaseSection: reviewedSection, + version: '13.51.0', + }), + ).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'); - - 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)'), - ); -}); + 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'); - - 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]'); -}); + 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'); - - 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'), - ); -}); + 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)'; - expect(removeReleaseEntries({ section, prNumbers: new Set(['9']) })).toBe( - 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 a9d201a7..02a0f73f 100644 --- a/.github/scripts/tests/release-version-utils.test.mts +++ b/.github/scripts/tests/release-version-utils.test.mts @@ -1,4 +1,4 @@ -import { expect, test } from 'vitest'; +import { describe, expect, it } from 'vitest'; import { compareSemver, @@ -6,44 +6,46 @@ import { selectHighestLowerVersion, } from '../release-version-utils.mts'; -test('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', +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', + }); }); - expect(parseReleaseBranch('release/13.50.3-ota')).toStrictEqual({ - version: '13.50.3', - kind: 'ota', - name: 'release/13.50.3-ota', - }); -}); -test('rejects unsupported release branch names', () => { - expect(parseReleaseBranch('release/13.50.3-fallback')).toBe(undefined); - expect(parseReleaseBranch('release/13.50.3.1')).toBe(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', () => { - 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); -}); + 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', () => { - expect( - 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', - ]), - ).toBe('13.50.3'); - expect(selectHighestLowerVersion('13.50.4', ['13.50.2', '13.50.3'])).toBe( - '13.50.3', - ); - expect( - selectHighestLowerVersion('13.51.0', ['13.51.0', '13.51.1', '14.0.0']), - ).toBe(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 65db6b0c..0d5e359d 100644 --- a/.github/scripts/tests/retry.test.mts +++ b/.github/scripts/tests/retry.test.mts @@ -1,53 +1,43 @@ -import { expect, test } from 'vitest'; +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); }, - }, - ); + }); - expect(result).toBe('recovered'); - expect(attempts).toBe(3); - expect(delays).toStrictEqual([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 expect( - (async () => - retry( - async () => { - attempts += 1; - throw new Error('Permanent failure'); - }, - { shouldRetry: () => false }, - ))(), - ).rejects.toThrow(/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); - expect(attempts).toBe(1); -}); + expect(operation).toHaveBeenCalledTimes(1); + }); -test('reports retry details before delaying', async () => { - const retries: { attempt: number; delayMilliseconds: number }[] = []; - await expect( - (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'); }, { @@ -57,8 +47,9 @@ test('reports retry details before delaying', async () => { }, sleep: async () => undefined, }, - ))(), - ).rejects.toThrow(/Transient failure/u); + ), + ).rejects.toThrow(/Transient failure/u); - expect(retries).toStrictEqual([{ 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 8f107535..80912df1 100644 --- a/.github/scripts/tests/update-release-changelog-baseline.test.mts +++ b/.github/scripts/tests/update-release-changelog-baseline.test.mts @@ -1,222 +1,238 @@ -import { expect, test } from 'vitest'; +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', () => { - 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', + 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', () => { - 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', + 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', () => { - 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' }); -}); + 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', () => { - 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', + 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', () => { - expect(() => - selectBaseline( - createDependencies({ - headings: new Set(['origin/stable:13.50.2']), - stableVersions: ['13.50.2'], - releaseBranches: [ - { - version: '13.50.3', - kind: 'native', - name: 'release/13.50.3', - }, - ], - }), - ), - ).toThrow( - /origin\/release\/13\.50\.3 has no ## \[13\.50\.3\] changelog section/u, - ); -}); + it('rejects a predecessor release branch whose changelog lacks its own section', () => { + expect(() => + selectBaseline( + createDependencies({ + headings: new Set(['origin/stable:13.50.2']), + stableVersions: ['13.50.2'], + releaseBranches: [ + { + version: '13.50.3', + kind: 'native', + name: 'release/13.50.3', + }, + ], + }), + ), + ).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', () => { - 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'), - ); -}); + 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', () => { - expect(removeNewerReleases(stableChangelog, '13.51.0')).toBe(stableChangelog); - expect(removeNewerReleases(stableChangelog, '14.0.0')).toBe(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'); - expect(removeNewerReleases(crlf, '13.50.4').includes('\r\r')).toBe(false); - expect(removeNewerReleases(crlf, '13.50.4').includes('13.51.0]')).toBe(false); - expect(removeNewerReleases(crlf, '13.50.4').split('\r\n').length).toBe( - 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', () => { - expect(() => - selectBaseline( - createDependencies({ - releaseBranches: [ - { - version: '13.50.3', - kind: 'native', - name: 'release/13.50.3', - }, - { - version: '13.50.3', - kind: 'ota', - name: 'release/13.50.3-ota', - }, - ], - }), - ), - ).toThrow(/Expected exactly one release branch/u); + it('rejects ambiguous native and OTA predecessor branches', () => { + expect(() => + selectBaseline( + createDependencies({ + releaseBranches: [ + { + version: '13.50.3', + kind: 'native', + name: 'release/13.50.3', + }, + { + version: '13.50.3', + kind: 'ota', + name: 'release/13.50.3-ota', + }, + ], + }), + ), + ).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 0c4a0732..79a664c3 100644 --- a/.github/scripts/tests/update-release-changelog-git.test.mts +++ b/.github/scripts/tests/update-release-changelog-git.test.mts @@ -195,7 +195,7 @@ describe('release changelog Git behavior', () => { expect(() => git(work, 'config', '--get', `branch.${CHANGELOG_BRANCH}.remote`), - ).toThrow(); + ).toThrow(/Command failed/u); }); it('fails when the baseline has no CHANGELOG.md', () => { @@ -229,7 +229,7 @@ describe('release changelog Git behavior', () => { throw new Error('must not query PRs on a first run'); }, }), - ).toBe(undefined); + ).toBeUndefined(); }); it('refuses a stale changelog branch that has no open PR', () => { @@ -250,7 +250,7 @@ describe('release changelog Git behavior', () => { isUpdaterOnlyBranch: () => true, getOpenPrNumber: () => undefined, }), - ).toBe(undefined); + ).toBeUndefined(); }); it('strips trailing whitespace from a reviewed section', () => { @@ -268,7 +268,7 @@ describe('release changelog Git behavior', () => { ...input, changelogBranchSha: getRemoteBranchSha(CHANGELOG_BRANCH), getOpenPrNumber: () => '7', - }) ?? '', + }), ).not.toMatch(/[ \t]$/mu); }); @@ -280,7 +280,7 @@ describe('release changelog Git behavior', () => { allowMissingOpenPr: true, getOpenPrNumber: () => undefined, }), - ).toBe(undefined); + ).toBeUndefined(); }); it('still preserves an open PR when the target already has the section', () => { @@ -291,7 +291,7 @@ describe('release changelog Git behavior', () => { changelogBranchSha: getRemoteBranchSha(CHANGELOG_BRANCH), allowMissingOpenPr: true, getOpenPrNumber: () => '7', - }) ?? '', + }), ).toMatch(/Added a reviewed feature \(#101\)/u); }); @@ -526,20 +526,18 @@ describe('release changelog Git behavior', () => { expect( getChangelogBranchCommits(CHANGELOG_BRANCH, TARGET)[0] ?.generatedThrough, - ).toBe(undefined); + ).toBeUndefined(); }); }); describe('assertRemoteRefUnchanged', () => { it('accepts an unchanged ref and rejects a moved one', () => { const sha = getRemoteBranchSha(TARGET); - if (sha === undefined) { - throw new Error('Expected the target release branch to exist'); - } + expect(sha).toBeDefined(); expect(() => assertRemoteRefUnchanged({ ref: `origin/${TARGET}`, - expectedSha: sha, + expectedSha: sha as string, description: 'Target release branch', }), ).not.toThrow(); @@ -551,7 +549,7 @@ describe('release changelog Git behavior', () => { expect(() => assertRemoteRefUnchanged({ ref: `origin/${TARGET}`, - expectedSha: sha, + expectedSha: sha as string, description: 'Target release branch', }), ).toThrow(/changed during changelog generation/u); diff --git a/.github/scripts/tests/update-release-changelog.test.mts b/.github/scripts/tests/update-release-changelog.test.mts index ee5651e0..c798a254 100644 --- a/.github/scripts/tests/update-release-changelog.test.mts +++ b/.github/scripts/tests/update-release-changelog.test.mts @@ -1,7 +1,7 @@ import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { expect, test, vi } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { assertReleaseSectionHasEntries, @@ -34,93 +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'); - 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 }); - } -}); +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', () => { - expect( - 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`), - ).toStrictEqual(['35695', '35716']); - expect(getHistoricalSkippedPrNumbers('')).toStrictEqual([]); -}); + ).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', () => { - expect([ - ...getAcceptedPrCommits(`[auto-changelog] commit=${COMMIT_A} accepted source-pr=1 canonical-pr=1 cherry-pick=false + 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], - }; - - expect( - getDeletedPrNumbers({ - ...options, - existingPrNumbers: new Set(['1']), - }), - ).toStrictEqual(new Set(['2'])); - expect( - getDeletedPrNumbers({ - ...options, - existingPrNumbers: new Set(['1', '2']), - }), - ).toStrictEqual(new Set()); -}); + ]).toStrictEqual([ + ['1', [COMMIT_A, COMMIT_B]], + ['2', [COMMIT_C]], + ]); + }); -test('treats nothing as deleted when the last tip cannot be read', () => { - expect( - 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'); - }, - }), - ).toStrictEqual(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()); + }); + + 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()); + }); -test('finds the releases that already list a PR, oldest first, excluding the target', () => { - const changelog = `# Changelog + it('finds the releases that already list a PR, oldest first, excluding the target', () => { + const changelog = `# Changelog ## [Unreleased] @@ -143,16 +145,16 @@ test('finds the releases that already list a PR, oldest first, excluding the tar - Unrelated (#1) `; - expect( - findReleaseVersionsContainingPrs(changelog, ['35695', '35716'], '8.10.3'), - ).toStrictEqual(['8.9.0', '8.11.0']); - expect( - findReleaseVersionsContainingPrs(changelog, ['35716'], '8.11.0'), - ).toStrictEqual([]); -}); + 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] @@ -162,1004 +164,1015 @@ 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'; - - expect( - findReleaseVersionsContainingPrs( - changelog, - ['35695'], - '8.10.3', - repositoryUrl, - ), - ).toStrictEqual(['8.9.0']); - expect( - findReleaseVersionsContainingPrs(changelog, ['35695'], '8.10.3'), - ).toStrictEqual([]); -}); + const repositoryUrl = 'https://github.com/MetaMask/metamask-mobile'; -test('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); -}); + expect( + findReleaseVersionsContainingPrs( + changelog, + ['35695'], + '8.10.3', + repositoryUrl, + ), + ).toStrictEqual(['8.9.0']); + expect( + findReleaseVersionsContainingPrs(changelog, ['35695'], '8.10.3'), + ).toStrictEqual([]); + }); -test('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.', + 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); }); - 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', () => { - 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', - ], + 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.', + }); + 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('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, - ); -}); + 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('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'], - ); -}); + 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('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', - ]); -}); + 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', + ]); + }); -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]; + 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]; + } } - } - 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', - }), - ); - - 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('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', }), - ); + ); - expect(body).toMatch( - /\[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', - }; - expect( - getChangelogPrPresentation({ - version: '13.51.0', - changelogBranch: 'release-changelog/13.51.0', - proofreadingStatus: authenticationFailure.status, - proofreadingStage: authenticationFailure.stage, - }).title, - ).toStrictEqual( - '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', + }), + ); + + expect(body).toMatch( + /\[View the proofreading report artifact\.\]\(https:\/\/github\.com\/MetaMask\/metamask-extension\/actions\/runs\/123#artifacts\)/u, + ); + }); -test('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.', + 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)', + ); }); -}); -test('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', - ), - ).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(); -}); + 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('leaves an existing changelog PR alone when nothing changed', () => { - expect( - shouldKeepChangelogPrPresentation({ - existingTitle: 'release: release-changelog/13.51.0', - proofreadingStatus: 'unchanged', - }), - ).toBe(true); -}); + 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', + ), + ).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); + }); - expect( - shouldKeepChangelogPrPresentation({ - existingTitle, - proofreadingStatus: 'succeeded', - }), - ).toBe(true); - expect( - shouldKeepChangelogPrPresentation({ - existingTitle, - proofreadingStatus: 'failed', - }), - ).toBe(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', () => { - expect( - shouldKeepChangelogPrPresentation({ - existingTitle: - 'release: release-changelog/13.51.0 (AI automation failed, not proofread)', - proofreadingStatus: 'succeeded', - replacesWholeSection: true, - }), - ).toBe(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); + }); - expect(isUntouchedUnproofreadChangelogPr(options)).toBe(true); - expect( - 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, }, ], - }), - ).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], - }; - - expect(hasOnlyUpdaterCommits(options)).toBe(true); - expect( - hasOnlyUpdaterCommits({ - ...options, - commits: [ - own, - { authorEmail: 'person@example.com', subject: 'fix wording' }, - ], - }), - ).toBe(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('rewrites the PR presentation after a normal successful run', () => { - expect( - shouldKeepChangelogPrPresentation({ - existingTitle: 'release: release-changelog/13.51.0', - proofreadingStatus: 'succeeded', - }), - ).toBe(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], + }; -test('rejects generated sections with missing or duplicate PR references', () => { - expect(() => - validateGeneratedReleaseSection( - `## [13.51.0] + expect(hasOnlyUpdaterCommits(options)).toBe(true); + expect( + hasOnlyUpdaterCommits({ + ...options, + commits: [ + own, + { authorEmail: 'person@example.com', subject: 'fix wording' }, + ], + }), + ).toBe(false); + }); + + it('rewrites the PR presentation after a normal successful run', () => { + expect( + shouldKeepChangelogPrPresentation({ + existingTitle: 'release: release-changelog/13.51.0', + proofreadingStatus: 'succeeded', + }), + ).toBe(false); + }); + + it('rejects generated sections with missing or duplicate PR references', () => { + expect(() => + validateGeneratedReleaseSection( + `## [13.51.0] ### Fixed - Fixed an issue`, - '13.51.0', - ), - ).toThrow(/without a PR reference/u); - expect(() => - validateGeneratedReleaseSection( - `## [13.51.0] + '13.51.0', + ), + ).toThrow(/without a PR reference/u); + expect(() => + validateGeneratedReleaseSection( + `## [13.51.0] ### Fixed - Fixed an issue (#101) - Fixed it again (#101)`, - '13.51.0', - ), - ).toThrow(/duplicate PR references/u); - expect(() => - validateGeneratedReleaseSection( - `## [13.51.0] + '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, - ), - ).not.toThrow(); -}); + '13.51.0', + true, + ), + ).not.toThrow(); + }); -test('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 + 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`), - ]).toStrictEqual([[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'], - ]); - - expect( - getPrsCherryPickedOntoBaseline({ - cherryPickedPrsByCommit, - baselineRef: 'origin/release/1.0.0', - isAncestor: (commit, ref) => - commit === COMMIT_A && ref === 'origin/release/1.0.0', - }), - ).toStrictEqual(new Set(['1'])); - expect( - getPrsCherryPickedOntoBaseline({ - cherryPickedPrsByCommit, - baselineRef: 'origin/stable', - isAncestor: () => false, - }), - ).toStrictEqual(new Set()); -}); + it('finds the PRs cherry-picked onto the baseline branch', () => { + const cherryPickedPrsByCommit = new Map([ + [COMMIT_A, '1'], + [COMMIT_B, '2'], + ]); -test('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 + 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()); + }); + + 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`), - ]).toStrictEqual([['1', ['7', '8']]]); -}); + ]).toStrictEqual([['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'); + 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']); -}); + 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']); -}); + 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']); + }); -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; -test('reads the earlier release section from its open changelog PR', () => { - const lookups: string[][] = []; + it('reads the earlier release section from its open changelog PR', () => { + const lookups: string[][] = []; - expect( - getOpenBaselineChangelogSection({ + 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'], + ]); + }); + + 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}`, - }), - ).toBe('release-changelog/1.0.0 1.0.0'); - expect(lookups).toStrictEqual([['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'); - }, - }; - - expect( - getOpenBaselineChangelogSection({ - ...options, - getSha: () => undefined, - getOpenPrNumber: () => '9', - }), - ).toBe(undefined); - expect( - getOpenBaselineChangelogSection({ - ...options, - getSha: () => 'abc', - getOpenPrNumber: () => undefined, - }), - ).toBe(undefined); -}); + }; -test('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', + ...options, + getSha: () => undefined, getOpenPrNumber: () => '9', - readSection: () => 'section', }), - ).toBe(undefined); - } -}); + ).toBeUndefined(); + expect( + getOpenBaselineChangelogSection({ + ...options, + getSha: () => 'abc', + getOpenPrNumber: () => undefined, + }), + ).toBeUndefined(); + }); -test('carries on when the open changelog branch lacks the section', () => { - vi.spyOn(console, 'warn').mockImplementation(() => 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(); + } + }); - 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'); - }, - }), - ).toBe(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'); - - expect( - findEntriesDroppedByRestore({ - restoredChangelog, - releaseChangelog: RELEASE_BRANCH_CHANGELOG, - }), - ).toStrictEqual([{ 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'); - expect( - findEntriesDroppedByRestore({ - restoredChangelog, - releaseChangelog: RELEASE_BRANCH_CHANGELOG, - }), - ).toStrictEqual([{ version: '1.0.0', entryCount: 1, prNumbers: ['3'] }]); -}); - -test('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([]); -}); + 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', () => { - 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); -}); + 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'; - expect( - findEntriesDroppedByRestore({ - restoredChangelog: '## [1.0.0]\n\n- Fixed the crash on launch (#2)\n', - releaseChangelog, - }), - ).toStrictEqual([]); -}); + 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`; - 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'] }]); -}); + 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'; - 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([]); -}); + 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 }, - ], - }); - 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, - ); -}); + 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([]); }); - 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, - ); -}); + 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', () => { - 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.', - ); -}); + 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'] })}`; - expect(refreshGeneratedWarnings({ existingBody, version: '8.20.0' })).toBe( - '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'], - }; - expect( - refreshGeneratedWarnings({ - existingBody, + it('adds the dropped entries warning to the PR body', () => { + const { body } = getChangelogPrPresentation({ version: '8.20.0', - unlistedCherryPicks, - }), - ).toBe( - `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)}`; - expect( - refreshGeneratedWarnings({ - existingBody, - version: '8.20.0', - unlistedCherryPicks, - }), - ).toBe(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'; + 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('finds the run the moving push triggered', () => { - expect( - hasWorkflowRunForSha({ - sha: 'abc', - workflowPath: RUN_PATH, - listRunPaths: () => ['.github/workflows/other.yml', RUN_PATH], - }), - ).toBe(true); -}); + 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('waits for the run of the moving push to appear', () => { - const waits: number[] = []; - let lookups = 0; - expect( - hasWorkflowRunForSha({ - sha: 'abc', - workflowPath: RUN_PATH, - listRunPaths: () => { - lookups += 1; - return lookups < 3 ? [] : [RUN_PATH]; - }, - attempts: 5, - delayMs: 1000, - wait: (milliseconds) => waits.push(milliseconds), - }), - ).toBe(true); - expect(waits).toStrictEqual([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('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]); -}); + 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('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); -}); + const RUN_PATH = '.github/workflows/update-release-changelog.yml'; -test('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({})).toBe(undefined); -}); + it('finds the run the moving push triggered', () => { + expect( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: RUN_PATH, + listRunPaths: () => ['.github/workflows/other.yml', RUN_PATH], + }), + ).toBe(true); + }); -const staleWarning = getUnlistedCherryPicksWarning('8.20.0', { - baselineVersion: '8.19.0', - prNumbers: ['1'], -}); + 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('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.'); -}); + 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('removes a stale warning separated by extra blank lines', () => { - expect( - refreshGeneratedWarnings({ - existingBody: `Intro.\n\n\n${staleWarning}`, - version: '8.20.0', - }), - ).toBe('Intro.'); -}); + 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('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); -}); + 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(); + }); -test('leaves a CRLF body whose warning sits mid-body', () => { - const unlistedCherryPicks = { + const staleWarning = getUnlistedCherryPicksWarning('8.20.0', { 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, - }), - ).toBe(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.'); }); - 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'), - ); -}); + 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); }); - expect(result.section).toBe(EXCLUSION_SECTION); - expect(result.excludedPrNumbers).toStrictEqual([]); -}); + 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(); + }); + + 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(), + }); -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']), + 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'), + ); }); - expect(result.excludedPrNumbers).toStrictEqual(['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([]); }); - expect(result.section).toBe(EXCLUSION_SECTION); - expect(result.excludedPrNumbers).toStrictEqual([]); -}); + 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']), + }); -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.excludedPrNumbers).toStrictEqual(['2']); }); - expect(body).toMatch(/#5 was left out of 2\.0\.0/u); + 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(), + }); + + expect(result.section).toBe(EXCLUSION_SECTION); + expect(result.excludedPrNumbers).toStrictEqual([]); + }); + + 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 fda10a3f..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,17 +23,6 @@ "count": 9 } }, - ".github/actions/playwright-test-health-report/lib/report-health.test.mjs": { - "require-unicode-regexp": { - "count": 2 - }, - "vitest/no-conditional-in-test": { - "count": 3 - }, - "vitest/prefer-to-have-length": { - "count": 3 - } - }, ".github/actions/playwright-test-health-report/lib/slack-test-health-blocks.mjs": { "no-useless-escape": { "count": 1 @@ -294,179 +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": 13 - }, - "typescript/no-base-to-string": { - "count": 2 - }, - "typescript/no-unnecessary-type-assertion": { - "count": 1 - }, - "typescript/return-await": { - "count": 9 - }, - "vitest/consistent-test-it": { - "count": 35 - }, - "vitest/no-conditional-in-test": { - "count": 7 - }, - "vitest/prefer-to-be": { - "count": 1 - }, - "vitest/prefer-to-have-length": { - "count": 9 - }, - "vitest/require-top-level-describe": { - "count": 34 - } - }, - ".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/consistent-test-it": { - "count": 6 - }, - "vitest/require-top-level-describe": { - "count": 7 - } - }, - ".github/scripts/tests/release-section.test.mts": { - "typescript/explicit-function-return-type": { - "count": 1 - }, - "vitest/consistent-test-it": { - "count": 29 - }, - "vitest/no-conditional-in-test": { - "count": 1 - }, - "vitest/no-restricted-matchers": { - "count": 3 - }, - "vitest/prefer-to-be": { - "count": 4 - }, - "vitest/prefer-to-contain": { - "count": 2 - }, - "vitest/require-top-level-describe": { - "count": 29 - } - }, - ".github/scripts/tests/release-version-utils.test.mts": { - "vitest/consistent-test-it": { - "count": 4 - }, - "vitest/prefer-to-be": { - "count": 3 - }, - "vitest/require-top-level-describe": { - "count": 4 - } - }, - ".github/scripts/tests/retry.test.mts": { - "typescript/explicit-function-return-type": { - "count": 2 - }, - "typescript/return-await": { - "count": 2 - }, - "vitest/consistent-test-it": { - "count": 3 - }, - "vitest/no-conditional-in-test": { - "count": 1 - }, - "vitest/require-top-level-describe": { - "count": 3 - } - }, - ".github/scripts/tests/update-release-changelog-baseline.test.mts": { - "import/consistent-type-specifier-style": { - "count": 1 - }, - "typescript/explicit-function-return-type": { - "count": 1 - }, - "vitest/consistent-test-it": { - "count": 9 - }, - "vitest/prefer-to-contain": { - "count": 2 - }, - "vitest/prefer-to-have-length": { - "count": 1 - }, - "vitest/require-top-level-describe": { - "count": 9 - } - }, - ".github/scripts/tests/update-release-changelog-git.test.mts": { - "node/no-sync": { - "count": 14 - }, - "vitest/no-conditional-in-test": { - "count": 3 - }, - "vitest/prefer-to-be": { - "count": 4 - }, - "vitest/require-to-throw-message": { - "count": 1 - } - }, - ".github/scripts/tests/update-release-changelog-reachability.test.mts": { - "node/no-sync": { - "count": 3 - } - }, - ".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/consistent-test-it": { - "count": 61 - }, - "vitest/no-conditional-in-test": { - "count": 2 - }, - "vitest/prefer-to-be": { - "count": 8 - }, - "vitest/require-top-level-describe": { - "count": 61 - } - }, ".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 a4051147..cbae98fd 100644 --- a/oxlint.config.mts +++ b/oxlint.config.mts @@ -36,16 +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', '.github/**/*.test.{mjs,mts}'], - extends: [nodejs, vitest], - }, ], });