Skip to content

Commit

Permalink
adding msw to lib tests (#898)
Browse files Browse the repository at this point in the history
* added config and setup for lib tests
* added config and setup for lib/libs/emails/content tests
* mocked getting security credentials from AWS
* mocked signing into Cognito
* mocked verifying identity with Cognito
* mocked getting exports from CloudFormation
* mocked getting a document from Opensearch
* mocked searching Opensearch for items, appk, and changelogs
* mocked getting secrets from AWS
* updated tests to use new mocks
  • Loading branch information
thetif authored Dec 17, 2024
1 parent d4b2070 commit 2b1f40a
Show file tree
Hide file tree
Showing 64 changed files with 1,773 additions and 955 deletions.
2 changes: 1 addition & 1 deletion bin/cli/src/commands/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ async function getLambdasWithTags(tags: Tag[]): Promise<string[]> {
const functionData = await lambdaClient.send(functionCommand);
return functionData.Configuration?.FunctionName || "";
} catch {
console.log(`Ecluding function ${arn}.`);
console.log(`Excluding function ${arn}.`);
return "";
}
}),
Expand Down
Binary file modified bun.lockb
Binary file not shown.
7 changes: 2 additions & 5 deletions lib/lambda/getAttachmentUrl.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { handleOpensearchError } from "./utils";
import { response } from "libs/handler-lib";
import { APIGatewayEvent } from "aws-lambda";
import { STSClient, AssumeRoleCommand } from "@aws-sdk/client-sts";
Expand Down Expand Up @@ -83,11 +84,7 @@ export const handler = async (event: APIGatewayEvent) => {
body: { url },
});
} catch (error) {
console.error({ error });
return response({
statusCode: 500,
body: { message: "Internal server error" },
});
return response(handleOpensearchError(error));
}
};

Expand Down
7 changes: 2 additions & 5 deletions lib/lambda/getCpocs.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { handleOpensearchError } from "./utils";
import { APIGatewayEvent } from "aws-lambda";
import * as os from "libs/opensearch-lib";
import { response } from "libs/handler-lib";
Expand Down Expand Up @@ -46,11 +47,7 @@ export const getCpocs = async (event: APIGatewayEvent) => {
body: result,
});
} catch (err) {
console.error({ err });
return response({
statusCode: 500,
body: { message: "Internal server error" },
});
return response(handleOpensearchError(err))
}
};

Expand Down
113 changes: 45 additions & 68 deletions lib/lambda/getPackageActions.test.ts
Original file line number Diff line number Diff line change
@@ -1,100 +1,77 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { APIGatewayEvent } from "aws-lambda";
import { handler } from "./getPackageActions";
import { response } from "libs/handler-lib";
import { getAvailableActions } from "shared-utils";
import { getPackage } from "../libs/api/package/getPackage";
import { getRequestContext } from "mocks";
import {
getAuthDetails,
isAuthorizedToGetPackageActions,
lookupUserAttributes,
} from "../libs/api/auth/user";

vi.mock("libs/handler-lib", () => ({
response: vi.fn(),
}));

vi.mock("shared-utils", () => ({
getAvailableActions: vi.fn(),
}));

vi.mock("../libs/api/package/getPackage", () => ({
getPackage: vi.fn(),
}));

vi.mock("../libs/api/auth/user", () => ({
getAuthDetails: vi.fn(),
isAuthorizedToGetPackageActions: vi.fn(),
lookupUserAttributes: vi.fn(),
}));
GET_ERROR_ITEM_ID,
HI_TEST_ITEM_ID,
NOT_FOUND_ITEM_ID,
WITHDRAWN_CHANGELOG_ITEM_ID,
} from "mocks/data/items";
import { describe, expect, it } from "vitest";
import { handler } from "./getPackageActions";

describe("getPackageActions Handler", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("should return 400 if event body is missing", async () => {
const event = {} as APIGatewayEvent;

await handler(event);
const res = await handler(event);

expect(response).toHaveBeenCalledWith({
statusCode: 400,
body: { message: "Event body required" },
});
expect(res).toBeTruthy();
expect(res.statusCode).toEqual(400);
});

it("should return 401 if not authorized to view resources from the state", async () => {
const packageData = { found: true, _source: { state: "test-state" } };
(getPackage as vi.Mock).mockResolvedValueOnce(packageData);
(isAuthorizedToGetPackageActions as vi.Mock).mockResolvedValueOnce(false);
const event = {
body: JSON.stringify({ id: HI_TEST_ITEM_ID }),
requestContext: getRequestContext(),
} as APIGatewayEvent;

const res = await handler(event);

expect(res).toBeTruthy();
expect(res.statusCode).toEqual(401);
expect(res.body).toEqual(
JSON.stringify({ message: "Not authorized to view resources from this state" }),
);
});

it("should return 404 if the package is not found", async () => {
const event = {
body: JSON.stringify({ id: "test-id" }),
body: JSON.stringify({ id: NOT_FOUND_ITEM_ID }),
requestContext: getRequestContext(),
} as APIGatewayEvent;

await handler(event);
const res = await handler(event);

expect(response).toHaveBeenCalledWith({
statusCode: 401,
body: { message: "Not authorized to view resources from this state" },
});
expect(res).toBeTruthy();
expect(res.statusCode).toEqual(404);
expect(res.body).toEqual(JSON.stringify({ message: "No record found for the given id" }));
});

it("should return 200 with available actions if authorized and package is found", async () => {
const packageData = { found: true, _source: { state: "test-state" } };
const userAttributes = { userId: "test-user", poolId: "test-pool" };
const actions = ["action1", "action2"];
(getPackage as vi.Mock).mockResolvedValueOnce(packageData);
(isAuthorizedToGetPackageActions as vi.Mock).mockResolvedValueOnce(true);
(getAuthDetails as vi.Mock).mockReturnValueOnce(userAttributes);
(lookupUserAttributes as vi.Mock).mockResolvedValueOnce(userAttributes);
(getAvailableActions as vi.Mock).mockReturnValueOnce(actions);

const event = {
body: JSON.stringify({ id: "test-id" }),
body: JSON.stringify({ id: WITHDRAWN_CHANGELOG_ITEM_ID }),
requestContext: getRequestContext(),
} as APIGatewayEvent;

await handler(event);
const res = await handler(event);

expect(response).toHaveBeenCalledWith({
statusCode: 200,
body: { actions },
});
expect(res).toBeTruthy();
expect(res.statusCode).toEqual(200);
expect(res.body).toEqual(JSON.stringify({ actions: [] }));
});

it("should handle errors during processing", async () => {
(getPackage as vi.Mock).mockRejectedValueOnce(new Error("Test error"));

const event = {
body: JSON.stringify({ id: "test-id" }),
body: JSON.stringify({ id: GET_ERROR_ITEM_ID }),
requestContext: getRequestContext(),
} as APIGatewayEvent;

await handler(event);
const res = await handler(event);

expect(response).toHaveBeenCalledWith({
statusCode: 500,
body: { message: "Internal server error" },
});
expect(res).toBeTruthy();
expect(res.statusCode).toEqual(500);
expect(res.body).toEqual(
JSON.stringify({ error: "Internal server error", message: "Response Error" }),
);
});
});
21 changes: 7 additions & 14 deletions lib/lambda/getPackageActions.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { APIGatewayEvent } from "aws-lambda";
import { response } from "libs/handler-lib";
import { getAvailableActions } from "shared-utils";
import { getPackage } from "../libs/api/package/getPackage";
import { handleOpensearchError } from "./utils";
import {
getAuthDetails,
isAuthorizedToGetPackageActions,
lookupUserAttributes,
} from "../libs/api/auth/user";
import { response } from "libs/handler-lib";
import { getPackage } from "../libs/api/package/getPackage";

export const getPackageActions = async (event: APIGatewayEvent) => {
if (!event.body) {
Expand All @@ -15,12 +16,13 @@ export const getPackageActions = async (event: APIGatewayEvent) => {
body: { message: "Event body required" },
});
}
const body = JSON.parse(event.body);

try {
const body = JSON.parse(event.body);

const result = await getPackage(body.id);

if (result === undefined) {
if (result === undefined || !result.found) {
return response({
statusCode: 404,
body: { message: "No record found for the given id" },
Expand All @@ -35,11 +37,6 @@ export const getPackageActions = async (event: APIGatewayEvent) => {
body: { message: "Not authorized to view resources from this state" },
});

if (!result.found)
return response({
statusCode: 404,
body: { message: "No record found for the given id" },
});
const authDetails = getAuthDetails(event);
const userAttr = await lookupUserAttributes(authDetails.userId, authDetails.poolId);

Expand All @@ -50,11 +47,7 @@ export const getPackageActions = async (event: APIGatewayEvent) => {
},
});
} catch (err) {
console.error({ err });
return response({
statusCode: 500,
body: { message: "Internal server error" },
});
return response(handleOpensearchError(err));
}
};
export const handler = getPackageActions;
7 changes: 2 additions & 5 deletions lib/lambda/getSubTypes.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { handleOpensearchError } from "./utils";
import { APIGatewayEvent } from "aws-lambda";
import * as os from "libs/opensearch-lib";
import { response } from "libs/handler-lib";
Expand Down Expand Up @@ -77,11 +78,7 @@ export const getSubTypes = async (event: APIGatewayEvent) => {
body: result,
});
} catch (err) {
console.error({ err });
return response({
statusCode: 500,
body: { message: "Internal server error" },
});
return response(handleOpensearchError(err))
}
};

Expand Down
7 changes: 2 additions & 5 deletions lib/lambda/getTypes.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { handleOpensearchError } from "./utils";
import { APIGatewayEvent } from "aws-lambda";
import * as os from "libs/opensearch-lib";
import { response } from "libs/handler-lib";
Expand Down Expand Up @@ -69,11 +70,7 @@ export const getTypes = async (event: APIGatewayEvent) => {
body: result,
});
} catch (err) {
console.error({ err });
return response({
statusCode: 500,
body: { message: "Internal server error" },
});
return response(handleOpensearchError(err));
}
};

Expand Down
Loading

0 comments on commit 2b1f40a

Please sign in to comment.