test: Booking flow App failure and ics file tests and improved logging (#11646)

This commit is contained in:
Hariom Balhara authored and GitHub committed 2023-10-02 16:21:04 +05:30
1 parent 07bfaec24e
commit 3ca7456885
17 files changed
+513 -239

No files matched your search

@@ -12,6 +12,7 @@ import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import { handleStripePaymentSuccess } from "@calcom/features/ee/payments/api/webhook";
import type { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import type { SchedulingType } from "@calcom/prisma/enums";
import type { BookingStatus } from "@calcom/prisma/enums";
import type { NewCalendarEventType } from "@calcom/types/Calendar";
@@ -19,6 +20,8 @@ import type { EventBusyDate } from "@calcom/types/Calendar";
import { getMockPaymentService } from "./MockPaymentService";
logger.setSettings({ minLevel: "silly" });
const log = logger.getChildLogger({ prefix: ["[bookingScenario]"] });
type App = {
slug: string;
dirName: string;
@@ -123,7 +126,6 @@ const Timezones = {
"+5:30": "Asia/Kolkata",
"+6:00": "Asia/Dhaka",
};
logger.setSettings({ minLevel: "silly" });
async function addEventTypesToDb(
eventTypes: (Omit<Prisma.EventTypeCreateInput, "users" | "worflows" | "destinationCalendar"> & {
@@ -135,11 +137,11 @@ async function addEventTypesToDb(
destinationCalendar?: any;
})[]
) {
logger.silly("TestData: Add EventTypes to DB", JSON.stringify(eventTypes));
log.silly("TestData: Add EventTypes to DB", JSON.stringify(eventTypes));
await prismock.eventType.createMany({
data: eventTypes,
});
logger.silly(
log.silly(
"TestData: All EventTypes in DB are",
JSON.stringify({
eventTypes: await prismock.eventType.findMany({
@@ -197,7 +199,7 @@ async function addEventTypes(eventTypes: InputEventType[], usersStore: InputUser
: eventType.destinationCalendar,
};
});
logger.silly("TestData: Creating EventType", JSON.stringify(eventTypesWithUsers));
log.silly("TestData: Creating EventType", JSON.stringify(eventTypesWithUsers));
await addEventTypesToDb(eventTypesWithUsers);
}
@@ -216,7 +218,7 @@ async function addBookingsToDb(
await prismock.booking.createMany({
data: bookings,
});
logger.silly(
log.silly(
"TestData: Booking as in DB",
JSON.stringify({
bookings: await prismock.booking.findMany({
@@ -229,7 +231,7 @@ async function addBookingsToDb(
}
async function addBookings(bookings: InputBooking[]) {
logger.silly("TestData: Creating Bookings", JSON.stringify(bookings));
log.silly("TestData: Creating Bookings", JSON.stringify(bookings));
const allBookings = [...bookings].map((booking) => {
if (booking.references) {
addBookingReferencesToDB(
@@ -277,19 +279,22 @@ async function addWebhooksToDb(webhooks: any[]) {
}
async function addWebhooks(webhooks: InputWebhook[]) {
logger.silly("TestData: Creating Webhooks", webhooks);
log.silly("TestData: Creating Webhooks", safeStringify(webhooks));
await addWebhooksToDb(webhooks);
}
async function addUsersToDb(users: (Prisma.UserCreateInput & { schedules: Prisma.ScheduleCreateInput[] })[]) {
logger.silly("TestData: Creating Users", JSON.stringify(users));
log.silly("TestData: Creating Users", JSON.stringify(users));
await prismock.user.createMany({
data: users,
});
logger.silly("Added users to Db", {
allUsers: await prismock.user.findMany(),
});
log.silly(
"Added users to Db",
safeStringify({
allUsers: await prismock.user.findMany(),
})
);
}
async function addUsers(users: InputUser[]) {
@@ -339,7 +344,7 @@ async function addUsers(users: InputUser[]) {
}
export async function createBookingScenario(data: ScenarioData) {
logger.silly("TestData: Creating Scenario", JSON.stringify({ data }));
log.silly("TestData: Creating Scenario", JSON.stringify({ data }));
await addUsers(data.users);
const eventType = await addEventTypes(data.eventTypes, data.users);
@@ -690,6 +695,7 @@ export function enableEmailFeature() {
}
export function mockNoTranslations() {
log.silly("Mocking i18n.getTranslation to return identity function");
// @ts-expect-error FIXME
i18nMock.getTranslation.mockImplementation(() => {
return new Promise((resolve) => {
@@ -707,10 +713,14 @@ export function mockCalendar(
metadataLookupKey: keyof typeof appStoreMetadata,
calendarData?: {
create?: {
id?: string;
uid?: string;
iCalUID?: string;
};
update?: {
id?: string;
uid: string;
iCalUID?: string;
};
busySlots?: { start: `${string}Z`; end: `${string}Z` }[];
creationCrash?: boolean;
@@ -727,7 +737,7 @@ export function mockCalendar(
uid: "UPDATED_MOCK_ID",
},
};
logger.silly(`Mocking ${appStoreLookupKey} on appStoreMock`);
log.silly(`Mocking ${appStoreLookupKey} on appStoreMock`);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const createEventCalls: any[] = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -745,13 +755,15 @@ export function mockCalendar(
throw new Error("MockCalendarService.createEvent fake error");
}
const [calEvent, credentialId] = rest;
logger.silly("mockCalendar.createEvent", JSON.stringify({ calEvent, credentialId }));
log.silly("mockCalendar.createEvent", JSON.stringify({ calEvent, credentialId }));
createEventCalls.push(rest);
return Promise.resolve({
type: app.type,
additionalInfo: {},
uid: "PROBABLY_UNUSED_UID",
id: normalizedCalendarData.create?.uid || "FALLBACK_MOCK_ID",
// A Calendar is always expected to return an id.
id: normalizedCalendarData.create?.id || "FALLBACK_MOCK_CALENDAR_EVENT_ID",
iCalUID: normalizedCalendarData.create?.iCalUID,
// Password and URL seems useless for CalendarService, plan to remove them if that's the case
password: "MOCK_PASSWORD",
url: "https://UNUSED_URL",
@@ -763,13 +775,15 @@ export function mockCalendar(
throw new Error("MockCalendarService.updateEvent fake error");
}
const [uid, event, externalCalendarId] = rest;
logger.silly("mockCalendar.updateEvent", JSON.stringify({ uid, event, externalCalendarId }));
log.silly("mockCalendar.updateEvent", JSON.stringify({ uid, event, externalCalendarId }));
// eslint-disable-next-line prefer-rest-params
updateEventCalls.push(rest);
return Promise.resolve({
type: app.type,
additionalInfo: {},
uid: "PROBABLY_UNUSED_UID",
iCalUID: normalizedCalendarData.update?.iCalUID,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
id: normalizedCalendarData.update?.uid || "FALLBACK_MOCK_ID",
// Password and URL seems useless for CalendarService, plan to remove them if that's the case
@@ -797,14 +811,7 @@ export function mockCalendar(
export function mockCalendarToHaveNoBusySlots(
metadataLookupKey: keyof typeof appStoreMetadata,
calendarData?: {
create: {
uid?: string;
};
update?: {
uid: string;
};
}
calendarData?: Parameters<typeof mockCalendar>[1]
) {
calendarData = calendarData || {
create: {
@@ -848,10 +855,7 @@ export function mockVideoApp({
password: "MOCK_PASS",
url: `http://mock-${metadataLookupKey}.example.com`,
};
logger.silly(
"mockSuccessfulVideoMeetingCreation",
JSON.stringify({ metadataLookupKey, appStoreLookupKey })
);
log.silly("mockSuccessfulVideoMeetingCreation", JSON.stringify({ metadataLookupKey, appStoreLookupKey }));
const createMeetingCalls: any[] = [];
const updateMeetingCalls: any[] = [];
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
@@ -888,7 +892,7 @@ export function mockVideoApp({
if (!calEvent.organizer) {
throw new Error("calEvent.organizer is not defined");
}
logger.silly(
log.silly(
"mockSuccessfulVideoMeetingCreation.updateMeeting",
JSON.stringify({ bookingRef, calEvent })
);
@@ -1019,7 +1023,7 @@ export async function mockPaymentSuccessWebhookFromStripe({ externalId }: { exte
try {
await handleStripePaymentSuccess(getMockedStripePaymentEvent({ paymentIntentId: externalId }));
} catch (e) {
logger.silly("mockPaymentSuccessWebhookFromStripe:catch", JSON.stringify(e));
log.silly("mockPaymentSuccessWebhookFromStripe:catch", JSON.stringify(e));
webhookResponse = e as HttpError;
}
+92 -8
View File
@@ -1,10 +1,12 @@
import prismaMock from "../../../../../tests/libs/__mocks__/prisma";
import type { WebhookTriggerEvents, Booking, BookingReference } from "@prisma/client";
import ical from "node-ical";
import { expect } from "vitest";
import "vitest-fetch-mock";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { BookingStatus } from "@calcom/prisma/enums";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { Fixtures } from "@calcom/web/test/fixtures/fixtures";
@@ -15,7 +17,19 @@ declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Matchers<R> {
toHaveEmail(expectedEmail: { htmlToContain?: string; to: string }, to: string): R;
toHaveEmail(
expectedEmail: {
//TODO: Support email HTML parsing to target specific elements
htmlToContain?: string;
to: string;
noIcs?: true;
ics?: {
filename: string;
iCalUID: string;
};
},
to: string
): R;
}
}
}
@@ -27,11 +41,18 @@ expect.extend({
//TODO: Support email HTML parsing to target specific elements
htmlToContain?: string;
to: string;
ics: {
filename: string;
iCalUID: string;
};
noIcs: true;
},
to: string
) {
const testEmail = emails.get().find((email) => email.to.includes(to));
const emailsToLog = emails.get().map((email) => ({ to: email.to, html: email.html }));
const emailsToLog = emails
.get()
.map((email) => ({ to: email.to, html: email.html, ics: email.icalEvent }));
if (!testEmail) {
logger.silly("All Emails", JSON.stringify({ numEmails: emailsToLog.length, emailsToLog }));
return {
@@ -39,11 +60,20 @@ expect.extend({
message: () => `No email sent to ${to}`,
};
}
const ics = testEmail.icalEvent;
const icsObject = ics?.content ? ical.sync.parseICS(ics?.content) : null;
let isHtmlContained = true;
let isToAddressExpected = true;
const isIcsFilenameExpected = expectedEmail.ics ? ics?.filename === expectedEmail.ics.filename : true;
const isIcsUIDExpected = expectedEmail.ics
? !!(icsObject ? icsObject[expectedEmail.ics.iCalUID] : null)
: true;
if (expectedEmail.htmlToContain) {
isHtmlContained = testEmail.html.includes(expectedEmail.htmlToContain);
}
isToAddressExpected = expectedEmail.to === testEmail.to;
if (!isHtmlContained || !isToAddressExpected) {
@@ -51,12 +81,29 @@ expect.extend({
}
return {
pass: isHtmlContained && isToAddressExpected,
pass:
isHtmlContained &&
isToAddressExpected &&
(expectedEmail.noIcs ? true : isIcsFilenameExpected && isIcsUIDExpected),
message: () => {
if (!isHtmlContained) {
return `Email HTML is not as expected. Expected:"${expectedEmail.htmlToContain}" isn't contained in "${testEmail.html}"`;
}
return `Email To address is not as expected. Expected:${expectedEmail.to} isn't equal to ${testEmail.to}`;
if (!isToAddressExpected) {
return `Email To address is not as expected. Expected:${expectedEmail.to} isn't equal to ${testEmail.to}`;
}
if (!isIcsFilenameExpected) {
return `ICS Filename is not as expected. Expected:${expectedEmail.ics.filename} isn't equal to ${ics?.filename}`;
}
if (!isIcsUIDExpected) {
return `ICS UID is not as expected. Expected:${
expectedEmail.ics.iCalUID
} isn't present in ${JSON.stringify(icsObject)}`;
}
throw new Error("Unknown error");
},
};
},
@@ -73,7 +120,7 @@ export function expectWebhookToHaveBeenCalledWith(
const webhooksToSubscriberUrl = fetchCalls.filter((call) => {
return call[0] === subscriberUrl;
});
logger.silly("Scanning fetchCalls for webhook", fetchCalls);
logger.silly("Scanning fetchCalls for webhook", safeStringify(fetchCalls));
const webhookFetchCall = webhooksToSubscriberUrl.find((call) => {
const body = call[1]?.body;
const parsedBody = JSON.parse((body as string) || "{}");
@@ -135,15 +182,21 @@ export function expectSuccessfulBookingCreationEmails({
emails,
organizer,
booker,
iCalUID,
}: {
emails: Fixtures["emails"];
organizer: { email: string; name: string };
booker: { email: string; name: string };
iCalUID: string;
}) {
expect(emails).toHaveEmail(
{
htmlToContain: "<title>confirmed_event_type_subject</title>",
to: `${organizer.email}`,
ics: {
filename: "event.ics",
iCalUID: iCalUID,
},
},
`${organizer.email}`
);
@@ -152,6 +205,10 @@ export function expectSuccessfulBookingCreationEmails({
{
htmlToContain: "<title>confirmed_event_type_subject</title>",
to: `${booker.name} <${booker.email}>`,
ics: {
filename: "event.ics",
iCalUID: iCalUID,
},
},
`${booker.name} <${booker.email}>`
);
@@ -160,17 +217,20 @@ export function expectSuccessfulBookingCreationEmails({
export function expectBrokenIntegrationEmails({
emails,
organizer,
booker,
}: {
emails: Fixtures["emails"];
organizer: { email: string; name: string };
booker: { email: string; name: string };
}) {
// Broken Integration email is only sent to the Organizer
expect(emails).toHaveEmail(
{
htmlToContain: "<title>broken_integration</title>",
to: `${organizer.email}`,
// No ics goes in case of broken integration email it seems
// ics: {
// filename: "event.ics",
// iCalUID: iCalUID,
// },
},
`${organizer.email}`
);
@@ -188,15 +248,21 @@ export function expectCalendarEventCreationFailureEmails({
emails,
organizer,
booker,
iCalUID,
}: {
emails: Fixtures["emails"];
organizer: { email: string; name: string };
booker: { email: string; name: string };
iCalUID: string;
}) {
expect(emails).toHaveEmail(
{
htmlToContain: "<title>broken_integration</title>",
to: `${organizer.email}`,
ics: {
filename: "event.ics",
iCalUID,
},
},
`${organizer.email}`
);
@@ -205,6 +271,10 @@ export function expectCalendarEventCreationFailureEmails({
{
htmlToContain: "<title>calendar_event_creation_failure_subject</title>",
to: `${booker.name} <${booker.email}>`,
ics: {
filename: "event.ics",
iCalUID,
},
},
`${booker.name} <${booker.email}>`
);
@@ -214,15 +284,21 @@ export function expectSuccessfulBookingRescheduledEmails({
emails,
organizer,
booker,
iCalUID,
}: {
emails: Fixtures["emails"];
organizer: { email: string; name: string };
booker: { email: string; name: string };
iCalUID: string;
}) {
expect(emails).toHaveEmail(
{
htmlToContain: "<title>event_type_has_been_rescheduled_on_time_date</title>",
to: `${organizer.email}`,
ics: {
filename: "event.ics",
iCalUID,
},
},
`${organizer.email}`
);
@@ -231,6 +307,10 @@ export function expectSuccessfulBookingRescheduledEmails({
{
htmlToContain: "<title>event_type_has_been_rescheduled_on_time_date</title>",
to: `${booker.name} <${booker.email}>`,
ics: {
filename: "event.ics",
iCalUID,
},
},
`${booker.name} <${booker.email}>`
);
@@ -247,6 +327,7 @@ export function expectAwaitingPaymentEmails({
{
htmlToContain: "<title>awaiting_payment_subject</title>",
to: `${booker.name} <${booker.email}>`,
noIcs: true,
},
`${booker.email}`
);
@@ -265,6 +346,7 @@ export function expectBookingRequestedEmails({
{
htmlToContain: "<title>event_awaiting_approval_subject</title>",
to: `${organizer.email}`,
noIcs: true,
},
`${organizer.email}`
);
@@ -273,6 +355,7 @@ export function expectBookingRequestedEmails({
{
htmlToContain: "<title>booking_submitted_subject</title>",
to: `${booker.email}`,
noIcs: true,
},
`${booker.email}`
);
@@ -346,7 +429,7 @@ export function expectBookingCreatedWebhookToHaveBeenFired({
subscriberUrl: string;
location: string;
paidEvent?: boolean;
videoCallUrl?: string;
videoCallUrl?: string | null;
}) {
if (!paidEvent) {
expectWebhookToHaveBeenCalledWith(subscriberUrl, {
@@ -545,6 +628,7 @@ export function expectSuccessfulVideoMeetingUpdationInCalendar(
expect(calendarEvent).toEqual(expect.objectContaining(expected.calEvent));
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function expectBookingInDBToBeRescheduledFromTo({ from, to }: { from: any; to: any }) {
// Expect previous booking to be cancelled
await expectBookingToBeInDatabase({