test: Google CalendarService test (#14793)

This commit is contained in:
Hariom Balhara authored and GitHub committed 2024-05-06 12:33:16 +05:30
1 parent e404f7eb88
commit 4f57e3201d
4 files changed
+235 -63

No files matched your search

@@ -1,12 +1,11 @@
import prismaMock from "../../../../tests/libs/__mocks__/prismaMock";
import prismock from "../../../../tests/libs/__mocks__/prisma";
import oAuthManagerMock, { defaultMockOAuthManager } from "../../tests/__mocks__/OAuthManager";
import { googleapisMock, setCredentialsMock } from "./__mocks__/googleapis";
import { afterEach, expect, test, vi } from "vitest";
import { expect, test, vi } from "vitest";
import "vitest-fetch-mock";
import CalendarService from "./CalendarService";
afterEach(() => {
vi.resetAllMocks();
});
import CalendarService, { getTimeMax, getTimeMin } from "./CalendarService";
vi.mock("@calcom/features/flags/server/utils", () => ({
getFeatureFlag: vi.fn().mockReturnValue(true),
@@ -19,8 +18,9 @@ vi.mock("./getGoogleAppKeys", () => ({
redirect_uris: ["http://localhost:3000/api/integrations/googlecalendar/callback"],
}),
}));
googleapisMock.google;
const googleTestCredential = {
const googleTestCredentialKey = {
scope: "https://www.googleapis.com/auth/calendar.events",
token_type: "Bearer",
expiry_date: 1625097600000,
@@ -28,15 +28,12 @@ const googleTestCredential = {
refresh_token: "",
};
const testCredential = {
appId: "test",
id: 1,
invalid: false,
key: googleTestCredential,
type: "test",
userId: 1,
user: { email: "[email protected]" },
teamId: 1,
const getSampleCredential = () => {
return {
invalid: false,
key: googleTestCredentialKey,
type: "test",
};
};
const testSelectedCalendar = {
@@ -45,53 +42,160 @@ const testSelectedCalendar = {
externalId: "[email protected]",
};
const testFreeBusyResponse = {
kind: "calendar#freeBusy",
timeMax: "2024-01-01T20:59:59.000Z",
timeMin: "2023-11-30T20:00:00.000Z",
calendars: {
"[email protected]": {
busy: [
{ end: "2023-12-01T19:00:00Z", start: "2023-12-01T18:00:00Z" },
{ end: "2023-12-04T19:00:00Z", start: "2023-12-04T18:00:00Z" },
],
test("Calendar Cache is being read and updated", async () => {
const credentialInDb1 = await createCredentialInDb();
const dateFrom1 = new Date().toISOString();
const dateTo1 = new Date().toISOString();
// Create cache
await prismock.calendarCache.create({
data: {
credentialId: credentialInDb1.id,
key: JSON.stringify({
timeMin: getTimeMin(dateFrom1),
timeMax: getTimeMax(dateTo1),
items: [{ id: testSelectedCalendar.externalId }],
}),
value: {
calendars: [
{
busy: [
{
start: "2023-12-01T18:00:00Z",
end: "2023-12-01T19:00:00Z",
},
],
},
],
},
expiresAt: String(Date.now() + 10000),
},
"[email protected]": { busy: [] },
},
};
});
const calendarCacheResponse = {
key: "dummy",
expiresAt: new Date(),
credentialId: 1,
value: testFreeBusyResponse,
};
oAuthManagerMock.OAuthManager = defaultMockOAuthManager;
const calendarService = new CalendarService(credentialInDb1);
test("Calendar Cache is being called", async () => {
prismaMock.calendarCache.findUnique
// First call won't have a cache
.mockResolvedValueOnce(null)
// Second call will have a cache
.mockResolvedValueOnce(calendarCacheResponse);
// Test cache hit
const data = await calendarService.getAvailability(dateFrom1, dateTo1, [testSelectedCalendar]);
expect(data).toEqual([
{
start: "2023-12-01T18:00:00Z",
end: "2023-12-01T19:00:00Z",
},
]);
// prismaMock.calendarCache.create.mock.
const calendarService = new CalendarService(testCredential);
vi.spyOn(calendarService, "authedCalendar").mockReturnValue({
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore - Mocking the authedCalendar so can't return the actual response
freebusy: {
query: vi.fn().mockReturnValue({
data: testFreeBusyResponse,
const credentialInDb2 = await createCredentialInDb();
const dateFrom2 = new Date(Date.now()).toISOString();
// Tweak date so that it's a cache miss
const dateTo2 = new Date(Date.now() + 100000000).toISOString();
const calendarService2 = new CalendarService(credentialInDb2);
// Test Cache Miss
await calendarService2.getAvailability(dateFrom2, dateTo2, [testSelectedCalendar]);
// Expect cache to be updated in case of a MISS
const calendarCache = await prismock.calendarCache.findFirst({
where: {
credentialId: credentialInDb2.id,
key: JSON.stringify({
timeMin: getTimeMin(dateFrom2),
timeMax: getTimeMax(dateTo2),
items: [{ id: testSelectedCalendar.externalId }],
}),
},
});
await calendarService.getAvailability(new Date().toISOString(), new Date().toISOString(), [
testSelectedCalendar,
]);
await calendarService.getAvailability(new Date().toISOString(), new Date().toISOString(), [
testSelectedCalendar,
]);
expect(prismaMock.calendarCache.findUnique).toHaveBeenCalled();
expect(prismaMock.calendarCache.upsert).toHaveBeenCalledOnce();
expect(calendarCache?.value).toEqual({ calendars: [] });
});
test("`updateTokenObject` should update credential in DB as well as myGoogleAuth", async () => {
const credentialInDb = await createCredentialInDb();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let updateTokenObject: any;
oAuthManagerMock.OAuthManager = vi.fn().mockImplementation((arg) => {
updateTokenObject = arg.updateTokenObject;
return {
getTokenObjectOrFetch: vi.fn().mockImplementation(() => {
return {
token: {
access_token: "FAKE_ACCESS_TOKEN",
},
};
}),
request: vi.fn().mockResolvedValue({
json: [],
}),
};
});
const calendarService = new CalendarService(credentialInDb);
await calendarService.listCalendars();
const newTokenObject = {
access_token: "NEW_FAKE_ACCESS_TOKEN",
};
// Scenario: OAuthManager causes `updateTokenObject` to be called
await updateTokenObject(newTokenObject);
const newCredential = await prismock.credential.findFirst({
where: {
id: credentialInDb.id,
},
});
// Expect update in DB
expect(newCredential).toEqual(
expect.objectContaining({
key: newTokenObject,
})
);
// Expect update in myGoogleAuth credentials
expect(setCredentialsMock).toHaveBeenCalledWith(newTokenObject);
});
async function createCredentialInDb() {
const user = await prismock.user.create({
data: {
email: "",
},
});
const app = await prismock.app.create({
data: {
slug: "google-calendar",
dirName: "google-calendar",
},
});
const credential = {
...getSampleCredential(),
key: {
...googleTestCredentialKey,
expiry_date: Date.now() - 1000,
},
};
const credentialInDb = await prismock.credential.create({
data: {
...credential,
user: {
connect: {
id: user.id,
},
},
app: {
connect: {
slug: app.slug,
},
},
},
include: {
user: true,
},
});
return credentialInDb;
}
@@ -38,7 +38,6 @@ import { metadata } from "../_metadata";
import { getGoogleAppKeys } from "./getGoogleAppKeys";
const log = logger.getSubLogger({ prefix: ["app-store/googlecalendar/lib/CalendarService"] });
interface GoogleCalError extends Error {
code?: number;
}
@@ -47,13 +46,13 @@ const ONE_MINUTE_MS = 60 * 1000;
const CACHING_TIME = ONE_MINUTE_MS;
/** Expand the start date to the start of the month */
function getTimeMin(timeMin: string) {
export function getTimeMin(timeMin: string) {
const dateMin = new Date(timeMin);
return new Date(dateMin.getFullYear(), dateMin.getMonth(), 1, 0, 0, 0, 0).toISOString();
}
/** Expand the end date to the end of the month */
function getTimeMax(timeMax: string) {
export function getTimeMax(timeMax: string) {
const dateMax = new Date(timeMax);
return new Date(dateMax.getFullYear(), dateMax.getMonth() + 1, 0, 0, 0, 0, 0).toISOString();
}
@@ -522,7 +521,6 @@ export default class GoogleCalendarService implements Calendar {
}): Promise<EventBusyDate[] | null> {
const calendar = await this.authedCalendar();
const calendarCacheEnabled = await getFeatureFlag(prisma, "calendar-cache");
let freeBusyResult: calendar_v3.Schema$FreeBusyResponse = {};
if (!calendarCacheEnabled) {
this.log.warn("Calendar Cache is disabled - Skipping");
@@ -601,7 +599,7 @@ export default class GoogleCalendarService implements Calendar {
dateTo: string,
selectedCalendars: IntegrationCalendar[]
): Promise<EventBusyDate[]> {
this.log.debug("Getting availability");
this.log.debug("Getting availability", safeStringify({ dateFrom, dateTo, selectedCalendars }));
const calendar = await this.authedCalendar();
const selectedCalendarIds = selectedCalendars
.filter((e) => e.integration === this.integrationName)
@@ -0,0 +1,35 @@
import type * as googleapis from "googleapis";
import { beforeEach, vi } from "vitest";
import { mockDeep, mockReset } from "vitest-mock-extended";
vi.mock("googleapis", () => googleapisMock);
beforeEach(() => {
mockReset(googleapisMock);
});
const googleapisMock = mockDeep<typeof googleapis>({
fallbackMockImplementation: (...args) => {
console.log(args);
throw new Error("Unimplemented");
},
});
const setCredentialsMock = vi.fn();
googleapisMock.google = {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
calendar: vi.fn().mockReturnValue({}),
auth: {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
OAuth2: function MockGoogleOAuth2() {
return {
setCredentials: setCredentialsMock,
};
},
},
};
export default googleapisMock;
export { googleapisMock, setCredentialsMock };
@@ -0,0 +1,35 @@
import { beforeEach, vi } from "vitest";
import { mockReset, mockDeep } from "vitest-mock-extended";
import type * as OAuthManager from "../../_utils/oauth/OAuthManager";
vi.mock("../../_utils/oauth/OAuthManager", () => oAuthManagerMock);
beforeEach(() => {
mockReset(oAuthManagerMock);
});
const oAuthManagerMock = mockDeep<typeof OAuthManager>({
fallbackMockImplementation: () => {
throw new Error("Unimplemented");
},
});
export default oAuthManagerMock;
const defaultMockOAuthManager = vi.fn().mockImplementation(() => {
return {
getTokenObjectOrFetch: vi.fn().mockImplementation(() => {
return {
token: {
access_token: "FAKE_ACCESS_TOKEN",
},
};
}),
request: vi.fn().mockResolvedValue({
json: {
calendars: [],
},
}),
};
});
export { oAuthManagerMock, defaultMockOAuthManager };