Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions app/definitions/ILoginCredentials.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
export type {
ICredentialsAppleAPI,
ICredentialsAuthenticated,
ICredentialsCasAPI,
ICredentialsCrowdAPI,
ICredentialsLdapAPI,
ICredentialsOAuth,
ICredentialsPasswordAPI,
ICredentialsSamlAPI,
ICredentialsTotpAPI,
ILoginCredentials
} from '@rocket.chat/sdk/interfaces';
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ import buildMessage from '../../helpers/buildMessage';
import { subscribeRoom, unsubscribeRoom } from '../../../../actions/room';
import { clearUserTyping } from '../../../../actions/usersTyping';
import {
flush,
flushMicrotasksAndTimers,
framesOn,
makeCollection as makeBaseCollection,
makeReduxStore,
Expand Down Expand Up @@ -131,18 +131,18 @@ afterEach(() => {
async function connectDriver() {
sdk.initialize('https://example.com');
const connectPromise = sdk.connect();
await flush();
await flushMicrotasksAndTimers();
mockConnections[0].onopen();
await flush();
await flushMicrotasksAndTimers();
await connectPromise;
}

async function subscribeToRoom(rid: string) {
const room = new RoomSubscription(rid);
const subscribing = room.subscribe();
await flush();
await flushMicrotasksAndTimers();
await subscribing;
await flush();
await flushMicrotasksAndTimers();
return room;
}

Expand All @@ -165,7 +165,7 @@ describe('RoomSubscription over the real SDK', () => {
collection: 'stream-room-messages',
fields: { eventName: 'room-rid', args: [MESSAGE] }
});
await flush();
await flushMicrotasksAndTimers();

expect(buildMessage).toHaveBeenCalledTimes(1);
expect(getMessageById).toHaveBeenCalledWith('msg-1');
Expand All @@ -179,7 +179,7 @@ describe('RoomSubscription over the real SDK', () => {
const room = await subscribeToRoom('room-rid');

await room.unsubscribe();
await flush();
await flushMicrotasksAndTimers();

expect(framesOn(mockConnections[0], 'unsub')).toHaveLength(5);
expect(redux.store.dispatch).toHaveBeenCalledWith(unsubscribeRoom('room-rid'));
Expand All @@ -190,7 +190,7 @@ describe('RoomSubscription over the real SDK', () => {
collection: 'stream-room-messages',
fields: { eventName: 'room-rid', args: [MESSAGE] }
});
await flush();
await flushMicrotasksAndTimers();

expect(buildMessage).not.toHaveBeenCalled();
});
Expand Down
42 changes: 21 additions & 21 deletions app/lib/services/__tests__/connect.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { setActiveUsers } from '../../../actions/activeUsers';
import { updateSettings } from '../../../actions/settings';
import { updatePermission } from '../../../actions/permissions';
import { _activeUsers, _setUserTimer } from '../../methods/setUser';
import { flush, framesOn, makeCollection, makeReduxStore, receiveFrame } from '../../testUtils/sdkIntegration';
import { flushMicrotasksAndTimers, framesOn, makeCollection, makeReduxStore, receiveFrame } from '../../testUtils/sdkIntegration';
import type { MockConnection } from '../../testUtils/sdkIntegration';
import type * as SdkIntegration from '../../testUtils/sdkIntegration';

Expand Down Expand Up @@ -119,10 +119,10 @@ afterEach(() => {

async function connectAndDriveHandshake(server = 'https://example.com') {
await connect({ server });
await flush();
await flushMicrotasksAndTimers();
expect(mockConnections.length).toBeGreaterThan(0);
mockConnections[0].onopen();
await flush();
await flushMicrotasksAndTimers();
}

describe('connect() over the real SDK', () => {
Expand All @@ -139,7 +139,7 @@ describe('connect() over the real SDK', () => {
redux.state.meteor.connected = true;

receiveFrame(mockConnections[0], { msg: 'connected', session: 'again' });
await flush();
await flushMicrotasksAndTimers();

expect(redux.store.dispatch.mock.calls.filter(([action]) => action.type === connectSuccess().type)).toHaveLength(1);
});
Expand All @@ -148,7 +148,7 @@ describe('connect() over the real SDK', () => {
await connectAndDriveHandshake();

mockConnections[0].onclose({ code: 1006 });
await flush();
await flushMicrotasksAndTimers();

expect(redux.store.dispatch).toHaveBeenCalledWith(disconnectAction());
});
Expand All @@ -168,12 +168,12 @@ describe('connect() over the real SDK', () => {
const before = successCount();

await connect({ server: 'https://b.example.com' });
await flush();
await flushMicrotasksAndTimers();

expect(firstConnection.close).toHaveBeenCalled();

firstConnection.onmessage({ data: JSON.stringify({ msg: 'connected', session: 'x' }) });
await flush();
await flushMicrotasksAndTimers();

expect(successCount()).toBe(before);
});
Expand All @@ -188,7 +188,7 @@ describe('login() over the real SDK', () => {
await connectLoggedIn();

const loginPromise = login({ user: 'the-user', password: 'secret' });
await flush();
await flushMicrotasksAndTimers();
const user = await loginPromise;

expect(user).toEqual(
Expand All @@ -211,7 +211,7 @@ describe('login() over the real SDK', () => {
await connectLoggedIn();

const loginPromise = login({ user: 'the-user', password: 'secret' });
await flush();
await flushMicrotasksAndTimers();
const user = await loginPromise;

expect(user).toEqual(
Expand All @@ -230,7 +230,7 @@ describe('login() over the real SDK', () => {
await connectLoggedIn();

const loginPromise = login({ user: 'the-user', password: 'secret' });
await flush();
await flushMicrotasksAndTimers();
const user = await loginPromise;

expect(user).toEqual(
Expand All @@ -246,7 +246,7 @@ describe('login() over the real SDK', () => {
await connectLoggedIn();

const loginPromise = loginWithPassword({ user: 'the-user', password: 'secret' });
await flush();
await flushMicrotasksAndTimers();
await loginPromise;

const loginCall = (global.fetch as jest.Mock).mock.calls.find(([url]) => String(url).includes('/api/v1/login'));
Expand All @@ -259,7 +259,7 @@ describe('login() over the real SDK', () => {
await connectLoggedIn();

const loginPromise = loginWithPassword({ user: 'the-user', password: 'secret' });
await flush();
await flushMicrotasksAndTimers();
await loginPromise;

const loginCall = (global.fetch as jest.Mock).mock.calls.find(([url]) => String(url).includes('/api/v1/login'));
Expand All @@ -278,7 +278,7 @@ describe('onStreamData handlers over real frames', () => {
collection: 'stream-notify-all',
fields: { eventName: 'public-settings-changed', args: [null, { _id: 'Site_Name', value: 'New Name' }] }
});
await flush();
await flushMicrotasksAndTimers();

expect(redux.store.dispatch).toHaveBeenCalledWith(updateSettings('Site_Name', 'New Name'));
});
Expand All @@ -292,7 +292,7 @@ describe('onStreamData handlers over real frames', () => {
collection: 'stream-user-presence',
fields: { uid: 'user-id', args: [['user-id', 1, '', '', undefined]] }
});
await flush();
await flushMicrotasksAndTimers();

expect(redux.store.dispatch).toHaveBeenCalledWith(
setActiveUsers({ 'user-id': expect.objectContaining({ status: 'online' }) })
Expand All @@ -309,7 +309,7 @@ describe('onStreamData handlers over real frames', () => {
collection: 'stream-notify-logged',
fields: { eventName: 'user-status', args: [['user-id', 'online', 1, '', '', undefined]] }
});
await flush();
await flushMicrotasksAndTimers();

expect(_activeUsers.activeUsers['user-id']).toEqual(expect.objectContaining({ status: 'online' }));
expect(redux.store.dispatch).toHaveBeenCalledWith(setUser(expect.objectContaining({ status: 'online' })));
Expand All @@ -324,7 +324,7 @@ describe('onStreamData handlers over real frames', () => {
collection: 'stream-notify-logged',
fields: { eventName: 'permissions-changed', args: [null, { _id: 'create-c', roles: ['admin'] }] }
});
await flush();
await flushMicrotasksAndTimers();

expect(redux.store.dispatch).toHaveBeenCalledWith(updatePermission('create-c', ['admin']));
});
Expand All @@ -339,7 +339,7 @@ describe('onStreamData handlers over real frames', () => {
collection: 'stream-notify-logged',
fields: { eventName: 'Users:NameChanged', args: [{ _id: 'user-id', username: 'renamed' }] }
});
await flush();
await flushMicrotasksAndTimers();

expect(collection.find).toHaveBeenCalledWith('user-id');
expect(database.active.write).toHaveBeenCalled();
Expand All @@ -349,7 +349,7 @@ describe('onStreamData handlers over real frames', () => {
await connectAndDriveHandshake();

receiveFrame(mockConnections[0], { msg: 'changed', collection: 'stream-force_logout', fields: {} });
await flush();
await flushMicrotasksAndTimers();

expect(redux.store.dispatch).toHaveBeenCalledWith(logout(true));
});
Expand All @@ -363,7 +363,7 @@ describe('onStreamData handlers over real frames', () => {
id: 'user-id',
fields: { username: 'the-user', status: 'online' }
});
await flush();
await flushMicrotasksAndTimers();

expect(_activeUsers.activeUsers['user-id']).toEqual(expect.objectContaining({ status: 'online' }));
});
Expand All @@ -375,7 +375,7 @@ describe('sdk.subscribeRoom() over the real SDK', () => {
await connectAndDriveHandshake();

const subscribing = sdk.subscribeRoom('room-rid');
await flush();
await flushMicrotasksAndTimers();
await subscribing;

const subs = framesOn(mockConnections[0], 'sub');
Expand All @@ -400,7 +400,7 @@ describe('sdk.subscribeRoom() over the real SDK', () => {
await connectAndDriveHandshake();

const subscribing = sdk.subscribeRoom('room-rid');
await flush();
await flushMicrotasksAndTimers();
await subscribing;

const subs = framesOn(mockConnections[0], 'sub');
Expand Down
4 changes: 0 additions & 4 deletions app/lib/services/__tests__/socketHealth.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,6 @@ describe('recoverSocket against the real SDK socket', () => {
jest.useRealTimers();
});

it('exposes the ping interval the health classification depends on', () => {
expect(driver.pingInterval).toBe(PING_INTERVAL);
});

it('keeps a doubtful socket when the round trip gets a pong', async () => {
backdateLastPing(driver, PING_INTERVAL + 5000);

Expand Down
15 changes: 2 additions & 13 deletions app/lib/services/__tests__/socketHealth.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import sdk, { type ISocketDriver } from '../sdk';
import { classifySocketHealth, recoverSocket } from '../socketHealth';
import sdk from '../sdk';
import { recoverSocket } from '../socketHealth';
import { buildConnectedDriver } from '../../testUtils/sdkIntegration';
import type { IMockSdk, IMockSdkDriver, MockConnection } from '../../testUtils/sdkIntegration';
import type * as SdkIntegration from '../../testUtils/sdkIntegration';
Expand Down Expand Up @@ -44,17 +44,6 @@ describe('socket health against a driver from the shared harness', () => {
jest.useRealTimers();
});

describe('classifySocketHealth', () => {
it('returns round-trip-check for a connected socket rather than trusting it outright', () => {
expect(classifySocketHealth(driver as unknown as ISocketDriver)).toBe('round-trip-check');
});

it('returns reopen for a closed socket even when lastPing is fresh', () => {
mockConnections[0].readyState = CLOSED;
expect(classifySocketHealth(driver as unknown as ISocketDriver)).toBe('reopen');
});
});

describe('recoverSocket', () => {
it('keeps a socket whose round trip answers', async () => {
await expect(recoverSocket()).resolves.toBe('confirmed-alive');
Expand Down
5 changes: 2 additions & 3 deletions app/lib/services/connect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ jest.mock('../methods/helpers/log', () => ({

const flushMicrotasks = async (): Promise<void> => {
for (let i = 0; i < 5; i += 1) {
// eslint-disable-next-line no-await-in-loop
await Promise.resolve();
}
};
Expand Down Expand Up @@ -695,7 +694,7 @@ describe('loginTOTP', () => {
mockSdkLogin.mockImplementationOnce(() => Promise.reject({ data: { error: 'totp-required', details: {} } }));
mockSdkCurrent.currentLogin = { result: { userId: 'userId', authToken: 'authToken', me: { username: 'username' } } };

await loginTOTP({ username: 'user', ldapPass: 'password', ldap: true, ldapOptions: {} }, true);
await loginTOTP({ username: 'user', ldapPass: 'password', ldap: true, ldapOptions: {} }, { retryWithPassword: true });

expect(mockSdkLogin).toHaveBeenLastCalledWith({ user: 'user', password: 'password', code: '123456' });
}, 2000);
Expand All @@ -704,7 +703,7 @@ describe('loginTOTP', () => {
mockSdkLogin.mockImplementationOnce(() => Promise.reject({ data: { error: 'totp-required', details: {} } }));
mockSdkCurrent.currentLogin = { result: { userId: 'userId', authToken: 'authToken', me: { username: 'username' } } };

await loginTOTP({ username: 'user', crowdPassword: 'password', crowd: true }, true);
await loginTOTP({ username: 'user', crowdPassword: 'password', crowd: true }, { retryWithPassword: true });

expect(mockSdkLogin).toHaveBeenLastCalledWith({ user: 'user', password: 'password', code: '123456' });
}, 2000);
Expand Down
10 changes: 5 additions & 5 deletions app/lib/services/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ function toPasswordLogin(params: ILoginCredentials): ICredentialsPasswordAPI | u
}
}

async function loginTOTP(params: ILoginCredentials, loginEmailPassword?: boolean): Promise<ILoggedUser> {
async function loginTOTP(params: ILoginCredentials, options?: { retryWithPassword?: boolean }): Promise<ILoggedUser> {
try {
return await login(params);
} catch (e: any) {
Expand All @@ -366,11 +366,11 @@ async function loginTOTP(params: ILoginCredentials, loginEmailPassword?: boolean
invalid: (details.error || error) === 'totp-invalid'
});

const passwordParams = loginEmailPassword ? toPasswordLogin(params) : undefined;
const passwordParams = options?.retryWithPassword ? toPasswordLogin(params) : undefined;
if (passwordParams) {
store.dispatch(setUser({ username: passwordParams.user || passwordParams.username }));

return loginTOTP({ ...passwordParams, code: code?.twoFactorCode }, loginEmailPassword);
return loginTOTP({ ...passwordParams, code: code?.twoFactorCode }, options);
}

return loginTOTP({
Expand Down Expand Up @@ -403,11 +403,11 @@ function loginWithPassword({ user, password }: { user: string; password: string
};
}

return loginTOTP(params, true);
return loginTOTP(params, { retryWithPassword: true });
}

async function loginOAuthOrSso(params: ILoginCredentials) {
const result = await loginTOTP(params, false);
const result = await loginTOTP(params);
store.dispatch(loginRequest({ resume: result.token }, false));
}

Expand Down
14 changes: 0 additions & 14 deletions app/lib/services/restApi.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { ServerMediaSignal } from '@rocket.chat/media-signaling';
import { Platform } from 'react-native';

import type * as SdkIntegration from '../testUtils/sdkIntegration';
Expand Down Expand Up @@ -94,19 +93,6 @@ describe('mediaCallsStateSignals', () => {
expect(result).toEqual({ signals: [], success: true });
});

it('returns signals and success from the API response', async () => {
const mockSignals = [
{ type: 'new', callId: 'call-1' } as unknown as ServerMediaSignal,
{ type: 'notification', notification: 'ringing' } as unknown as ServerMediaSignal
];
mockSdkGet.mockResolvedValueOnce({ signals: mockSignals, success: true });

const result = await mediaCallsStateSignals('device-id');

expect(result.signals).toHaveLength(2);
expect(result.success).toBe(true);
});

it('returns empty signals and success false when sdk.get throws', async () => {
mockSdkGet.mockRejectedValueOnce(new Error('Network error'));

Expand Down
2 changes: 0 additions & 2 deletions app/lib/services/sdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ jest.mock('@rocket.chat/sdk', () => ({
settings: { customHeaders: {} }
}));

jest.mock('../constants/twoFactor', () => ({ TWO_FACTOR: 'TWO_FACTOR' }));

jest.mock('./twoFactor/twoFactor', () => ({
twoFactor: (...args: unknown[]) => mockTwoFactor(...args)
}));
Expand Down
Loading
Loading