Skip to content

Commit f185a20

Browse files
committed
refactor: enhance GitHub API integration by adding user retrieval and updating related logic in tests
1 parent 366f045 commit f185a20

File tree

7 files changed

+47
-40
lines changed

7 files changed

+47
-40
lines changed

__tests__/helpers/octokit.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ type EndpointNames = {
1919
issues: 'createComment' | 'deleteComment' | 'listComments';
2020
pulls: 'listCommits' | 'listFiles';
2121
repos: 'getCommit' | 'listTags' | 'listReleases' | 'createRelease' | 'deleteRelease';
22+
users: 'getByUsername';
2223
};
2324

2425
// Type guard that ensures the method name is valid for the given namespace K.
@@ -164,12 +165,26 @@ export function resetMockStore() {
164165
headers: {},
165166
},
166167
},
168+
users: {
169+
getByUsername: {
170+
data: {
171+
login: 'github-actions[bot]',
172+
id: 41898282,
173+
type: 'Bot',
174+
site_admin: false,
175+
},
176+
status: 200,
177+
url: 'https://api.github.com/users/github-actions[bot]',
178+
headers: {},
179+
},
180+
},
167181
},
168182
implementations: {
169183
git: {},
170184
issues: {},
171185
pulls: {},
172186
repos: {},
187+
users: {},
173188
},
174189
};
175190
}
@@ -302,6 +317,9 @@ export function createDefaultOctokitMock(): OctokitRestApi {
302317
createRelease: vi.fn().mockImplementation(() => getMockResponse('repos.createRelease')),
303318
deleteRelease: vi.fn().mockImplementation(() => getMockResponse('repos.deleteRelease')),
304319
},
320+
users: {
321+
getByUsername: vi.fn().mockImplementation((params) => getMockResponse('users.getByUsername', params)),
322+
},
305323
},
306324
paginate: {
307325
iterator: <T>(

__tests__/pull-request.test.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,7 @@ import type { TerraformModule } from '@/terraform-module';
55
import { stubOctokitImplementation, stubOctokitReturnData } from '@/tests/helpers/octokit';
66
import { createMockTerraformModule } from '@/tests/helpers/terraform-module';
77
import type { GitHubRelease } from '@/types';
8-
import {
9-
BRANDING_COMMENT,
10-
PR_RELEASE_MARKER,
11-
PR_SUMMARY_MARKER,
12-
WIKI_STATUS,
13-
} from '@/utils/constants';
8+
import { BRANDING_COMMENT, PR_RELEASE_MARKER, PR_SUMMARY_MARKER, WIKI_STATUS } from '@/utils/constants';
149
import { debug, endGroup, info, startGroup } from '@actions/core';
1510
import { RequestError } from '@octokit/request-error';
1611
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -54,7 +49,6 @@ describe('pull-request', () => {
5449
context.useMockOctokit();
5550
});
5651

57-
5852
it('should return true when release marker is found in comments', async () => {
5953
stubOctokitReturnData('issues.listComments', {
6054
data: [
@@ -64,7 +58,7 @@ describe('pull-request', () => {
6458
],
6559
});
6660
expect(await hasReleaseComment()).toBe(true);
67-
})
61+
});
6862

6963
it('should return false when no release marker is found', async () => {
7064
stubOctokitReturnData('issues.listComments', {

__tests__/utils/github.test.ts

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { context } from '@/mocks/context';
22
import { getGitHubActionsBotEmail } from '@/utils/github';
3-
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
3+
import { beforeAll, describe, expect, it } from 'vitest';
44

55
describe('utils/github', () => {
66
describe('getGitHubActionsBotEmail - real API queries', () => {
@@ -11,15 +11,10 @@ describe('utils/github', () => {
1111
await context.useRealOctokit();
1212
});
1313

14-
afterAll(() => {
15-
context.useMockOctokit();
16-
});
17-
1814
it('should return the correct email format for GitHub.com public API', async () => {
1915
// This test uses the real GitHub API and expects the standard GitHub.com user ID
2016
// for the github-actions[bot] user, which is 41898282
21-
22-
// Act
17+
2318
const result = await getGitHubActionsBotEmail();
2419

2520
// Assert

__tests__/wiki.test.ts

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ describe('wiki', async () => {
205205

206206
afterAll(() => {
207207
vi.mocked(execFileSync).mockImplementation(vi.fn());
208+
vi.resetAllMocks(); // Unclears the console.log
208209
});
209210

210211
it('should generate all required wiki files', async () => {
@@ -259,11 +260,16 @@ describe('wiki', async () => {
259260
});
260261

261262
describe('commitAndPushWikiChanges()', () => {
262-
it('should commit and push changes when changes are detected', () => {
263+
beforeAll(() => {
264+
// Ensure we're using the mock octokit, not real one
265+
context.useMockOctokit();
266+
});
267+
268+
it('should commit and push changes when changes are detected', async () => {
263269
// Mock git status to indicate changes exist
264270
vi.mocked(execFileSync).mockImplementationOnce(() => Buffer.from('M _Sidebar.md\n'));
265271

266-
commitAndPushWikiChanges();
272+
await commitAndPushWikiChanges();
267273

268274
// Verify git commands were called in correct order
269275
const gitCalls = vi.mocked(execFileSync).mock.calls.map((call) => call?.[1]?.join(' ') || '');
@@ -284,11 +290,11 @@ describe('wiki', async () => {
284290
expect(endGroup).toHaveBeenCalled();
285291
});
286292

287-
it('should skip commit and push when no changes are detected', () => {
293+
it('should skip commit and push when no changes are detected', async () => {
288294
// Mock git status to indicate no changes
289295
vi.mocked(execFileSync).mockImplementationOnce(() => Buffer.from(''));
290296

291-
commitAndPushWikiChanges();
297+
await commitAndPushWikiChanges();
292298

293299
// Verify only status check was called
294300
const gitCalls = vi.mocked(execFileSync).mock.calls.map((call) => call?.[1]?.join(' ') || '');
@@ -301,23 +307,23 @@ describe('wiki', async () => {
301307
expect(endGroup).toHaveBeenCalled();
302308
});
303309

304-
it('should handle git command failures gracefully', () => {
310+
it('should handle git command failures gracefully', async () => {
305311
// Mock git status to indicate changes exist but make add command fail
306312
vi.mocked(execFileSync)
307313
.mockImplementationOnce(() => Buffer.from('M _Sidebar.md\n'))
308314
.mockImplementationOnce(() => {
309315
throw new Error('Git command failed');
310316
});
311317

312-
expect(() => commitAndPushWikiChanges()).toThrow('Git command failed');
318+
await expect(commitAndPushWikiChanges()).rejects.toThrow('Git command failed');
313319

314320
expect(startGroup).toHaveBeenCalledWith('Committing and pushing changes to wiki');
315321
expect(info).toHaveBeenCalledWith('Checking for changes in wiki repository');
316322
expect(info).toHaveBeenCalledWith('git status output: M _Sidebar.md');
317323
expect(endGroup).toHaveBeenCalled();
318324
});
319325

320-
it('should not use complete PR information in commit message', () => {
326+
it('should not use complete PR information in commit message', async () => {
321327
// Set up PR context with multiline body
322328
context.set({
323329
prBody: 'Line 1\nLine 2\nLine 3',
@@ -328,7 +334,7 @@ describe('wiki', async () => {
328334
// Mock git status to indicate changes exist
329335
vi.mocked(execFileSync).mockImplementationOnce(() => Buffer.from('M _Sidebar.md\n'));
330336

331-
commitAndPushWikiChanges();
337+
await commitAndPushWikiChanges();
332338

333339
// Verify commit message format
334340
const commitCall = vi.mocked(execFileSync).mock.calls.find((call) => call?.[1]?.includes('commit'));

src/pull-request.ts

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,7 @@ import { config } from '@/config';
33
import { context } from '@/context';
44
import { TerraformModule } from '@/terraform-module';
55
import type { CommitDetails, GitHubRelease, WikiStatusResult } from '@/types';
6-
import {
7-
BRANDING_COMMENT,
8-
PROJECT_URL,
9-
PR_RELEASE_MARKER,
10-
PR_SUMMARY_MARKER,
11-
WIKI_STATUS,
12-
} from '@/utils/constants';
6+
import { BRANDING_COMMENT, PROJECT_URL, PR_RELEASE_MARKER, PR_SUMMARY_MARKER, WIKI_STATUS } from '@/utils/constants';
137

148
import { getWikiLink } from '@/wiki';
159
import { debug, endGroup, info, startGroup } from '@actions/core';

src/utils/github.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,16 @@ import { GITHUB_ACTIONS_BOT_USERNAME } from '@/utils/constants';
44
/**
55
* Retrieves the GitHub Actions bot email address dynamically by querying the GitHub API.
66
* This function handles both GitHub.com and GitHub Enterprise Server environments.
7-
*
7+
*
88
* The email format follows GitHub's standard: {user_id}+{username}@users.noreply.github.com
9-
*
9+
*
1010
* @returns {Promise<string>} The GitHub Actions bot email address
1111
* @throws {Error} If the API request fails or the user information cannot be retrieved
1212
*/
1313
export async function getGitHubActionsBotEmail(): Promise<string> {
14-
const response = await context.octokit.rest.users.getByUsername({
15-
username: GITHUB_ACTIONS_BOT_USERNAME,
16-
});
17-
18-
return `${response.data.id}+${GITHUB_ACTIONS_BOT_USERNAME}@users.noreply.github.com`;
14+
const response = await context.octokit.rest.users.getByUsername({
15+
username: GITHUB_ACTIONS_BOT_USERNAME,
16+
});
17+
18+
return `${response.data.id}+${GITHUB_ACTIONS_BOT_USERNAME}@users.noreply.github.com`;
1919
}

src/wiki.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -583,11 +583,11 @@ export async function commitAndPushWikiChanges(): Promise<void> {
583583

584584
if (status !== null && status.toString().trim() !== '') {
585585
// There are changes, commit and push
586-
const botEmail = await getGitHubActionsBotEmail();
587-
586+
const githubActionsBotEmail = await getGitHubActionsBotEmail();
587+
588588
for (const cmd of [
589589
['config', '--local', 'user.name', GITHUB_ACTIONS_BOT_NAME],
590-
['config', '--local', 'user.email', botEmail],
590+
['config', '--local', 'user.email', githubActionsBotEmail],
591591
['add', '.'],
592592
['commit', '-m', commitMessage.trim()],
593593
['push', 'origin'],

0 commit comments

Comments
 (0)