Skip to content

Commit 87a08d7

Browse files
authored
Merge pull request Real-Dev-Squad#277 from vikhyat187/grant-aws-access
Grant aws access - test cases
2 parents 0421825 + 50579bf commit 87a08d7

File tree

2 files changed

+170
-6
lines changed

2 files changed

+170
-6
lines changed

src/utils/awsAccess.ts

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@ import config from "../../config/config";
55
import { discordTextResponse } from "./discordResponse";
66
import { DISCORD_BASE_URL, AWS_IAM_SIGNIN_URL } from "../constants/urls";
77

8-
async function processAWSAccessRequest(
8+
export async function processAWSAccessRequest(
99
discordUserId: string,
1010
awsGroupId: string,
1111
env: env,
12-
TraceId: uuidv4,
12+
TraceId: string,
1313
channelId: number
1414
) {
1515
const authToken = await jwt.sign(
@@ -60,10 +60,6 @@ async function processAWSAccessRequest(
6060
});
6161
}
6262
} catch (err) {
63-
console.log(
64-
`[TraceId: ${TraceId}] Failed to grant AWS Access, error - `,
65-
err
66-
);
6763
return fetch(`${DISCORD_BASE_URL}/channels/${channelId}/messages`, {
6864
method: "POST",
6965
headers: {
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
import {
2+
grantAWSAccess,
3+
processAWSAccessRequest,
4+
} from "../../../src/utils/awsAccess";
5+
import { discordTextResponse } from "../../../src/utils/discordResponse";
6+
import jwt from "@tsndr/cloudflare-worker-jwt";
7+
import { AWS_IAM_SIGNIN_URL } from "../../../src/constants/urls";
8+
9+
jest.mock("node-fetch");
10+
jest.mock("@tsndr/cloudflare-worker-jwt");
11+
jest.mock("uuid", () => ({
12+
v4: jest.fn(() => "123e4567-e89b-12d3-a456-426614174000"),
13+
}));
14+
jest.mock("../../../src/utils/discordResponse", () => ({
15+
discordTextResponse: jest.fn(),
16+
}));
17+
18+
const discordUserId = "test-user";
19+
const awsGroupId = "test-group";
20+
const env = {
21+
BOT_PRIVATE_KEY: "mock-bot-private-key",
22+
DISCORD_TOKEN: "mock-discord-token",
23+
RDS_BASE_API_URL: "https://mock-api-url.com",
24+
};
25+
const channelId = 123456789;
26+
const traceId = "123424";
27+
const ctx = {
28+
waitUntil: jest.fn(),
29+
passThroughOnException: jest.fn(),
30+
};
31+
let fetchSpy: jest.SpyInstance;
32+
33+
beforeEach(() => {
34+
fetchSpy = jest.spyOn(global, "fetch");
35+
jest.spyOn(jwt, "sign").mockResolvedValue("mockJwtToken");
36+
});
37+
38+
afterEach(() => {
39+
jest.clearAllMocks();
40+
});
41+
42+
describe("ProcessAWSAccessRequest", () => {
43+
it("Should be a JSON response", async () => {
44+
const mockResponse = { content: "Processing your request..." };
45+
(discordTextResponse as jest.Mock).mockReturnValue(mockResponse);
46+
const response = await grantAWSAccess(
47+
discordUserId,
48+
awsGroupId,
49+
env,
50+
ctx,
51+
channelId
52+
);
53+
expect(discordTextResponse).toHaveBeenCalledWith(
54+
`[TraceId: 123e4567-e89b-12d3-a456-426614174000] <@${discordUserId}> Processing your request to grant AWS access.`
55+
);
56+
57+
// Ensure the function returns the mocked response
58+
expect(response).toEqual(mockResponse);
59+
expect(ctx.waitUntil).toHaveBeenCalled(); // Ensure waitUntil is called
60+
});
61+
62+
it("should handle succesful API call and grant access", async () => {
63+
const fetchCalls: string[] = [];
64+
fetchSpy.mockImplementation((url, options) => {
65+
fetchCalls.push(`Fetch call to: ${url}`);
66+
if (url.includes("/aws-access")) {
67+
return Promise.resolve({ ok: true } as Response);
68+
} else if (url.includes("/channels/123456789/messages")) {
69+
return Promise.resolve({ ok: true } as Response);
70+
}
71+
return Promise.reject(new Error("Unexpected URL"));
72+
});
73+
74+
await processAWSAccessRequest(
75+
discordUserId,
76+
awsGroupId,
77+
env as any,
78+
traceId,
79+
channelId
80+
);
81+
82+
console.log("Fetch calls made:", fetchCalls);
83+
84+
expect(fetchSpy).toHaveBeenCalledTimes(2);
85+
expect(fetchCalls).toHaveLength(2);
86+
87+
expect(fetchCalls[0]).toContain("/aws-access");
88+
expect(fetchCalls[1]).toContain("/channels/123456789/messages");
89+
// The last call should be the error message
90+
expect(fetchSpy).toHaveBeenNthCalledWith(
91+
1,
92+
expect.stringContaining("/aws-access"),
93+
expect.objectContaining({
94+
method: "POST",
95+
headers: expect.objectContaining({
96+
"Content-Type": "application/json",
97+
Authorization: "Bearer mockJwtToken",
98+
}),
99+
body: JSON.stringify({
100+
groupId: awsGroupId,
101+
userId: discordUserId,
102+
}),
103+
})
104+
);
105+
106+
expect(fetchSpy).toHaveBeenNthCalledWith(
107+
2,
108+
expect.stringContaining("/channels/123456789/messages"),
109+
expect.objectContaining({
110+
method: "POST",
111+
headers: expect.objectContaining({
112+
"Content-Type": "application/json",
113+
Authorization: "Bot mock-discord-token",
114+
}),
115+
body: JSON.stringify({
116+
content: `AWS access granted successfully <@${discordUserId}>! Please head over to AWS - ${AWS_IAM_SIGNIN_URL}.`,
117+
}),
118+
})
119+
);
120+
});
121+
122+
it("should handle API error", async () => {
123+
const fetchCalls: string[] = [];
124+
fetchSpy.mockImplementation((url, options) => {
125+
fetchCalls.push(`Fetch call to: ${url}`);
126+
if (url.includes("/aws-access")) {
127+
return Promise.resolve({
128+
ok: false,
129+
status: 500,
130+
statusText: "Internal Server Error",
131+
} as Response);
132+
} else if (url.includes(`/channels/123456789/messages`)) {
133+
return Promise.resolve({ ok: true } as Response);
134+
}
135+
return Promise.reject(new Error("Unexpected URL"));
136+
});
137+
138+
await processAWSAccessRequest(
139+
discordUserId,
140+
awsGroupId,
141+
env as any,
142+
traceId,
143+
channelId
144+
);
145+
146+
console.log("Fetch calls made:", fetchCalls);
147+
148+
expect(fetchSpy).toHaveBeenCalledTimes(2);
149+
expect(fetchCalls).toHaveLength(2);
150+
151+
expect(fetchCalls[0]).toContain("/aws-access");
152+
expect(fetchCalls[1]).toContain("/channels/123456789/messages");
153+
154+
expect(fetchSpy).toHaveBeenLastCalledWith(
155+
expect.stringContaining("/channels/123456789/messages"),
156+
expect.objectContaining({
157+
method: "POST",
158+
headers: expect.objectContaining({
159+
"Content-Type": "application/json",
160+
Authorization: "Bot mock-discord-token",
161+
}),
162+
body: JSON.stringify({
163+
content: `<@${discordUserId}> Error occurred while granting AWS access: 500 Internal Server Error`,
164+
}),
165+
})
166+
);
167+
});
168+
});

0 commit comments

Comments
 (0)