snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
import fs from 'fs';
import { request } from '@playwright/test';
import type { Endpoints } from '@rocket.chat/rest-typings';
import { expect, type BaseTest } from './test';
import { APP_URL } from '../../data/apps/apps-data';
import { BASE_API_URL, BASE_URL } from '../config/constants';
import { Users } from '../fixtures/userStates';
export async function insertDefaultTestApp(): Promise<void> {
const api = await request.newContext();
const headers = {
'X-Auth-Token': Users.admin.data.loginToken,
'X-User-Id': Users.admin.data._id,
};
await api.post(`${BASE_URL}/api/apps`, { data: { url: APP_URL }, headers });
await api.post(`${BASE_API_URL}/settings/VideoConf_Default_Provider`, { data: { value: 'test' }, headers });
}
export async function installLocalTestPackage(packagePath: string): Promise<{ app: { id: string } }> {
const api = await request.newContext();
const headers = {
'X-Auth-Token': Users.admin.data.loginToken,
'X-User-Id': Users.admin.data._id,
};
const response = await api.post(`${BASE_URL}/api/apps`, { multipart: { app: fs.createReadStream(packagePath) }, headers });
await expect(response).toBeOK();
return response.json();
}
export async function uninstallApp(appId: string): Promise<void> {
const api = await request.newContext();
const headers = {
'X-Auth-Token': Users.admin.data.loginToken,
'X-User-Id': Users.admin.data._id,
};
const response = await api.delete(`${BASE_URL}/api/apps/${appId}`, { headers });
await expect(response).toBeOK();
}
export async function getAppLogs(api: BaseTest['api'], appId: string): Promise<ReturnType<Endpoints['/apps/:id/logs']['GET']>> {
const response = await api.get(`/apps/${appId}/logs`, undefined, '/api');
await expect(response).toBeOK();
return response.json();
}

View File

@@ -0,0 +1,9 @@
export const convertHexToRGB = (hex: string) => {
hex = hex.replace(/^#/, '');
const red = parseInt(hex.substring(0, 2), 16);
const green = parseInt(hex.substring(2, 4), 16);
const blue = parseInt(hex.substring(4, 6), 16);
return `rgb(${red}, ${green}, ${blue})`;
};

View File

@@ -0,0 +1,208 @@
import { faker } from '@faker-js/faker';
import { request as baseRequest } from '@playwright/test';
import type { IRoom, IMessage } from '@rocket.chat/core-typings';
import type { ChannelsCreateProps, GroupsCreateProps } from '@rocket.chat/rest-typings';
import type { BaseTest } from './test';
import { BASE_API_URL } from '../config/constants';
/**
* createTargetChannel:
* - Usefull to create a target channel for message related tests
*/
export async function createTargetChannel(api: BaseTest['api'], options?: Omit<ChannelsCreateProps, 'name'>): Promise<string> {
const name = faker.string.uuid();
await api.post('/channels.create', { name, ...options });
return name;
}
export async function createTargetChannelAndReturnFullRoom(
api: BaseTest['api'],
options?: Omit<ChannelsCreateProps, 'name'>,
): Promise<{ channel: IRoom }> {
const name = faker.string.uuid();
return (await api.post('/channels.create', { name, ...options })).json();
}
export async function sendTargetChannelMessage(api: BaseTest['api'], roomName: string, options?: Partial<IMessage>) {
const response = await api.get(`/channels.info?roomName=${roomName}`);
const {
channel: { _id: rid },
}: { channel: IRoom } = await response.json();
await api.post('/chat.sendMessage', {
message: {
rid,
msg: options?.msg || 'simple message',
...options,
},
});
return options?.msg || 'simple message';
}
export async function deleteChannel(api: BaseTest['api'], roomName: string): Promise<void> {
await api.post('/channels.delete', { roomName });
}
export async function isChannelMember(api: BaseTest['api'], roomName: string, username: string): Promise<boolean> {
const response = await api.get(`/channels.members?roomName=${roomName}`);
const { members }: { members: { username: string }[] } = await response.json();
return members.some((member) => member.username === username);
}
export async function deleteRoom(api: BaseTest['api'], roomId: string): Promise<void> {
await api.post('/rooms.delete', { roomId });
}
export async function deletePrivateRoomsByName(credentials: { username: string; password: string }, roomNames: string[]): Promise<void> {
const userApi = await baseRequest.newContext();
try {
const loginResponse = await userApi.post(`${BASE_API_URL}/login`, { data: credentials });
if (!loginResponse.ok()) {
return;
}
const { data } = await loginResponse.json();
await Promise.allSettled(
roomNames.map((roomName) =>
userApi.post(`${BASE_API_URL}/groups.delete`, {
data: { roomName },
headers: {
'X-Auth-Token': data.authToken,
'X-User-Id': data.userId,
},
}),
),
);
} finally {
await userApi.dispose();
}
}
export async function markRoomAsRead(api: BaseTest['api'], roomId: string): Promise<void> {
await api.post('/subscriptions.read', { rid: roomId });
}
export async function createTargetPrivateChannel(api: BaseTest['api'], options?: Omit<GroupsCreateProps, 'name'>): Promise<string> {
const name = faker.string.uuid();
await api.post('/groups.create', { name, ...options });
return name;
}
export async function createTargetTeam(api: BaseTest['api'], options?: Omit<GroupsCreateProps, 'name'>): Promise<string> {
const name = faker.string.uuid();
await api.post('/teams.create', { name, type: 1, members: ['user2', 'user1'], ...options });
return name;
}
export async function deleteTeam(api: BaseTest['api'], teamName: string): Promise<void> {
await api.post('/teams.delete', { teamName });
}
export async function createDirectMessage(api: BaseTest['api']): Promise<void> {
await api.post('/dm.create', {
usernames: 'user1,user2',
});
}
export async function createTargetDiscussion(api: BaseTest['api']): Promise<Record<string, string>> {
const channelName = faker.string.uuid();
const discussionName = faker.string.uuid();
const channelResponse = await api.post('/channels.create', { name: channelName });
const { channel } = await channelResponse.json();
const discussionResponse = await api.post('/rooms.createDiscussion', { t_name: discussionName, prid: channel._id });
const { discussion } = await discussionResponse.json();
if (!discussion) {
throw new Error('Discussion not created');
}
return discussion;
}
export async function createChannelWithTeam(api: BaseTest['api']): Promise<Record<string, string>> {
const channelName = faker.string.uuid();
const teamName = faker.string.uuid();
const teamResponse = await api.post('/teams.create', { name: teamName, type: 1, members: ['user2'] });
const { team } = await teamResponse.json();
await api.post('/channels.create', { name: channelName, members: ['user1'], extraData: { teamId: team._id } });
return { channelName, teamName };
}
export async function createArchivedChannel(api: BaseTest['api']): Promise<string> {
const { channel } = await createTargetChannelAndReturnFullRoom(api);
try {
await api.post('/channels.archive', { roomId: channel._id });
} catch (error) {
throw new Error(`Error archiving the channel: ${error}`);
}
if (!channel.name) {
throw new Error('Invalid channel was created');
}
return channel.name;
}
export async function createTargetGroupAndReturnFullRoom(
api: BaseTest['api'],
options?: Omit<GroupsCreateProps, 'name'>,
): Promise<{ group: IRoom }> {
const name = faker.string.uuid();
return (await api.post('/groups.create', { name, ...options })).json();
}
export async function sendMessage(api: BaseTest['api'], roomId: string, msg: string, threadId?: string): Promise<string> {
const payload: { message: { rid: string; msg: string; tmid?: string } } = { message: { rid: roomId, msg } };
if (threadId) {
payload.message.tmid = threadId;
}
const response = await api.post('/chat.sendMessage', payload);
const data: { success?: boolean; message?: { _id: string } } = await response.json();
if (!data.success || !data.message?._id) {
throw new Error(`Error sending message: ${JSON.stringify(data)}`);
}
return data.message._id;
}
export async function createDiscussion(api: BaseTest['api'], parentRoomId: string, parentMessageId: string, name: string): Promise<string> {
const response = await api.post('/rooms.createDiscussion', {
prid: parentRoomId,
pmid: parentMessageId,
t_name: name,
});
const data: { success?: boolean; discussion?: { _id: string } } = await response.json();
if (!data.discussion?._id) {
throw new Error(`Error creating discussion: ${JSON.stringify(data)}`);
}
return data.discussion._id;
}
export async function createDirectMessageRoom(api: BaseTest['api'], username: string): Promise<string> {
const response = await api.post('/im.create', { username });
const data: { success?: boolean; room?: { _id: string } } = await response.json();
if (!data.room?._id) {
throw new Error(`Error creating direct message room: ${JSON.stringify(data)}`);
}
return data.room._id;
}

View File

@@ -0,0 +1,11 @@
import type { Endpoints } from '@rocket.chat/rest-typings';
import type { BaseTest } from './test';
export async function createCustomRole(api: BaseTest['api'], data: Parameters<Endpoints['/v1/roles.create']['POST']>[0]) {
return api.post('/roles.create', data);
}
export async function deleteCustomRole(api: BaseTest['api'], roleId: string) {
return api.post('/roles.delete', { roleId });
}

View File

@@ -0,0 +1,7 @@
import { getUserInfo } from './getUserInfo';
import type { BaseTest } from './test';
import { expect } from './test';
export const expectPollUserStatus = async (api: BaseTest['api'], username: string, status: 'online' | 'offline' | 'away' | 'busy') => {
await expect.poll(async () => (await getUserInfo(api, username))?.status).toBe(status);
};

View File

@@ -0,0 +1,7 @@
import type { BaseTest } from './test';
export const getPermissionRoles = async (api: BaseTest['api'], permissionId: string): Promise<string[]> => {
const res = await api.get('/permissions.listAll');
const { update } = await res.json();
return update.find((p: { _id: string }) => p._id === permissionId)?.roles ?? [];
};

View File

@@ -0,0 +1,7 @@
import type { BaseTest } from './test';
export const getSettingValueById = async (api: BaseTest['api'], settingId: string): Promise<unknown> => {
const response = await api.get(`/settings/${settingId}`);
const { value } = await response.json();
return value;
};

View File

@@ -0,0 +1,15 @@
import type { IUser } from '@rocket.chat/core-typings';
import type { BaseTest } from './test';
export const getUserInfo = async (api: BaseTest['api'], username: string): Promise<IUser | undefined> => {
const response = await api.get(`/users.info?username=${username}`);
if (response.status() !== 200) {
throw new Error('Failed to get user info.');
}
const data = await response.json();
return data.user;
};

View File

@@ -0,0 +1,7 @@
export * from './create-target-channel';
export * from './setSettingValueById';
export * from './getSettingValueById';
export * from './getPermissionRoles';
export * from './updatePermissions';
export * from './setUserPreferences';
export * from './updateOwnUserInfo';

View File

@@ -0,0 +1,30 @@
import type { BaseTest } from '../test';
export const makeAgentAvailable = async (api: BaseTest['api'], agentId: string) => {
await api.post('/users.setStatus', {
userId: agentId,
message: '',
status: 'online',
});
return api.post('/livechat/agent.status', {
agentId,
status: 'available',
});
};
export const createAgent = async (api: BaseTest['api'], username: string) => {
const response = await api.post('/livechat/users/agent', { username });
if (response.status() !== 200) {
throw new Error(`Failed to create agent [http status: ${response.status()}]`);
}
const { user: agent } = await response.json();
return {
response,
data: agent,
delete: async () => api.delete(`/livechat/users/agent/${agent._id}`),
};
};

View File

@@ -0,0 +1,36 @@
import type { BaseTest } from '../test';
type CreateBusinessHoursParams = {
id?: string | null;
name?: string;
description?: string;
departments?: { departmentId: string }[];
};
export const createBusinessHour = async (api: BaseTest['api'], { name, departments = [] }: CreateBusinessHoursParams = {}) => {
const departmentIds = departments.join(',');
return api.post('/livechat/business-hours.save', {
name,
timezoneName: 'America/Sao_Paulo',
daysOpen: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
daysTime: [
{ day: 'Monday', start: { time: '08:00' }, finish: { time: '18:00' }, open: true },
{ day: 'Tuesday', start: { time: '08:00' }, finish: { time: '18:00' }, open: true },
{ day: 'Wednesday', start: { time: '08:00' }, finish: { time: '18:00' }, open: true },
{ day: 'Thursday', start: { time: '08:00' }, finish: { time: '18:00' }, open: true },
{ day: 'Friday', start: { time: '08:00' }, finish: { time: '18:00' }, open: true },
],
departmentsToApplyBusinessHour: departmentIds,
active: true,
type: 'custom',
timezone: 'America/Sao_Paulo',
workHours: [
{ day: 'Monday', start: '08:00', finish: '18:00', open: true },
{ day: 'Tuesday', start: '08:00', finish: '18:00', open: true },
{ day: 'Wednesday', start: '08:00', finish: '18:00', open: true },
{ day: 'Thursday', start: '08:00', finish: '18:00', open: true },
{ day: 'Friday', start: '08:00', finish: '18:00', open: true },
],
});
};

View File

@@ -0,0 +1,60 @@
import type { ILivechatCustomField } from '@rocket.chat/core-typings';
import type { BaseTest } from '../test';
type CustomField = Omit<ILivechatCustomField, '_id' | '_updatedAt'> & { field: string };
export const removeCustomField = (api: BaseTest['api'], id: string) => {
return api.post('/livechat/custom-fields.delete', {
customFieldId: id,
});
};
export const setVisitorCustomFieldValue = async (
api: BaseTest['api'],
params: { token: string; customFieldId: string; value: string; overwrite?: boolean },
) => {
const response = await api.post('/livechat/custom.field', {
token: params.token,
key: params.customFieldId,
value: params.value,
overwrite: params.overwrite ?? true,
});
if (!response.ok()) {
throw new Error(`Failed to set visitor custom field [http status: ${response.status()}]`);
}
const { field } = await response.json();
return { response, field };
};
export const createCustomField = async (api: BaseTest['api'], overwrites: Partial<CustomField>) => {
const response = await api.post('/livechat/custom-fields.save', {
customFieldId: null,
customFieldData: {
field: overwrites.field,
label: overwrites.label || overwrites.field,
visibility: 'visible',
scope: 'visitor',
searchable: false,
regexp: '',
type: 'input',
required: false,
defaultValue: '',
options: '',
public: false,
...overwrites,
},
});
if (!response.ok()) {
throw new Error(`Failed to create custom field [http status: ${response.status()}]`);
}
const { customField } = await response.json();
return {
response,
customField,
delete: () => removeCustomField(api, customField._id),
};
};

View File

@@ -0,0 +1,93 @@
import { faker } from '@faker-js/faker';
import type { ILivechatDepartment } from '@rocket.chat/core-typings';
import type { BaseTest } from '../test';
type CreateDepartmentParams = {
name?: string;
enabled?: boolean;
description?: string;
showOnRegistration?: boolean;
showOnOfflineForm?: boolean;
requestTagBeforeClosingChat?: boolean;
email?: string;
chatClosingTags?: string[];
offlineMessageChannelName?: string;
abandonedRoomsCloseCustomMessage?: string;
waitingQueueMessage?: string;
departmentsAllowedToForward?: string[];
fallbackForwardDepartment?: string;
maxNumberSimultaneousChat?: number;
allowReceiveForwardOffline?: boolean;
};
export const createDepartment = async (
api: BaseTest['api'],
{
name = '',
enabled = true,
description = '',
showOnRegistration = false,
showOnOfflineForm = false,
requestTagBeforeClosingChat = false,
email = '',
chatClosingTags = [],
offlineMessageChannelName = '',
abandonedRoomsCloseCustomMessage = '',
waitingQueueMessage = '',
departmentsAllowedToForward = [],
fallbackForwardDepartment = '',
maxNumberSimultaneousChat,
allowReceiveForwardOffline,
}: CreateDepartmentParams = {},
) => {
const response = await api.post('/livechat/department', {
department: {
name: name || faker.string.uuid(),
enabled,
description,
showOnRegistration,
showOnOfflineForm,
requestTagBeforeClosingChat,
email: email || faker.internet.email(),
chatClosingTags,
offlineMessageChannelName,
abandonedRoomsCloseCustomMessage,
waitingQueueMessage,
departmentsAllowedToForward,
fallbackForwardDepartment,
maxNumberSimultaneousChat,
allowReceiveForwardOffline,
},
});
if (response.status() !== 200) {
throw Error(`Unable to create department [http status: ${response.status()}]`);
}
const { department } = await response.json();
return {
response,
data: department,
delete: async () => api.delete(`/livechat/department/${department._id}`),
};
};
export const addAgentToDepartment = async (
api: BaseTest['api'],
{ department, agentId, username }: { department: ILivechatDepartment; agentId: string; username?: string },
) =>
api.post(`/livechat/department/${department._id}/agents`, {
remove: [],
upsert: [
{
agentId,
username: username || agentId,
count: 0,
order: 0,
},
],
});
export const deleteDepartment = async (api: BaseTest['api'], { id }: { id: string }) => api.delete(`/livechat/department/${id}`);

View File

@@ -0,0 +1,19 @@
import type { BaseTest } from '../test';
export const createManager = async (api: BaseTest['api'], username: string) => {
const response = await api.post('/livechat/users/manager', {
username,
});
if (response.status() !== 200) {
throw Error(`Unable to create manager [http status: ${response.status()}]`);
}
const { user: manager } = await response.json();
return {
response,
data: manager,
delete: async () => api.delete(`/livechat/users/manager/${manager._id}`),
};
};

View File

@@ -0,0 +1,19 @@
import type { BaseTest } from '../test';
const deleteMonitor = async (api: BaseTest['api'], username: string) => api.post('/livechat/monitors.delete', { username });
export const createMonitor = async (api: BaseTest['api'], username: string) => {
const response = await api.post('/livechat/monitors.create', { username });
if (response.status() !== 200) {
throw new Error(`Failed to create monitor [http status: ${response.status()}]`);
}
const data = await response.json();
return {
response,
data,
delete: async () => deleteMonitor(api, data.username),
};
};

View File

@@ -0,0 +1,16 @@
import type { ILivechatPriority } from '@rocket.chat/core-typings';
import type { BaseTest } from '../test';
import { expect } from '../test';
export const getPriorityByi18nLabel = async (api: BaseTest['api'], i18n: string): Promise<ILivechatPriority> => {
const allPriorityResp = await api.get('/livechat/priorities');
expect(allPriorityResp.status()).toBe(200);
const { priorities } = (await allPriorityResp.json()) as { priorities: ILivechatPriority[] };
const priority = priorities.find((p) => p.i18n === i18n);
if (!priority) {
throw new Error('Could not find priority with i18n "High"');
}
return priority;
};

View File

@@ -0,0 +1,123 @@
import { faker } from '@faker-js/faker';
import { createFakeVisitor } from '../../../mocks/data';
import type { BaseTest } from '../test';
type UpdateRoomParams = { roomId: string; visitorId: string; tags: string[] };
type CloseRoomParams = { roomId: string; visitorToken: string };
type CreateRoomParams = { tags?: string[]; visitorToken: string; agentId?: string };
type CreateVisitorParams = { token: string; departmentId?: string; name?: string; email?: string };
type CreateConversationParams = { visitorName?: string; visitorToken?: string; agentId?: string; departmentId?: string };
export const updateRoom = async (api: BaseTest['api'], { roomId, visitorId, tags }: UpdateRoomParams) => {
if (!roomId) {
throw Error('Unable to update room info, missing room id');
}
if (!visitorId) {
throw Error('Unable to update room info, missing visitor id');
}
const response = await api.post('/livechat/room.saveInfo', {
guestData: { _id: visitorId },
roomData: { _id: roomId, tags },
});
if (response.status() !== 200) {
throw Error(`Unable to update room info [http status: ${response.status()}]`);
}
return response;
};
export const closeRoom = async (api: BaseTest['api'], { roomId, visitorToken }: CloseRoomParams) =>
api.post('/livechat/room.close', { rid: roomId, token: visitorToken });
export const createRoom = async (api: BaseTest['api'], { visitorToken, agentId }: CreateRoomParams) => {
const response = await api.get('/livechat/room', {
token: visitorToken,
agentId,
});
if (response.status() !== 200) {
throw Error(`Unable to create room [http status: ${response.status()}]`, { cause: await response.json() });
}
const { room } = await response.json();
return {
response,
data: room,
async delete() {
await closeRoom(api, { roomId: room._id, visitorToken });
return api.post('/livechat/rooms.delete', { roomId: room._id });
},
};
};
export const createVisitor = async (api: BaseTest['api'], { name, token, departmentId }: CreateVisitorParams) => {
const fakeVisitor = createFakeVisitor();
const response = await api.post('/livechat/visitor', {
visitor: {
name: name || fakeVisitor.name,
email: fakeVisitor.email,
token,
...(departmentId && { department: departmentId }),
},
});
if (response.status() !== 200) {
throw Error(`Unable to create visitor [http status: ${response.status()}]`);
}
const { visitor } = await response.json();
return {
response,
data: visitor,
delete: async () => api.delete(`/livechat/visitor/${token}`),
};
};
export const sendMessageToRoom = async (
api: BaseTest['api'],
{ visitorToken, roomId, message }: { visitorToken: string; roomId: string; message?: string },
) => {
const response = await api.post(`/livechat/message`, {
token: visitorToken,
rid: roomId,
msg: message || faker.lorem.sentence(),
});
if (response.status() !== 200) {
throw Error(`Unable to send message to room [http status: ${response.status()}]`);
}
return response;
};
export const createConversation = async (
api: BaseTest['api'],
{ visitorName, visitorToken, agentId, departmentId }: CreateConversationParams = {},
) => {
const token = visitorToken || faker.string.uuid();
const { data: visitor, delete: deleteVisitor } = await createVisitor(api, { token, name: visitorName, departmentId });
const { data: room, delete: deleteRoom } = await createRoom(api, { visitorToken: token, agentId });
await sendMessageToRoom(api, { visitorToken: token, roomId: room._id });
return {
data: {
room,
visitor,
},
delete: async () => {
await deleteRoom();
await deleteVisitor();
},
};
};

View File

@@ -0,0 +1,22 @@
import { faker } from '@faker-js/faker';
import { type IOmnichannelServiceLevelAgreements, DEFAULT_SLA_CONFIG } from '@rocket.chat/core-typings';
import type { BaseTest } from '../test';
import { expect } from '../test';
export const generateRandomSLAData = (): Omit<IOmnichannelServiceLevelAgreements, '_updatedAt' | '_id'> => ({
name: `${faker.person.firstName()}-${faker.database.mongodbObjectId()}`,
description: faker.lorem.sentence(),
dueTimeInMinutes: faker.number.int({ min: 10, max: DEFAULT_SLA_CONFIG.ESTIMATED_WAITING_TIME_QUEUE }),
});
export const createSLA = async (
api: BaseTest['api'],
slaData?: Omit<IOmnichannelServiceLevelAgreements, '_updatedAt' | '_id'>,
): Promise<Omit<IOmnichannelServiceLevelAgreements, '_updated'>> => {
const response = await api.post('/livechat/sla', slaData ?? generateRandomSLAData());
expect(response.status()).toBe(200);
const { sla } = (await response.json()) as { sla: Omit<IOmnichannelServiceLevelAgreements, '_updated'> };
return sla;
};

View File

@@ -0,0 +1,36 @@
import { faker } from '@faker-js/faker';
import type { ILivechatTag } from '@rocket.chat/core-typings';
import type { BaseTest } from '../test';
type CreateTagParams = {
id?: string | null;
name?: string;
description?: string;
departments?: string[];
};
const removeTag = async (api: BaseTest['api'], id: string) => api.post('/livechat/tags.delete', { id });
export const createTag = async (api: BaseTest['api'], { id = null, name, description, departments = [] }: CreateTagParams = {}) => {
const response = await api.post('/livechat/tags.save', {
_id: id,
tagData: {
name: name ?? faker.string.alpha({ length: 8 }),
description: description ?? faker.string.alpha({ length: 16 }),
},
...(departments.length > 0 && { tagDepartments: departments }),
});
if (response.status() !== 200) {
throw new Error(`Failed to create tag [http status: ${response.status()}]`);
}
const data: ILivechatTag = await response.json();
return {
response,
data,
delete: async () => removeTag(api, data._id),
};
};

View File

@@ -0,0 +1,56 @@
import { faker } from '@faker-js/faker';
import type { BaseTest } from '../test';
type CreateUnitParams = {
id?: string | null;
name?: string;
visibility?: 'public' | 'private';
monitors?: { monitorId: string; username: string }[];
departments?: { departmentId: string }[];
};
const removeUnit = async (api: BaseTest['api'], id: string) => api.delete(`/livechat/units/${id}`);
export const createOrUpdateUnit = async (
api: BaseTest['api'],
{ id = null, name, visibility, monitors, departments }: CreateUnitParams = {},
) => {
const unitPayload = {
unitData: {
name: name ?? faker.string.uuid(),
visibility: visibility ?? 'public',
},
unitMonitors: monitors,
unitDepartments: departments,
};
const response = id ? await api.post(`/livechat/units/${id}`, unitPayload) : await api.post('/livechat/units', unitPayload);
if (response.status() !== 200) {
throw new Error(`Failed to create or update unit [http status: ${response.status()}]`);
}
const data = await response.json();
return {
response,
data,
delete: async () => removeUnit(api, data?._id),
};
};
export const fetchUnitMonitors = async (api: BaseTest['api'], unitId: string) => {
const response = await api.get(`/livechat/units/${unitId}/monitors`);
if (response.status() !== 200) {
throw new Error(`Failed to fetch unit monitors [http status: ${response.status()}]`);
}
const { monitors } = await response.json();
return {
response,
data: monitors,
};
};

View File

@@ -0,0 +1,18 @@
import type { APIResponse } from '@playwright/test';
import type { Serialized } from '@rocket.chat/core-typings';
export const parseMeteorResponse = async <ResponseType = unknown>(response: APIResponse): Promise<Serialized<ResponseType>> => {
const { message, success } = await response.json();
if (!success) {
throw new Error(message);
}
const { result, error } = JSON.parse(message);
if (error) {
throw new Error(JSON.stringify(error));
}
return result;
};

View File

@@ -0,0 +1,19 @@
import { getSettingValueById } from './getSettingValueById';
import { test } from './test';
export function preserveSettings(settingsList: string[]) {
const originalSettings: Record<string, unknown> = {};
test.beforeAll(async ({ api }) => {
const settingValues = await Promise.all(settingsList.map((setting) => getSettingValueById(api, setting)));
settingsList.forEach((setting, index) => {
originalSettings[setting] = settingValues[index];
});
});
test.afterAll(async ({ api }) => {
await Promise.all(settingsList.map((setting) => api.post(`/settings/${setting}`, { value: originalSettings[setting] })));
});
return originalSettings;
}

View File

@@ -0,0 +1,12 @@
import type { APIResponse } from '@playwright/test';
import type { ISetting } from '@rocket.chat/core-typings';
import type { BaseTest } from './test';
export const saveSettings = (
api: BaseTest['api'],
changes: {
_id: ISetting['_id'];
value: ISetting['value'];
}[],
): Promise<APIResponse> => api.post('/settings', { settings: changes });

View File

@@ -0,0 +1,26 @@
import { MongoClient } from 'mongodb';
import { URL_MONGODB } from '../config/constants';
import type { IUserState } from '../fixtures/userStates';
type SeedTranslatedMessageParams = {
rid: string;
msg: string;
author: IUserState;
translations: Record<string, string>;
};
// No translation provider is reachable from CI, so translations are seeded straight into the message.
// The author is reassigned as well because auto-translate skips messages sent by the user reading them.
export const seedTranslatedMessage = async ({ rid, msg, author, translations }: SeedTranslatedMessageParams): Promise<void> => {
const connection = await MongoClient.connect(URL_MONGODB);
try {
await connection
.db()
.collection('rocketchat_message')
.updateOne({ rid, msg }, { $set: { u: { _id: author.data._id, username: author.data.username }, translations } });
} finally {
await connection.close();
}
};

View File

@@ -0,0 +1,27 @@
import type { APIRequestContext } from 'playwright-core';
import type { BaseTest } from './test';
import { BASE_API_URL } from '../config/constants';
import type { IUserState } from '../fixtures/userStates';
export const sendMessageFromUser = async (request: APIRequestContext, user: IUserState, rid: string, message: string) => {
return request
.post(`${BASE_API_URL}/chat.postMessage`, {
headers: {
'X-Auth-Token': user.data.loginToken,
'X-User-Id': user.data._id,
},
data: {
roomId: rid,
text: message,
},
})
.then((response) => response.json());
};
export const sendFillerMessages = async (api: BaseTest['api'], rid: string, count = 50, batchSize = 10) => {
const messages = Array.from({ length: count }, (_, i) => `filler message ${i + 1}`);
for (let i = 0; i < messages.length; i += batchSize) {
await Promise.all(messages.slice(i, i + batchSize).map((text) => api.post('/chat.postMessage', { roomId: rid, text })));
}
};

View File

@@ -0,0 +1,6 @@
import type { APIResponse } from '@playwright/test';
import type { BaseTest } from './test';
export const setSettingValueById = (api: BaseTest['api'], settingId: string, value: unknown): Promise<APIResponse> =>
api.post(`/settings/${settingId}`, { value });

View File

@@ -0,0 +1,7 @@
import type { APIResponse } from '@playwright/test';
import type { UsersSetPreferencesParamsPOST } from '@rocket.chat/rest-typings';
import type { BaseTest } from './test';
export const setUserPreferences = (api: BaseTest['api'], preferences: UsersSetPreferencesParamsPOST['data']): Promise<APIResponse> =>
api.post(`/users.setPreferences`, { data: preferences });

View File

@@ -0,0 +1,175 @@
/* eslint-disable react-hooks/rules-of-hooks */
import { randomUUID } from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import AxeBuilder from '@axe-core/playwright';
import type { Locator, APIResponse, APIRequestContext } from '@playwright/test';
import { test as baseTest, request as baseRequest } from '@playwright/test';
import { BASE_API_URL, API_PREFIX, ADMIN_CREDENTIALS } from '../config/constants';
import { Users } from '../fixtures/userStates';
const PATH_NYC_OUTPUT = path.join(process.cwd(), '.nyc_output');
export type AnyObj = { [key: string]: any };
export type BaseTest = {
api: {
recreateContext(): Promise<void>;
login(credentials: { username: string; password: string }): Promise<APIRequestContext>;
get(uri: string, params?: AnyObj, prefix?: string): Promise<APIResponse>;
post(uri: string, data: AnyObj, prefix?: string): Promise<APIResponse>;
put(uri: string, data: AnyObj, prefix?: string): Promise<APIResponse>;
delete(uri: string, params?: AnyObj, prefix?: string): Promise<APIResponse>;
};
makeAxeBuilder: () => AxeBuilder;
};
declare global {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface Window {
collectIstanbulCoverage: (coverageJSON: string) => void;
__coverage__: Record<string, unknown>;
}
}
let apiContext: APIRequestContext;
const cacheFromCredentials = new Map<string, string>();
export const test = baseTest.extend<BaseTest>({
context: async ({ context }, use) => {
if (!process.env.E2E_COVERAGE) {
await use(context);
await context.close();
return;
}
await context.addInitScript(() =>
window.addEventListener('beforeunload', () => window.collectIstanbulCoverage(JSON.stringify(window.__coverage__))),
);
await fs.promises.mkdir(PATH_NYC_OUTPUT, { recursive: true });
await context.exposeFunction('collectIstanbulCoverage', (coverageJSON: string) => {
if (coverageJSON) {
fs.writeFileSync(path.join(PATH_NYC_OUTPUT, `playwright_coverage_${randomUUID()}.json`), coverageJSON);
}
});
await use(context);
await Promise.all(
context.pages().map(async (page) => {
await page.evaluate(() => window.collectIstanbulCoverage(JSON.stringify(window.__coverage__)));
await page.close();
}),
);
},
api: async ({ request }, use) => {
const newContext = async (token: string, userId: string) =>
baseRequest.newContext({
baseURL: BASE_API_URL,
extraHTTPHeaders: {
'X-Auth-Token': token,
'X-User-Id': userId,
},
});
const login = async (credentials: { username: string; password: string }): Promise<APIRequestContext> => {
if (credentials.username === Users.admin.data.username) {
return newContext(Users.admin.data.loginToken, Users.admin.data.username);
}
if (cacheFromCredentials.has(credentials.username + credentials.password)) {
const token = cacheFromCredentials.get(credentials.username + credentials.password);
return newContext(token!, credentials.username);
}
const resp = await request.post(`${BASE_API_URL}/login`, { data: credentials });
const json = await resp.json();
cacheFromCredentials.set(credentials.username + credentials.password, json.data.authToken);
return newContext(json.data.authToken, json.data.userId);
};
const recreateContext = async () => {
apiContext = await login(ADMIN_CREDENTIALS);
};
await recreateContext();
await use({
recreateContext,
login,
get(uri: string, params?: AnyObj, prefix = API_PREFIX) {
return apiContext.get(prefix + uri, { params });
},
post(uri: string, data: AnyObj, prefix = API_PREFIX) {
return apiContext.post(prefix + uri, { data });
},
put(uri: string, data: AnyObj, prefix = API_PREFIX) {
return apiContext.put(prefix + uri, { data });
},
delete(uri: string, params?: AnyObj, prefix = API_PREFIX) {
return apiContext.delete(prefix + uri, { params });
},
});
},
makeAxeBuilder: async ({ page }, use) => {
const SELECT_KNOW_ISSUES = ['aria-hidden-focus', 'nested-interactive'];
const makeAxeBuilder = () =>
new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
.include('body')
.disableRules([...SELECT_KNOW_ISSUES]);
await use(makeAxeBuilder);
},
});
export const { expect } = test;
expect.extend({
async toBeInvalid(received: Locator) {
try {
await expect(received).toHaveAttribute('aria-invalid', 'true');
return {
message: () => `expected ${received} to be invalid`,
pass: true,
};
} catch (error) {
return {
message: () => `expected ${received} to be invalid`,
pass: false,
};
}
},
async toBeBusy(received: Locator) {
try {
await expect(received).toHaveAttribute('aria-busy', 'true');
return {
message: () => `expected ${received} to be busy`,
pass: true,
};
} catch (error) {
return {
message: () => `expected ${received} to be busy`,
pass: false,
};
}
},
async hasAttribute(received: Locator, attribute: string) {
const pass = await received.evaluate((node, attribute) => node.hasAttribute(attribute), attribute);
return {
message: () => `expected ${received} to have attribute \`${attribute}\``,
pass,
};
},
});

View File

@@ -0,0 +1,19 @@
import crypto from 'crypto';
import type { APIResponse } from '@playwright/test';
import type { UsersUpdateOwnBasicInfoParamsPOST } from '@rocket.chat/rest-typings';
import type { BaseTest } from './test';
export const updateOwnUserPassword = async (
api: BaseTest['api'],
{ newPassword, currentPassword }: { newPassword: string; currentPassword: string },
): Promise<APIResponse> => {
/**
* SHA-256 is used here for client-side password hashing before transmission (2FA verification), not for password storage. The server expects this specific format for password verification. This is a requirement of the Rocket.Chat API for the 2FA flow. */
const encryptedPassword = crypto.createHash('sha256').update(currentPassword, 'utf8').digest('hex');
return updateOwnUserInfo(api, { newPassword, currentPassword: encryptedPassword });
};
const updateOwnUserInfo = (api: BaseTest['api'], data: UsersUpdateOwnBasicInfoParamsPOST['data']): Promise<APIResponse> =>
api.post(`/users.updateOwnBasicInfo`, { data });

View File

@@ -0,0 +1,7 @@
import { expect, type BaseTest } from './test';
type PermissionUpdate = { _id: string; roles: string[] };
export const updatePermissions = async (api: BaseTest['api'], permissions: PermissionUpdate[]): Promise<void> => {
await expect(await api.post('/permissions.update', { permissions })).toBeOK();
};

View File

@@ -0,0 +1,135 @@
import { faker } from '@faker-js/faker';
import type { APIResponse } from '@playwright/test';
import type { IUser } from '@rocket.chat/core-typings';
import type { BaseTest } from './test';
import { BASE_URL, DEFAULT_USER_CREDENTIALS } from '../config/constants';
import type { IUserState } from '../fixtures/userStates';
export interface ICreateUserOptions {
username?: string;
email?: string;
name?: string;
password?: string;
roles?: string[];
data?: Record<string, any>;
}
export interface ITestUser {
response: APIResponse;
data: IUser & { username: string };
deleted: boolean;
delete: () => Promise<APIResponse | undefined>;
markAsDeleted: () => void;
}
/**
* Creates a test user with optional customizations
*/
export async function createTestUser(api: BaseTest['api'], options: ICreateUserOptions = {}): Promise<ITestUser> {
const userData = {
email: options.email || faker.internet.email(),
name: options.name || faker.person.fullName(),
password: options.password || DEFAULT_USER_CREDENTIALS.password,
username: options.username || `test-user-${faker.string.uuid()}`,
roles: options.roles || ['user'],
...options.data,
};
const response = await api.post('/users.create', userData);
if (response.status() !== 200) {
throw new Error(`Failed to create user: ${response.status()}, response: ${await response.text()}`);
}
const { user } = await response.json();
return {
response,
data: user,
deleted: false,
markAsDeleted(this: ITestUser) {
this.deleted = true;
},
async delete(this: ITestUser) {
if (this.deleted) {
return;
}
const response = await api.post('/users.delete', { userId: user._id });
this.markAsDeleted();
return response;
},
};
}
/**
* Logs in a test user via the REST API and returns an IUserState
* suitable for use with createAuxContext.
*
* Use this instead of the pre-baked Users.userN fixtures whenever the test
* will deactivate (or otherwise invalidate the session of) the user, so that
* shared fixture tokens are never corrupted.
*/
export async function loginTestUser(api: BaseTest['api'], user: ITestUser): Promise<IUserState> {
const response = await api.post('/login', {
username: user.data.username,
password: DEFAULT_USER_CREDENTIALS.password,
});
const {
data: { userId, authToken },
} = await response.json();
const expires = new Date();
expires.setFullYear(expires.getFullYear() + 1);
return {
data: {
_id: userId,
username: user.data.username,
loginToken: authToken,
loginExpire: expires,
hashedToken: '',
},
state: {
cookies: [
{ sameSite: 'Lax', name: 'rc_uid', value: userId, domain: 'localhost', path: '/', expires: -1, httpOnly: false, secure: false },
{
sameSite: 'Lax',
name: 'rc_token',
value: authToken,
domain: 'localhost',
path: '/',
expires: -1,
httpOnly: false,
secure: false,
},
],
origins: [
{
origin: BASE_URL,
localStorage: [
{ name: 'userLanguage', value: 'en-US' },
{ name: 'Meteor.loginToken', value: authToken },
{ name: 'Meteor.loginTokenExpires', value: expires.toISOString() },
{ name: 'Meteor.userId', value: userId },
],
},
],
},
};
}
/**
* Creates multiple test users at once
*/
export async function createTestUsers(api: BaseTest['api'], count: number, options: ICreateUserOptions = {}): Promise<ITestUser[]> {
const promises = Array.from({ length: count }, (_, i) =>
createTestUser(api, {
...options,
username: options.username ? `${options.username}-${i + 1}` : undefined,
}),
);
return Promise.all(promises);
}