level_0
int64 0
10k
| index
int64 0
0
| repo_id
stringlengths 22
152
| file_path
stringlengths 41
203
| content
stringlengths 11
11.5M
|
---|---|---|---|---|
1,820 | 0 | petrpan-code/web-infra-dev/modern.js/tests/integration/swc | petrpan-code/web-infra-dev/modern.js/tests/integration/swc/tests/minify-js.test.ts | import path from 'path';
import { readdirSync, readFileSync } from 'fs';
import { modernBuild } from '../../../utils/modernTestUtils';
const fixtures = path.resolve(__dirname, '../fixtures');
const getJsFiles = (appDir: string) =>
readdirSync(path.resolve(appDir, 'dist/static/js')).filter(filepath =>
/\.js$/.test(filepath),
);
describe('swc js minify', () => {
test('should emitted script files correctly', async () => {
const appDir = path.resolve(fixtures, 'minify-js');
await modernBuild(appDir);
const files = getJsFiles(appDir);
const mainFile = files.filter(filepath => filepath.startsWith('main'))[0];
expect(files.length).toBe(3);
expect(
readFileSync(path.resolve(appDir, `dist/static/js/${mainFile}`), 'utf8'),
).toContain('children:"helloworld"');
});
});
|
1,821 | 0 | petrpan-code/web-infra-dev/modern.js/tests/integration/swc | petrpan-code/web-infra-dev/modern.js/tests/integration/swc/tests/transform-fail.test.ts | import path from 'path';
import type { ChildProcess } from 'child_process';
import getPort from 'get-port';
import { runModernCommandDev } from '../../../utils/modernTestUtils';
const fixtures = path.resolve(__dirname, '../fixtures');
describe('swc transform failed minify', () => {
test('should not exit unexpectly when transform failed', async () => {
const appDir = path.resolve(fixtures, 'transform-fail');
const port = await getPort();
const cp: ChildProcess = await runModernCommandDev(['dev'], false, {
cwd: appDir,
env: {
NODE_ENV: 'development',
PORT: port,
},
});
expect(cp).toBeDefined();
expect(cp.exitCode).toBe(null);
cp.kill('SIGTERM');
});
});
|
1,848 | 0 | petrpan-code/web-infra-dev/modern.js/tests/integration/tailwindcss | petrpan-code/web-infra-dev/modern.js/tests/integration/tailwindcss/tests/tailwindcss-v2.test.ts | import path from 'path';
import { fixtures, launchAppWithPage } from './utils';
describe('use tailwindcss v2', () => {
test(`should show style by use tailwindcss text-black`, async () => {
const appDir = path.resolve(fixtures, 'tailwindcss-v2');
const { page, clear } = await launchAppWithPage(appDir);
const textColor = await page.$eval('p', p =>
window.getComputedStyle(p).getPropertyValue('color'),
);
expect(textColor).toBe('rgb(239, 68, 68)');
await clear();
});
});
|
1,849 | 0 | petrpan-code/web-infra-dev/modern.js/tests/integration/tailwindcss | petrpan-code/web-infra-dev/modern.js/tests/integration/tailwindcss/tests/tailwindcss-v3.test.ts | import path from 'path';
import { fixtures, launchAppWithPage } from './utils';
describe('use tailwindcss v3', () => {
test(`should show style by use tailwindcss text-black`, async () => {
const appDir = path.resolve(fixtures, 'tailwindcss-v3');
const { page, clear } = await launchAppWithPage(appDir);
const textColor = await page.$eval('p', p =>
window.getComputedStyle(p).getPropertyValue('color'),
);
expect(textColor).toBe('rgb(239, 68, 68)');
await clear();
});
test(`should load tailwind.config.js correctly`, async () => {
const appDir = path.resolve(fixtures, 'tailwindcss-v3-js-config');
const { page, clear } = await launchAppWithPage(appDir);
const textColor = await page.$eval('p', p =>
window.getComputedStyle(p).getPropertyValue('color'),
);
expect(textColor).toBe('rgb(31, 182, 255)');
await clear();
});
test(`should load tailwind.config.ts correctly`, async () => {
const appDir = path.resolve(fixtures, 'tailwindcss-v3-ts-config');
const { page, clear } = await launchAppWithPage(appDir);
const textColor = await page.$eval('p', p =>
window.getComputedStyle(p).getPropertyValue('color'),
);
expect(textColor).toBe('rgb(31, 182, 255)');
await clear();
});
test(`should merge tailwind config correctly`, async () => {
const appDir = path.resolve(fixtures, 'tailwindcss-v3-merge-config');
const { page, clear } = await launchAppWithPage(appDir);
const textColor = await page.$eval('p', p =>
window.getComputedStyle(p).getPropertyValue('color'),
);
expect(textColor).toBe('rgb(0, 128, 0)');
await clear();
});
});
|
1,851 | 0 | petrpan-code/web-infra-dev/modern.js/tests/integration/tailwindcss | petrpan-code/web-infra-dev/modern.js/tests/integration/tailwindcss/tests/twin.macro-v2.test.ts | import path from 'path';
import { fixtures, launchAppWithPage } from './utils';
describe('use twin.macro v2', () => {
test(`should show style by use tailwindcss theme when use twin.macro v2`, async () => {
const appDir = path.resolve(fixtures, 'twin.macro-v2');
const { page, clear } = await launchAppWithPage(appDir);
const textColor = await page.$eval('p', p =>
window.getComputedStyle(p).getPropertyValue('color'),
);
expect(textColor).toBe('rgb(255, 0, 0)');
await clear();
});
});
|
1,852 | 0 | petrpan-code/web-infra-dev/modern.js/tests/integration/tailwindcss | petrpan-code/web-infra-dev/modern.js/tests/integration/tailwindcss/tests/twin.macro-v3.test.ts | import path from 'path';
import { fixtures, launchAppWithPage } from './utils';
describe('use twin.macro v2', () => {
test(`should show style by use tailwindcss theme when use twin.macro v2`, async () => {
const appDir = path.resolve(fixtures, 'twin.macro-v3');
const { page, clear } = await launchAppWithPage(appDir);
const textColor = await page.$eval('p', p =>
window.getComputedStyle(p).getPropertyValue('color'),
);
expect(textColor).toBe('rgb(255, 0, 0)');
await clear();
});
});
|
1,860 | 0 | petrpan-code/web-infra-dev/modern.js/tests/integration/temp-dir | petrpan-code/web-infra-dev/modern.js/tests/integration/temp-dir/tests/index.test.ts | import fs from 'fs';
import path from 'path';
import { modernBuild } from '../../../utils/modernTestUtils';
const appDir = path.resolve(__dirname, '../');
function existsSync(filePath: string) {
return fs.existsSync(path.join(appDir, filePath));
}
describe('test temp-dir', () => {
let buildRes: { code: number };
beforeAll(async () => {
buildRes = await modernBuild(appDir);
});
test(`should get right alias build!`, async () => {
expect(buildRes.code === 0).toBe(true);
expect(existsSync('node_modules/.temp-dir/main')).toBe(true);
expect(existsSync('node_modules/.temp-dir/.runtime-exports')).toBe(true);
});
});
|
1,866 | 0 | petrpan-code/web-infra-dev/modern.js/tests/integration/testing-plugin | petrpan-code/web-infra-dev/modern.js/tests/integration/testing-plugin/tests/index.test.ts | import { DummyClass } from '../src';
describe('basic test', () => {
test('should compile legacy decorator correctly', () => {
expect(new DummyClass()).toEqual({});
});
});
|
1,874 | 0 | petrpan-code/web-infra-dev/modern.js/tests/integration/write-to-dist | petrpan-code/web-infra-dev/modern.js/tests/integration/write-to-dist/tests/index.test.ts | import path from 'path';
import fs from 'fs';
import puppeteer, { Browser, Page } from 'puppeteer';
import {
launchApp,
killApp,
getPort,
launchOptions,
} from '../../../utils/modernTestUtils';
const appDir = path.resolve(__dirname, '../');
function existsSync(filePath: string) {
return fs.existsSync(path.join(appDir, 'dist', filePath));
}
describe('test dev', () => {
let appPort: number;
let app: any;
let page: Page;
let browser: Browser;
beforeAll(async () => {
appPort = await getPort();
app = await launchApp(appDir, appPort, {}, {});
browser = await puppeteer.launch(launchOptions as any);
page = await browser.newPage();
});
afterAll(async () => {
await killApp(app);
await page.close();
await browser.close();
});
test(`should render csr page with memory correctly`, async () => {
const errors = [];
page.on('pageerror', error => {
errors.push(error.message);
});
await page.goto(`http://localhost:${appPort}`, {
waitUntil: ['networkidle0'],
});
const root = await page.$('.description');
const targetText = await page.evaluate(el => el?.textContent, root);
expect(targetText?.trim()).toEqual('Get started by editing src/App.tsx');
expect(errors.length).toEqual(0);
});
test('should not get production in dist', async () => {
expect(existsSync('route.json')).toBeTruthy();
expect(existsSync('html/main/index.html')).toBeFalsy();
});
});
|
2,048 | 0 | petrpan-code/ProtonMail/WebClients/applications/account/src/app | petrpan-code/ProtonMail/WebClients/applications/account/src/app/public/LayoutFooter.test.tsx | import { render } from '@testing-library/react';
import LayoutFooter from './LayoutFooter';
describe('<LayoutFooter />', () => {
// NOTE: Don't remove this test. Often forget the old-link class, let's make sure it's always there.
it('adds the old-link class', () => {
const { getByText } = render(<LayoutFooter version="123" app="proton-mail" />);
const element = getByText('Privacy policy');
expect(element).toHaveClass('old-link');
});
});
|
2,072 | 0 | petrpan-code/ProtonMail/WebClients/applications/account/src/app | petrpan-code/ProtonMail/WebClients/applications/account/src/app/signup/AccountStep.test.tsx | import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import { CLIENT_TYPES, SSO_PATHS } from '@proton/shared/lib/constants';
import { applyHOCs, withConfig } from '@proton/testing/index';
import AccountStep, { AccountStepProps } from './AccountStep';
import { SignupType } from './interfaces';
const AccountStepWrapper = (props: AccountStepProps) => {
const AccountStepContext = applyHOCs(withConfig())(AccountStep);
return (
<MemoryRouter>
<AccountStepContext {...props} />
</MemoryRouter>
);
};
let props: AccountStepProps;
beforeEach(() => {
jest.clearAllMocks();
props = {
clientType: CLIENT_TYPES.VPN,
toApp: 'proton-vpn-settings',
signupTypes: [SignupType.Email, SignupType.Username],
signupType: SignupType.Email,
onChangeSignupType: jest.fn(),
domains: [],
hasChallenge: false,
title: 'title123',
subTitle: 'subTitle123',
onSubmit: jest.fn(),
loginUrl: SSO_PATHS.MAIL_SIGN_IN,
};
});
it('should render', () => {
const { container } = render(<AccountStepWrapper {...props} />);
expect(container).not.toBeEmptyDOMElement();
});
it('should display "Already have an account" by default', () => {
const { getByText } = render(<AccountStepWrapper {...props} />);
expect(getByText('Already have an account?')).toBeInTheDocument();
});
|
2,078 | 0 | petrpan-code/ProtonMail/WebClients/applications/account/src/app | petrpan-code/ProtonMail/WebClients/applications/account/src/app/signup/PaymentStep.test.tsx | import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { PAYMENT_TOKEN_STATUS, PaymentMethodStatus } from '@proton/components/payments/core';
import { queryPaymentMethodStatus } from '@proton/shared/lib/api/payments';
import { CYCLE, PLANS, PLAN_TYPES } from '@proton/shared/lib/constants';
import { addApiMock, applyHOCs, withApi, withAuthentication, withConfig, withDeprecatedModals } from '@proton/testing';
import noop from '@proton/utils/noop';
import PaymentStep, { Props } from './PaymentStep';
let paymentMethodStatus: PaymentMethodStatus;
beforeEach(() => {
jest.clearAllMocks();
paymentMethodStatus = {
Card: true,
Paypal: true,
Apple: true,
Cash: true,
Bitcoin: true,
};
addApiMock(queryPaymentMethodStatus().url, () => paymentMethodStatus);
});
const PaymentStepContext = applyHOCs(
withApi(),
withConfig(),
withDeprecatedModals(),
withAuthentication()
)(PaymentStep);
let props: Props;
beforeEach(() => {
const plans: Props['plans'] = [
{
ID: '1',
Type: PLAN_TYPES.PLAN,
Cycle: CYCLE.MONTHLY,
Name: PLANS.BUNDLE,
Title: 'ProtonMail Plus',
Currency: 'USD',
Amount: 1099,
MaxDomains: 10,
MaxAddresses: 10,
MaxSpace: 5368709120,
MaxCalendars: 10,
MaxMembers: 10,
MaxVPN: 10,
MaxTier: 3,
Services: 1,
Features: 1,
Quantity: 1,
Pricing: {
[CYCLE.MONTHLY]: 1099,
[CYCLE.YEARLY]: 1099 * 12,
[CYCLE.TWO_YEARS]: 1099 * 24,
},
State: 1,
Offers: [],
},
];
props = {
api: noop as any,
subscriptionData: {
currency: 'USD',
cycle: CYCLE.MONTHLY,
minimumCycle: CYCLE.MONTHLY,
skipUpsell: false,
planIDs: {
[PLANS.BUNDLE]: 1,
},
checkResult: {
Amount: 1099,
AmountDue: 1099,
CouponDiscount: 0,
Coupon: null,
UnusedCredit: 0,
Credit: 0,
Currency: 'USD',
Cycle: CYCLE.MONTHLY,
Gift: 0,
Additions: null,
PeriodEnd: 1622505600,
},
payment: undefined,
},
plans,
onPay: jest.fn(),
onChangePlanIDs: jest.fn(),
onChangeCurrency: jest.fn(),
onChangeCycle: jest.fn(),
plan: plans[0],
planName: plans[0].Name,
paymentMethodStatus: {
Card: true,
Paypal: true,
Apple: false,
Cash: false,
Bitcoin: false,
},
};
});
jest.mock('@proton/components/hooks/useElementRect');
it('should render', () => {
const { container } = render(<PaymentStepContext {...props} />);
expect(container).not.toBeEmptyDOMElement();
});
it('should call onPay with the new token', async () => {
addApiMock('payments/v4/tokens', () => ({
Token: 'token123',
Code: 1000,
Status: PAYMENT_TOKEN_STATUS.STATUS_CHARGEABLE,
}));
const { findByTestId, findByText } = render(<PaymentStepContext {...props} />);
const payButton = await findByText(/Pay /);
expect(payButton).toBeDefined();
expect(payButton).toHaveTextContent('Pay');
const ccNumber = await findByTestId('ccnumber');
const cvc = await findByTestId('cvc');
const exp = await findByTestId('exp');
const postalCode = await findByTestId('postalCode');
await userEvent.type(ccNumber, '4242424242424242');
await userEvent.type(cvc, '123');
await userEvent.type(exp, '1230'); // stands for 12/30, i.e. December 2030
await userEvent.type(postalCode, '12345');
await userEvent.click(payButton);
expect(props.onPay).toHaveBeenCalledWith(
{
Details: {
Token: 'token123',
},
Type: 'token',
},
'cc'
);
});
|
2,091 | 0 | petrpan-code/ProtonMail/WebClients/applications/account/src/app | petrpan-code/ProtonMail/WebClients/applications/account/src/app/signup/searchParams.test.ts | import { SERVICES } from './interfaces';
import { getProductParams } from './searchParams';
describe('search params helper', () => {
const values = [
{
params: 'product=mail',
pathname: '/signup',
expectation: { product: SERVICES.mail, productParam: SERVICES.mail },
},
{
params: 'product=calendar',
pathname: '/signup',
expectation: { product: SERVICES.calendar, productParam: SERVICES.calendar },
},
{
params: 'product=business',
pathname: '/signup',
expectation: { product: undefined, productParam: 'business' },
},
{
params: 'product=generic',
pathname: '/signup',
expectation: { product: undefined, productParam: 'generic' },
},
{
params: '',
pathname: '/mail/signup',
expectation: { product: SERVICES.mail, productParam: SERVICES.mail },
},
{
params: '',
pathname: '/mail/signup',
expectation: { product: SERVICES.mail, productParam: SERVICES.mail },
},
{
params: 'product=calendar',
pathname: '/mail/signup',
expectation: { product: SERVICES.mail, productParam: SERVICES.mail },
},
{
params: 'product=foo',
pathname: '/foo/signup',
expectation: { product: undefined, productParam: 'generic' },
},
{
params: 'product=foo',
pathname: '/mail/signup',
expectation: { product: SERVICES.mail, productParam: SERVICES.mail },
},
{
params: 'product=generic',
pathname: '/mail/signup',
expectation: { product: SERVICES.mail, productParam: SERVICES.mail },
},
];
it.each(values)('$pathname?$params should be $expectation', ({ params, pathname, expectation }) => {
expect(getProductParams(pathname, new URLSearchParams(params))).toEqual(expectation);
});
});
|
2,119 | 0 | petrpan-code/ProtonMail/WebClients/applications/account/src/app | petrpan-code/ProtonMail/WebClients/applications/account/src/app/single-signup-v2/PlanCardSelector.test.tsx | import { render } from '@testing-library/react';
import { CYCLE, PLANS } from '@proton/shared/lib/constants';
import { PlansMap } from '@proton/shared/lib/interfaces';
import { PlanCard, PlanCardSelector } from './PlanCardSelector';
const onSelect = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
});
const defaultPlansMap: PlansMap = {
[PLANS.PASS_PLUS]: {
ID: 'id-123',
Type: 1,
Name: PLANS.PASS_PLUS,
Title: 'Pass Plus',
MaxDomains: 0,
MaxAddresses: 0,
MaxCalendars: 0,
MaxSpace: 0,
MaxMembers: 0,
MaxVPN: 0,
MaxTier: 0,
Services: 8,
Features: 0,
State: 1,
Pricing: {
'1': 499,
'12': 4788,
'24': 7176,
},
Currency: 'CHF',
Quantity: 1,
Offers: [],
Cycle: 1,
Amount: 499,
},
};
const defaultPlanCards: PlanCard[] = [
{
plan: PLANS.PASS_PLUS,
subsection: null,
type: 'best',
guarantee: true,
},
];
it('should render', () => {
const { container } = render(
<PlanCardSelector
cycle={CYCLE.MONTHLY}
currency="CHF"
plan={PLANS.PASS_PLUS}
onSelect={onSelect}
plansMap={defaultPlansMap}
planCards={defaultPlanCards}
/>
);
expect(container).toBeInTheDocument();
});
it('should display the discount price comparing against the monthly price', () => {
const { container } = render(
<PlanCardSelector
cycle={CYCLE.YEARLY}
currency="CHF"
plan={PLANS.PASS_PLUS}
onSelect={onSelect}
plansMap={defaultPlansMap}
planCards={defaultPlanCards}
/>
);
expect(container).toHaveTextContent('CHF 3.99');
expect(container.querySelector('.text-strike')).toHaveTextContent('CHF 4.99');
expect(container).toHaveTextContent('− 20%');
});
it('should display the discount price against the same cycle if it is discounted', () => {
const plansMap: PlansMap = {
...defaultPlansMap,
[PLANS.PASS_PLUS]: {
...defaultPlansMap[PLANS.PASS_PLUS],
Pricing: {
'1': 499,
'12': 1200,
'24': 7176,
},
} as any,
};
const { container } = render(
<PlanCardSelector
cycle={CYCLE.YEARLY}
currency="CHF"
plan={PLANS.PASS_PLUS}
onSelect={onSelect}
plansMap={plansMap}
planCards={defaultPlanCards}
/>
);
expect(container).toHaveTextContent('CHF 1');
expect(container.querySelector('.text-strike')).toHaveTextContent('CHF 4.99');
expect(container).toHaveTextContent('− 80%');
});
|
2,550 | 0 | petrpan-code/ProtonMail/WebClients/applications/calendar/src/app | petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/attendees.test.ts | import { SimpleMap } from '@proton/shared/lib/interfaces';
import { ContactEmail } from '@proton/shared/lib/interfaces/contacts';
import { DisplayNameEmail } from '../containers/calendar/interface';
import { getOrganizerDisplayData } from './attendees';
const generateDummyContactEmail = ({
email,
name,
contactEmailID,
contactID,
}: {
email: string;
name: string;
contactEmailID: string;
contactID: string;
}) => {
const result: ContactEmail = {
ID: contactEmailID,
Email: email,
Name: name,
Type: [],
Defaults: 0,
Order: 0,
ContactID: contactID,
LabelIDs: [],
LastUsedTime: 0,
};
return result;
};
describe('getOrganizerDisplayData()', () => {
const testEmail = '[email protected]';
const organizer = { email: testEmail, cn: 'The organizer' };
const isOrganizer = false;
const contacts = [
{ name: 'Unexpected match', email: testEmail, contactEmailID: '2', contactID: 'unexpected' },
{
name: 'Canonicalized match',
email: '[email protected]',
contactEmailID: '3',
contactID: 'internal',
},
{ name: 'A gmail match', email: 'te_ste-mail@proton,me', contactEmailID: '4', contactID: 'gmail' },
{ name: 'A lonely contact', email: '[email protected]', contactEmailID: '5', contactID: 'other' },
{ name: 'Expected match', email: '[email protected]', contactEmailID: '1', contactID: 'expected' },
];
// keys in contactsEmailMap are emails canonicalized with the generic scheme
const contactsEmailMap = contacts.reduce<SimpleMap<ContactEmail>>((acc, contact) => {
acc[contact.email] = generateDummyContactEmail(contact);
return acc;
}, {});
// keys in displayNameEmailMap are emails canonicalized by guess. In particular all Proton ones are canonicalized internally
const displayNameEmailMap: SimpleMap<DisplayNameEmail> = {
'[email protected]': { displayName: "It's me", displayEmail: '[email protected]' },
'[email protected]': { displayName: 'Lone star', displayEmail: '[email protected]' },
};
test('Distinguishes dots, hyphens and underscores, but not capitalization, to return correct contactId', () => {
const { contactID } = getOrganizerDisplayData(organizer, isOrganizer, contactsEmailMap, displayNameEmailMap);
expect(contactID).toEqual('expected');
});
test('Neither distinguishes dots, hyphens, underscores or capitalization, to return correct display name', () => {
const { title, name } = getOrganizerDisplayData(organizer, isOrganizer, contactsEmailMap, displayNameEmailMap);
expect(name).toEqual("It's me");
expect(title).toEqual("It's me <[email protected]>");
});
describe('when user is organiser', () => {
const isOrganizer = true;
test('Neither distinguish dots, hyphens, underscores nor capitalization, to return correct display name', () => {
expect(getOrganizerDisplayData(organizer, isOrganizer, contactsEmailMap, displayNameEmailMap)).toEqual({
name: 'You',
title: testEmail,
contactID: 'expected',
});
});
});
});
|
2,554 | 0 | petrpan-code/ProtonMail/WebClients/applications/calendar/src/app | petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/event.test.ts | import { MAX_ATTENDEES } from '@proton/shared/lib/calendar/constants';
import { ADDRESS_SEND } from '@proton/shared/lib/constants';
import { addressBuilder } from '@proton/testing/lib/builders';
import {
getCanChangeCalendarOfEvent,
getCanDeleteEvent,
getCanDuplicateEvent,
getCanEditEvent,
getCanEditSharedEventData,
getCanReplyToEvent,
getCannotSaveEvent,
getIsAvailableCalendar,
} from './event';
describe('getCannotSaveEvent()', () => {
test('Member cannot create invites in a shared calendar', () => {
const isOwnedCalendar = false;
const isOrganizer = true;
const numberOfAttendees = MAX_ATTENDEES - 1;
const canEditSharedEventData = true;
expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual(
true
);
});
test('Owner can create invites in a personal calendar', () => {
const isOwnedCalendar = true;
const isOrganizer = true;
const numberOfAttendees = MAX_ATTENDEES - 1;
const canEditSharedEventData = true;
expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual(
false
);
});
test('Owner cannot create invites with too many participants', () => {
const isOwnedCalendar = true;
const isOrganizer = true;
const numberOfAttendees = MAX_ATTENDEES + 1;
const canEditSharedEventData = true;
expect(
getCannotSaveEvent({
isOwnedCalendar,
isOrganizer,
numberOfAttendees,
canEditSharedEventData,
maxAttendees: MAX_ATTENDEES,
})
).toEqual(true);
});
test('Attendee can add notifications to invite in a personal calendar', () => {
const isOwnedCalendar = true;
const isOrganizer = false;
const numberOfAttendees = MAX_ATTENDEES - 1;
const canEditSharedEventData = false;
expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual(
false
);
});
test('Attendee can add notifications to invite in a shared calendar', () => {
const isOwnedCalendar = false;
const isOrganizer = false;
const numberOfAttendees = MAX_ATTENDEES - 1;
const canEditSharedEventData = false;
expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual(
false
);
});
test('Member can add notifications to an invite she organized in a shared calendar', () => {
const isOwnedCalendar = false;
const isOrganizer = true;
const numberOfAttendees = 10;
const canEditSharedEventData = false;
expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual(
false
);
});
});
describe('getCanEditEvent()', () => {
test('User can edit events only if the calendar is of known type and is not disabled', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isUnknownCalendar = !!(1 & i);
const isCalendarDisabled = !!(2 & i);
combinations.push({ isUnknownCalendar, isCalendarDisabled });
}
combinations.forEach(({ isUnknownCalendar, isCalendarDisabled }) => {
expect(
getCanEditEvent({
isUnknownCalendar,
isCalendarDisabled,
})
).toEqual(!isCalendarDisabled && !isUnknownCalendar);
});
});
});
describe('getCanDeleteEvent()', () => {
test('User cannot delete events in subscribed or other read-only calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOwnedCalendar = !!(1 & i);
const isInvitation = !!(2 & i);
combinations.push({ isOwnedCalendar, isInvitation });
}
combinations.forEach(({ isOwnedCalendar, isInvitation }) => {
expect(
getCanDeleteEvent({
isOwnedCalendar,
isCalendarWritable: false,
isInvitation,
})
).toEqual(false);
});
});
test('Attendee can delete invites in her own calendar', () => {
const isOwnedCalendar = true;
const isCalendarWritable = true;
const isInvitation = true;
expect(getCanDeleteEvent({ isOwnedCalendar, isCalendarWritable, isInvitation })).toEqual(true);
});
test('Member cannot delete invites in a shared calendar with edit rights', () => {
const isOwnedCalendar = false;
const isCalendarWritable = true;
const isInvitation = true;
expect(getCanDeleteEvent({ isOwnedCalendar, isCalendarWritable, isInvitation })).toEqual(false);
});
test('Member cannot delete invites in a shared calendar with view-only rights', () => {
const isOwnedCalendar = false;
const isCalendarWritable = false;
const isInvitation = true;
expect(getCanDeleteEvent({ isOwnedCalendar, isCalendarWritable, isInvitation })).toEqual(false);
});
});
describe('getCanEditSharedEventData()', () => {
const activeAddress = addressBuilder();
const cannotSendAddress = {
...activeAddress,
Send: ADDRESS_SEND.SEND_NO,
};
test('Owner can edit shared event data of events which are not invitations', () => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: true,
isCalendarWritable: true,
isOrganizer: false,
isAttendee: false,
isInvitation: false,
selfAddress: undefined,
})
).toEqual(true);
});
test('Owner can edit shared event data of events she organizes if the address is active', () => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: true,
isCalendarWritable: true,
isOrganizer: true,
isAttendee: false,
isInvitation: false,
selfAddress: activeAddress,
})
).toEqual(true);
});
test('Owner cannot edit shared event data of events she organizes if the address cannot send', () => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: true,
isCalendarWritable: true,
isOrganizer: true,
isAttendee: false,
isInvitation: true,
selfAddress: cannotSendAddress,
})
).toEqual(false);
});
test('User cannot edit shared event data in subscribed calendars or other read-only calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 3; i++) {
const isOrganizer = !!(1 & i);
const isAttendee = !!(2 & i);
const isInvitation = isOrganizer || isAttendee || !!(4 & i);
const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined;
combinations.push({ isOrganizer, isAttendee, isInvitation, selfAddress });
}
combinations.forEach(({ isOrganizer, isAttendee, isInvitation, selfAddress }) => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: true,
isCalendarWritable: false,
isOrganizer,
isAttendee,
isInvitation,
selfAddress,
})
).toEqual(false);
});
});
test('Member cannot edit shared event data in shared calendars with view-only rights', () => {
const combinations = [];
for (let i = 0; i < 2 ** 3; i++) {
const isOrganizer = !!(1 & i);
const isAttendee = !!(2 & i);
const isInvitation = isOrganizer || isAttendee || !!(4 & i);
const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined;
combinations.push({ isOrganizer, isAttendee, isInvitation, selfAddress });
}
combinations.forEach(({ isOrganizer, isAttendee, isInvitation, selfAddress }) => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: false,
isCalendarWritable: false,
isOrganizer,
isAttendee,
isInvitation,
selfAddress,
})
).toEqual(false);
});
});
test('Member with edit rights cannot edit shared event data of invitations', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOrganizer = !!(1 & i);
const isAttendee = !!(2 & i);
const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined;
combinations.push({ isOrganizer, isAttendee, selfAddress });
}
combinations.forEach(({ isOrganizer, isAttendee, selfAddress }) => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: false,
isCalendarWritable: true,
isOrganizer,
isAttendee,
isInvitation: true,
selfAddress,
})
).toEqual(false);
});
});
test('Member with view-only rights cannot edit invitations', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOrganizer = !!(1 & i);
const isAttendee = !!(2 & i);
const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined;
combinations.push({ isOrganizer, isAttendee, selfAddress });
}
combinations.forEach(({ isOrganizer, isAttendee, selfAddress }) => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: false,
isCalendarWritable: false,
isOrganizer,
isAttendee,
isInvitation: true,
selfAddress,
})
).toEqual(false);
});
});
test('User cannot edit invitations in owned calendars if she is not organizing or attending', () => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: true,
isCalendarWritable: true,
isOrganizer: false,
isAttendee: false,
isInvitation: true,
selfAddress: undefined,
})
).toEqual(false);
});
});
describe('getCanChangeCalendar()', () => {
test('User can change calendar of events that are not invitations', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOwnedCalendar = !!(1 & i);
const isSingleEdit = !!(2 & i);
combinations.push({ isOwnedCalendar, isSingleEdit });
}
combinations.forEach(({ isOwnedCalendar, isSingleEdit }) => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar,
isCalendarWritable: true,
isSingleEdit,
isInvitation: false,
isAttendee: false,
isOrganizer: false,
})
).toEqual(true);
});
});
test('User creating event can change calendar', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOwnedCalendar = !!(1 & i);
const isOrganizer = !!(2 & i);
const isInvitation = isOrganizer;
combinations.push({ isOwnedCalendar, isOrganizer, isInvitation });
}
combinations.forEach(({ isOwnedCalendar, isInvitation, isOrganizer }) => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: true,
isOwnedCalendar,
isCalendarWritable: true,
isSingleEdit: false,
isInvitation,
isAttendee: false,
isOrganizer,
})
).toEqual(true);
});
});
test('User cannot change calendar of event in non-writable calendar', () => {
const combinations = [];
for (let i = 0; i < 2 ** 5; i++) {
const isOwnedCalendar = !!(1 & i);
const isSingleEdit = !!(2 & i);
const isOrganizer = !!(4 & i);
const isAttendee = isOrganizer ? false : !!(8 & i);
const isInvitation = isOrganizer || isAttendee ? true : !!(16 & i);
combinations.push({ isOwnedCalendar, isSingleEdit, isInvitation, isOrganizer, isAttendee });
}
combinations.forEach(({ isOwnedCalendar, isSingleEdit, isInvitation, isOrganizer, isAttendee }) => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar,
isCalendarWritable: false,
isSingleEdit,
isInvitation,
isAttendee,
isOrganizer,
})
).toEqual(false);
});
});
test('Member cannot change calendar of non-organized invitation in shared calendar', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isSingleEdit = !!(1 & i);
const isAttendee = !!(2 & i);
combinations.push({ isSingleEdit, isAttendee });
}
combinations.forEach(({ isSingleEdit, isAttendee }) => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar: false,
isCalendarWritable: true,
isSingleEdit,
isInvitation: true,
isAttendee,
isOrganizer: false,
})
).toEqual(false);
});
});
test('Organizer cannot change calendar existing invitation', () => {
const combinations = [];
for (let i = 0; i < 2 ** 3; i++) {
const isOwnedCalendar = !!(1 & i);
const isCalendarWritable = !!(2 & i);
const isSingleEdit = !!(4 & i);
combinations.push({ isOwnedCalendar, isCalendarWritable, isSingleEdit });
}
combinations.forEach(({ isOwnedCalendar, isCalendarWritable, isSingleEdit }) => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar,
isCalendarWritable,
isSingleEdit,
isInvitation: true,
isAttendee: false,
isOrganizer: true,
})
).toEqual(false);
});
});
test('Attendee can change calendar in owned calendars if the event is not a single edit', () => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar: true,
isCalendarWritable: true,
isSingleEdit: false,
isInvitation: true,
isAttendee: true,
isOrganizer: false,
})
).toEqual(true);
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar: true,
isCalendarWritable: true,
isSingleEdit: true,
isInvitation: true,
isAttendee: true,
isOrganizer: false,
})
).toEqual(false);
});
});
describe('getIsAvailableCalendar()', () => {
test('User cannot change calendar of events to subscribed or other read-only calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOwnedCalendar = !!(1 & i);
const isInvitation = !!(2 & i);
combinations.push({ isOwnedCalendar, isInvitation });
}
combinations.forEach(({ isOwnedCalendar, isInvitation }) => {
expect(
getIsAvailableCalendar({
isOwnedCalendar,
isCalendarWritable: false,
isInvitation,
})
).toEqual(false);
});
});
test('Invitations can only be changed to owned calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOwnedCalendar = !!(1 & i);
const isCalendarWritable = isOwnedCalendar || !!(2 & i);
combinations.push({ isOwnedCalendar, isCalendarWritable });
}
combinations.forEach(({ isOwnedCalendar, isCalendarWritable }) => {
expect(
getIsAvailableCalendar({
isOwnedCalendar,
isCalendarWritable,
isInvitation: true,
})
).toEqual(isOwnedCalendar);
});
});
test('Events that are not invitations can be changed to writable calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 1; i++) {
const isOwnedCalendar = !!(1 & i);
const isCalendarWritable = isOwnedCalendar || !!(2 & i);
combinations.push({ isOwnedCalendar, isCalendarWritable });
}
combinations.forEach(({ isOwnedCalendar, isCalendarWritable }) => {
expect(
getIsAvailableCalendar({
isOwnedCalendar,
isCalendarWritable,
isInvitation: true,
})
).toEqual(isCalendarWritable);
});
});
});
describe('getCanDuplicateEvent()', () => {
test('User cannot duplicate events in unknown calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 4; i++) {
const isSubscribedCalendar = !!(1 & i);
const isOwnedCalendar = !!(2 & i);
const isOrganizer = !!(4 & i);
const isInvitation = !!(8 & i);
combinations.push({ isSubscribedCalendar, isOwnedCalendar, isOrganizer, isInvitation });
}
combinations.forEach(({ isSubscribedCalendar, isOwnedCalendar, isOrganizer, isInvitation }) => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: true,
isSubscribedCalendar,
isOwnedCalendar,
isInvitation,
isOrganizer,
})
).toEqual(false);
});
});
test('User cannot duplicate events in subscribed calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOrganizer = !!(1 & i);
const isInvitation = isOrganizer || !!(2 & i);
combinations.push({ isOrganizer, isInvitation });
}
combinations.forEach(({ isOrganizer, isInvitation }) => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: true,
isOwnedCalendar: true,
isInvitation,
isOrganizer,
})
).toEqual(false);
});
});
test('Owner can duplicate events that are not invitations', () => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: false,
isOwnedCalendar: true,
isInvitation: false,
isOrganizer: false,
})
).toEqual(true);
});
test('Owner can duplicate invitations that she is organizing', () => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: false,
isOwnedCalendar: true,
isInvitation: true,
isOrganizer: true,
})
).toEqual(true);
});
test('Owner cannot duplicate invitations if she is not the organizer', () => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: false,
isOwnedCalendar: true,
isInvitation: true,
isOrganizer: false,
})
).toEqual(false);
});
test('Member can duplicate events that are not invitations', () => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: false,
isOwnedCalendar: false,
isInvitation: false,
isOrganizer: false,
})
).toEqual(true);
});
test('Member cannot duplicate invitations', () => {
const combinations = [];
for (let i = 0; i < 2 ** 1; i++) {
const isOrganizer = !!(1 & i);
combinations.push({ isOrganizer });
}
combinations.forEach(({ isOrganizer }) => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: false,
isOwnedCalendar: false,
isInvitation: true,
isOrganizer,
})
).toEqual(false);
});
});
});
describe('getCanReplyToEvent()', () => {
test('User can reply to events he is invited in one of his own personal calendars if and only if the event is not cancelled', () => {
const combinations = [];
for (let i = 0; i < 2 ** 1; i++) {
const isCancelled = !!(1 & i);
combinations.push({ isCancelled });
}
combinations.forEach(({ isCancelled }) => {
expect(
getCanReplyToEvent({
isOwnedCalendar: true,
isCalendarWritable: true,
isAttendee: true,
isCancelled,
})
).toEqual(!isCancelled);
});
});
test('User cannot reply to events he is not attending', () => {
const combinations = [];
for (let i = 0; i < 2 ** 3; i++) {
const isOwnedCalendar = !!(1 & i);
const isCalendarWritable = isOwnedCalendar || !!(2 & i);
const isCancelled = !!(4 & i);
combinations.push({ isOwnedCalendar, isCalendarWritable, isCancelled });
}
combinations.forEach(({ isOwnedCalendar, isCalendarWritable, isCancelled }) => {
expect(
getCanReplyToEvent({
isOwnedCalendar,
isCalendarWritable,
isAttendee: false,
isCancelled,
})
).toEqual(false);
});
});
test('User cannot reply to invitations on subscribed calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 1; i++) {
const isCancelled = !!(1 & i);
combinations.push({ isCancelled });
}
combinations.forEach(({ isCancelled }) => {
expect(
getCanReplyToEvent({
isOwnedCalendar: true,
isCalendarWritable: false,
isAttendee: true,
isCancelled,
})
).toEqual(false);
});
});
test('User cannot reply to invitations on shared calendars, with or without edit rights', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isCalendarWritable = !!(1 & i);
const isCancelled = !!(2 & i);
combinations.push({ isCalendarWritable, isCancelled });
}
combinations.forEach(({ isCalendarWritable, isCancelled }) => {
expect(
getCanReplyToEvent({
isOwnedCalendar: false,
isCalendarWritable,
isAttendee: true,
isCancelled,
})
).toEqual(false);
});
});
});
|
2,716 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/hooks/useSelectionControls.test.ts | import { act, renderHook } from '@testing-library/react-hooks';
import { SelectionState, useSelectionControls } from './useSelectionControls';
const ALL_IDS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
describe('useSelection', () => {
let hook: {
current: ReturnType<typeof useSelectionControls>;
};
let rerenderHook: (props?: unknown) => void;
let itemIds = ALL_IDS;
beforeEach(() => {
const { result, rerender } = renderHook(() => useSelectionControls({ itemIds }));
hook = result;
rerenderHook = rerender;
});
it('toggleSelectItem', () => {
const itemIdToToggle = '1';
const secondItemIdToToggle = '2';
act(() => {
hook.current.toggleSelectItem(itemIdToToggle);
});
expect(hook.current.selectedItemIds).toMatchObject([itemIdToToggle]);
// Select new item
rerenderHook();
act(() => {
hook.current.toggleSelectItem(secondItemIdToToggle);
});
expect(hook.current.selectedItemIds).toMatchObject([itemIdToToggle, secondItemIdToToggle]);
// Unselect items one by one
rerenderHook();
act(() => {
hook.current.toggleSelectItem(itemIdToToggle);
hook.current.toggleSelectItem(secondItemIdToToggle);
});
rerenderHook();
expect(hook.current.selectedItemIds).toMatchObject([]);
});
it('toggleAllSelected', () => {
act(() => {
hook.current.toggleAllSelected();
});
expect(hook.current.selectedItemIds).toMatchObject(ALL_IDS);
});
it('toggleRange', () => {
act(() => {
hook.current.selectItem('3');
});
act(() => {
hook.current.toggleRange('5');
});
expect(hook.current.selectedItemIds).toMatchObject(['3', '4', '5']);
});
it('toggleRange with no selectItem before', () => {
act(() => {
hook.current.toggleRange('5');
});
expect(hook.current.selectedItemIds).toMatchObject(['5']);
});
it('selectItem', () => {
act(() => {
hook.current.selectItem('1');
});
act(() => {
hook.current.selectItem('3');
});
expect(hook.current.selectedItemIds).toMatchObject(['3']);
});
it('clearSelection', () => {
act(() => {
hook.current.toggleAllSelected();
});
act(() => {
hook.current.clearSelections();
});
expect(hook.current.selectedItemIds).toMatchObject([]);
});
it('isSelected', () => {
act(() => {
hook.current.selectItem('2');
});
expect(hook.current.isSelected('2')).toBe(true);
expect(hook.current.isSelected('1')).toBe(false);
});
it('selectionState', () => {
act(() => {
hook.current.selectItem('2');
hook.current.selectItem('1');
});
expect(hook.current.selectionState).toBe(SelectionState.SOME);
act(() => {
hook.current.toggleAllSelected();
});
expect(hook.current.selectionState).toBe(SelectionState.ALL);
act(() => {
hook.current.toggleAllSelected();
});
expect(hook.current.selectionState).toBe(SelectionState.NONE);
});
it('should reset multiSelectedStartId on itemIds changes', () => {
act(() => {
hook.current.selectItem('3');
});
itemIds = ['10', '11', '12'];
rerenderHook();
act(() => {
hook.current.toggleRange('10');
});
expect(hook.current.selectedItemIds).toMatchObject(['10']);
});
});
|
2,859 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/getCategorizedRevisions.test.ts | import { DriveFileRevision } from '../../store';
import { getCategorizedRevisions } from './getCategorizedRevisions';
describe('getCategorizedRevisions', () => {
beforeEach(() => {
jest.useFakeTimers().setSystemTime(new Date('2023-03-17T20:00:00'));
});
afterEach(() => {
jest.useRealTimers();
});
it('categorizes revisions correctly', () => {
const revisions = [
{ createTime: 1679058000 }, // March 17, 2023 at 2:00 PM
{ createTime: 1679036400 }, // March 17, 2023 at 7:00 AM
{ createTime: 1678968000 }, // March 16, 2023 at 12:00 PM
{ createTime: 1678986000 }, // March 16, 2023 at 5:00 PM
{ createTime: 1678950000 }, // March 16, 2023 at 7:00 AM
{ createTime: 1678777200 }, // March 14, 2023 at 7:00 AM
{ createTime: 1678431600 }, // March 10, 2023 at 7:00 AM
{ createTime: 1678172400 }, // March 7, 2023 at 7:00 AM
{ createTime: 1675753200 }, // February 7, 2023 at 7:00 AM
{ createTime: 1675234800 }, // February 1, 2023 at 7:00 AM
{ createTime: 1640415600 }, // December 25, 2021 at 7:00 AM
{ createTime: 1621926000 }, // May 25, 2021 at 7:00 AM
{ createTime: 1593500400 }, // June 30, 2020 at 7:00 AM
{ createTime: 1559372400 }, // June 1, 2019 at 7:00 AM
] as DriveFileRevision[];
const result = getCategorizedRevisions(revisions, 'en-US');
expect([...result.entries()]).toStrictEqual([
['today', { title: 'Today', list: [revisions[0], revisions[1]] }],
['yesterday', { title: 'Yesterday', list: [revisions[2], revisions[3], revisions[4]] }],
['d2', { title: 'Tuesday', list: [revisions[5]] }],
['last-week', { title: 'Last week', list: [revisions[6], revisions[7]] }],
['m1', { title: 'February', list: [revisions[8], revisions[9]] }],
['2021', { title: '2021', list: [revisions[10], revisions[11]] }],
['2020', { title: '2020', list: [revisions[12]] }],
['2019', { title: '2019', list: [revisions[13]] }],
]);
});
});
|
2,936 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/grid/formatVideoDuration.test.ts | import { formatVideoDuration } from './formatVideoDuration';
jest.mock('@proton/shared/lib/i18n', () => ({
dateLocale: {
code: 'en-US',
formatLong: {
time: jest.fn(),
},
},
}));
describe('formatVideoDuration()', () => {
it('format a duration without hours', () => {
const durationInSeconds = 65; // 1 minute and 5 seconds
const formattedDuration = formatVideoDuration(durationInSeconds);
expect(formattedDuration).toBe('1:05');
});
it('format a duration with hours', () => {
const durationInSeconds = 3665; // 1 hour, 1 minute, and 5 seconds
const formattedDuration = formatVideoDuration(durationInSeconds);
expect(formattedDuration).toBe('1:01:05');
});
it('format a duration in different locale', () => {
const durationInSeconds = 3665; // 1 hour, 1 minute, and 5 seconds
const formattedDuration = formatVideoDuration(durationInSeconds, 'fr-FR');
expect(formattedDuration).toBe('1:01:05');
});
});
|
2,940 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/hooks/usePhotosSelection.test.ts | import { act, renderHook } from '@testing-library/react-hooks';
import { isPhotoGroup } from '../../../../store/_photos';
import type { PhotoGroup } from '../../../../store/_photos/interface';
import { getGroupLinkIds, usePhotosSelection } from './usePhotosSelection';
const groups: Record<PhotoGroup, string[]> = {
group1: ['id1', 'id2', 'id3'],
group2: ['id4', 'id5'],
empty: [],
group3: ['id6'],
};
const makeItem = (linkId: string) => ({ linkId });
const data = Object.keys(groups).reduce<(string | ReturnType<typeof makeItem>)[]>((acc, item) => {
acc.push(item);
acc.push(...groups[item].map(makeItem));
return acc;
}, []);
const indexMap = data.reduce<Record<string, number>>((acc, item, index) => {
if (!isPhotoGroup(item)) {
acc[item.linkId] = index;
}
return acc;
}, {});
describe('usePhotosSelection', () => {
let hook: {
current: ReturnType<typeof usePhotosSelection>;
};
beforeEach(() => {
jest.resetAllMocks();
const { result } = renderHook(() => usePhotosSelection(data, indexMap));
hook = result;
expect(hook.current.selectedItems).toStrictEqual([]);
});
it('selects IDs', () => {
const input = ['id1', 'id2'];
const expected = input.map(makeItem);
act(() => {
hook.current.setSelected(true, ...input);
});
expect(hook.current.selectedItems).toStrictEqual(expected);
});
it('removes the IDs from the map', () => {
const input = ['id1', 'id2'];
const params = ['id1'];
const expected = ['id2'].map(makeItem);
act(() => {
hook.current.setSelected(true, ...input);
hook.current.setSelected(false, ...params);
});
expect(hook.current.selectedItems).toStrictEqual(expected);
});
it("does not fail when removing IDs that aren't in the state", () => {
const input = ['id1', 'id2'];
const params = ['not-in-state', 'blah'];
const expected = input.map(makeItem);
act(() => {
hook.current.setSelected(true, ...input);
hook.current.setSelected(false, ...params);
});
expect(hook.current.selectedItems).toStrictEqual(expected);
});
it("does not show IDs that aren't in the data", () => {
const input = ['id9001'];
const expected: any[] = [];
act(() => {
hook.current.setSelected(true, ...input);
});
expect(hook.current.selectedItems).toStrictEqual(expected);
});
it('clears selection', () => {
const input = ['id1', 'id2'];
const expected: any[] = [];
act(() => {
hook.current.setSelected(true, ...input);
hook.current.clearSelection();
});
expect(hook.current.selectedItems).toStrictEqual(expected);
});
describe('handleSelection', () => {
it('selects groups properly', () => {
const id = 'group1';
act(() => {
hook.current.handleSelection(
data.findIndex((group) => group === id),
{ isSelected: true }
);
});
expect(hook.current.selectedItems).toStrictEqual(groups[id].map(makeItem));
});
it('selects items properly', () => {
const id = 'id2';
const index = indexMap[id];
act(() => {
hook.current.handleSelection(index, { isSelected: true });
});
expect(hook.current.selectedItems).toStrictEqual([data[index]]);
});
});
describe('isGroupSelected', () => {
it('returns true for a fully selected group', () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, ...group);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe(true);
});
it("returns 'some' for a partially selected group (start not selected)", () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, ...group.slice(1, 2));
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe('some');
});
it("returns 'some' for a partially selected group (middle not selected)", () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, group[0], group[2]);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe('some');
});
it("returns 'some' for a partially selected group (end not selected)", () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, ...group.slice(0, 2));
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe('some');
});
it("returns 'some' if only the first item is selected", () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, group[0]);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe('some');
});
it("returns 'some' if only the last item is selected", () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, group[group.length - 1]);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe('some');
});
it('returns false for a non-selected group', () => {
const id = 'group1';
const group = groups[id];
const otherId = 'group2';
act(() => {
hook.current.setSelected(true, ...group);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === otherId))).toBe(false);
});
it('returns false for an empty group', () => {
const id = 'empty';
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe(false);
});
});
describe('isItemSelected', () => {
it('returns true for a selected item', () => {
const id = 'id1';
act(() => {
hook.current.setSelected(true, id);
});
expect(hook.current.isItemSelected(id)).toBe(true);
});
it('returns false for a non-selected item', () => {
const id = 'id1';
const otherId = 'id2';
act(() => {
hook.current.setSelected(true, id);
});
expect(hook.current.isItemSelected(otherId)).toBe(false);
});
});
describe('isMultiSelect', () => {
it('select multiple items', () => {
const id = 'id1';
const lastId = 'id6';
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === id),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.isItemSelected(id)).toBe(true);
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === lastId),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.selectedItems).toStrictEqual(data.filter((item) => typeof item !== 'string'));
});
it('select multiple items after selecting a group', () => {
const id = 'group1';
const lastId = 'id6';
act(() => {
hook.current.handleSelection(
data.findIndex((group) => group === id),
{ isSelected: true, isMultiSelect: true }
);
});
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === lastId),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.selectedItems).toStrictEqual(data.filter((item) => typeof item !== 'string'));
});
it('select multiple from higher index to lower', () => {
const id = 'id6';
const lastId = 'id1';
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === id),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.isItemSelected(id)).toBe(true);
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === lastId),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.selectedItems).toStrictEqual(data.filter((item) => typeof item !== 'string'));
});
it('unselect multiple items ', () => {
const id = 'id1';
const id2 = 'id2';
const lastId = 'id6';
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === id),
{ isSelected: true, isMultiSelect: true }
);
});
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === lastId),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.selectedItems).toStrictEqual(data.filter((item) => typeof item !== 'string'));
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === id2),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id || item === id2))).toBe(false);
});
});
});
describe('getGroupLinkIds', () => {
it('gets all group items', () => {
const id = 'group1';
act(() => {
const groupItems = getGroupLinkIds(
data,
data.findIndex((item) => item === id)
);
expect(groupItems).toStrictEqual(groups[id]);
});
});
it('handles empty groups', () => {
const id = 'empty';
act(() => {
const groupItems = getGroupLinkIds(
data,
data.findIndex((item) => item === id)
);
expect(groupItems).toStrictEqual([]);
});
});
it('handles the last group properly', () => {
const id = 'group3';
act(() => {
const groupItems = getGroupLinkIds(
data,
data.findIndex((item) => item === id)
);
expect(groupItems).toStrictEqual(groups[id]);
});
});
it('does not error on out-of-bounds groups', () => {
act(() => {
const groupItems = getGroupLinkIds(data, 9000);
expect(groupItems).toStrictEqual([]);
});
});
it('does not error on non-groups', () => {
const id = 'id1';
act(() => {
const groupItems = getGroupLinkIds(data, indexMap[id]);
expect(groupItems).toStrictEqual([]);
});
});
});
|
3,004 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/hooks | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/hooks/drive/useDesktopDownloads.test.tsx | import { expect, jest } from '@jest/globals';
import { renderHook } from '@testing-library/react-hooks';
import { fetchDesktopVersion } from '@proton/shared/lib/apps/desktopVersions';
import { appPlatforms } from '../../utils/appPlatforms';
import useDesktopDownloads from './useDesktopDownloads';
jest.mock('@proton/shared/lib/apps/desktopVersions');
const mockFetchDesktopVersion = jest.mocked(fetchDesktopVersion);
const originalConsoleWarn = console.warn;
const mockConsoleWarn = jest.fn();
describe('useDesktopDownloads', () => {
let hook: ReturnType<typeof renderHook<{}, ReturnType<typeof useDesktopDownloads>>>;
const render = async () => {
hook = renderHook(() => useDesktopDownloads());
await hook.waitForNextUpdate();
};
const assertOK = (
downloads: ReturnType<typeof useDesktopDownloads>['downloads'],
expectedUrls?: (string | undefined)[]
) => {
appPlatforms.forEach(({ platform, hideIfUnavailable }) => {
const index = downloads.findIndex((download) => download.platform === platform);
const download = downloads[index];
if (!download) {
if (hideIfUnavailable) {
return;
}
throw new Error(`Platform not present: ${platform}`);
}
expect(download.url).toBe(expectedUrls ? expectedUrls[index] : 'url');
expect(download.startDownload).toBeDefined();
});
};
beforeEach(async () => {
jest.resetAllMocks();
console.warn = mockConsoleWarn;
// Some default values for mocks
mockFetchDesktopVersion.mockResolvedValue({ url: 'url', version: '0.x' });
});
afterEach(() => {
console.warn = originalConsoleWarn;
});
it('should return downloads for each platform', async () => {
await render();
assertOK(hook.result.current.downloads);
});
it('should remove from list ONLY hidden platforms if all fetch calls fail', async () => {
mockFetchDesktopVersion.mockRejectedValue(new Error('oh no'));
await render();
assertOK(hook.result.current.downloads, [undefined, undefined]);
expect(mockConsoleWarn).toHaveBeenCalledTimes(appPlatforms.length);
});
it('should not remove from list platforms not marked for hiding', async () => {
mockFetchDesktopVersion
.mockRejectedValueOnce(new Error('oh no'))
.mockResolvedValueOnce({ url: 'url', version: '0.x' });
await render();
assertOK(hook.result.current.downloads, [undefined, 'url']);
expect(mockConsoleWarn).toHaveBeenCalledTimes(1);
});
});
|
3,032 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_devices/useDevicesListing.test.tsx | import { act, renderHook } from '@testing-library/react-hooks';
import { sendErrorReport } from '../../utils/errorHandling';
import { VolumesStateProvider } from '../_volumes/useVolumesState';
import { Device } from './interface';
import { useDevicesListingProvider } from './useDevicesListing';
const SHARE_ID_0 = 'shareId0';
const SHARE_ID_1 = 'shareId1';
const DEVICE_0: Device = {
id: '1',
volumeId: '1',
shareId: SHARE_ID_0,
linkId: 'linkId0',
name: 'HOME-DESKTOP',
modificationTime: Date.now(),
haveLegacyName: true,
};
const DEVICE_1: Device = {
id: '2',
volumeId: '1',
shareId: SHARE_ID_1,
linkId: 'linkId1',
name: 'Macbook Pro',
modificationTime: Date.now(),
haveLegacyName: true,
};
const DEVICE_2: Device = {
id: '3',
volumeId: '1',
shareId: SHARE_ID_1,
linkId: 'linkId1',
name: '',
modificationTime: Date.now(),
haveLegacyName: false,
};
const mockDevicesPayload = [DEVICE_0, DEVICE_1];
jest.mock('../../utils/errorHandling');
const mockedSendErrorReport = jest.mocked(sendErrorReport);
const mockedCreateNotification = jest.fn();
jest.mock('@proton/components/hooks', () => {
return {
useNotifications: jest.fn(() => ({ createNotification: mockedCreateNotification })),
};
});
const mockedLoadDevices = jest.fn().mockResolvedValue(mockDevicesPayload);
jest.mock('./useDevicesApi', () => {
const useDeviceApi = () => {
return {
loadDevices: mockedLoadDevices,
};
};
return useDeviceApi;
});
const mockedGetLink = jest.fn();
jest.mock('../_links', () => {
const useLink = jest.fn(() => ({
getLink: mockedGetLink,
}));
return { useLink };
});
describe('useLinksState', () => {
let hook: {
current: ReturnType<typeof useDevicesListingProvider>;
};
beforeEach(() => {
const wrapper = ({ children }: { children: React.ReactNode }) => (
<VolumesStateProvider>{children}</VolumesStateProvider>
);
mockedCreateNotification.mockClear();
mockedGetLink.mockClear();
mockedSendErrorReport.mockClear();
const { result } = renderHook(() => useDevicesListingProvider(), { wrapper });
hook = result;
});
it('finds device by shareId', async () => {
await act(async () => {
await hook.current.loadDevices(new AbortController().signal);
const device = hook.current.getDeviceByShareId(SHARE_ID_0);
expect(device).toEqual(DEVICE_0);
});
});
it('lists loaded devices', async () => {
await act(async () => {
await hook.current.loadDevices(new AbortController().signal);
const cachedDevices = hook.current.cachedDevices;
const targetList = [DEVICE_0, DEVICE_1];
expect(cachedDevices).toEqual(targetList);
});
});
it('should call getLink to get root link', async () => {
mockedLoadDevices.mockResolvedValue([DEVICE_2]);
await act(async () => {
const name = 'rootName';
mockedGetLink.mockResolvedValue({ name });
await hook.current.loadDevices(new AbortController().signal);
const cachedDevices = hook.current.cachedDevices;
const targetList = [{ ...DEVICE_2, name }];
expect(cachedDevices).toEqual(targetList);
expect(mockedGetLink).toHaveBeenCalled();
expect(mockedCreateNotification).not.toHaveBeenCalled();
expect(mockedSendErrorReport).not.toHaveBeenCalled();
});
});
it('should notify the user if there is a failure loading a link', async () => {
mockedLoadDevices.mockResolvedValue([DEVICE_2]);
await act(async () => {
mockedGetLink.mockRejectedValue('error');
await hook.current.loadDevices(new AbortController().signal);
const cachedDevices = hook.current.cachedDevices;
const targetList: Device[] = [];
expect(cachedDevices).toEqual(targetList);
expect(mockedGetLink).toHaveBeenCalled();
expect(mockedCreateNotification).toHaveBeenCalled();
expect(mockedSendErrorReport).toHaveBeenCalled();
});
});
});
|
3,044 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads/DownloadProvider/useDownloadControl.test.ts | import { act, renderHook } from '@testing-library/react-hooks';
import { FILE_CHUNK_SIZE, SupportedMimeTypes } from '@proton/shared/lib/drive/constants';
import { TransferState } from '../../../components/TransferManager/transfer';
import { LinkDownload } from '../interface';
import { Download } from './interface';
import useDownloadControl from './useDownloadControl';
function makeDownload(id: string, state: TransferState, links: LinkDownload[], setSize = true): Download {
return {
id,
startDate: new Date(),
state,
links,
meta: {
filename: links.length === 1 ? links[0].name : `My files.zip`,
mimeType: links.length === 1 ? links[0].mimeType : SupportedMimeTypes.zip,
size: setSize ? links.reduce((sum, link) => sum + link.size, 0) : undefined,
},
};
}
function makeDownloadLink(name: string, size = 2 * FILE_CHUNK_SIZE): LinkDownload {
return {
isFile: true,
shareId: 'shareId',
linkId: 'linkId',
name,
mimeType: 'text/plain',
size,
signatureAddress: 'address',
};
}
describe('useDownloadControl', () => {
const mockUpdateWithCallback = jest.fn();
const mockRemoveFromQueue = jest.fn();
const mockClearQueue = jest.fn();
const testDownloads: Download[] = [
makeDownload('init', TransferState.Initializing, [makeDownloadLink('init.txt')]),
makeDownload('pending', TransferState.Pending, [makeDownloadLink('pending.txt')]),
makeDownload('progress', TransferState.Progress, [makeDownloadLink('progress.txt', 2 * FILE_CHUNK_SIZE + 42)]),
makeDownload('progressMulti', TransferState.Progress, [
makeDownloadLink('progress1.txt'),
makeDownloadLink('progress2.txt'),
makeDownloadLink('progress3.txt'),
]),
makeDownload('big', TransferState.Progress, [makeDownloadLink('big.txt', 100 * FILE_CHUNK_SIZE)]),
makeDownload('done', TransferState.Done, [makeDownloadLink('done.txt')]),
];
beforeEach(() => {
mockUpdateWithCallback.mockClear();
mockRemoveFromQueue.mockClear();
mockClearQueue.mockClear();
});
it('calculates download block load', () => {
const { result: hook } = renderHook(() =>
useDownloadControl(testDownloads, mockUpdateWithCallback, mockRemoveFromQueue, mockClearQueue)
);
const controls = { start: jest.fn(), pause: jest.fn(), resume: jest.fn(), cancel: jest.fn() };
act(() => {
hook.current.add('progress', controls);
hook.current.updateProgress('progress', ['linkId'], FILE_CHUNK_SIZE);
expect(hook.current.calculateDownloadBlockLoad()).toBe(
// 2 progress (one chunk done above, one and a bit to go) + 2*3 progressMulti + 100 big
2 + 6 + 100
);
});
});
it('does not calculate download block load', () => {
const downloads = [
...testDownloads,
makeDownload('withoutSize', TransferState.Progress, [makeDownloadLink('withoutSize.txt')], false),
];
const { result: hook } = renderHook(() =>
useDownloadControl(downloads, mockUpdateWithCallback, mockRemoveFromQueue, mockClearQueue)
);
const controls = { start: jest.fn(), pause: jest.fn(), resume: jest.fn(), cancel: jest.fn() };
act(() => {
hook.current.add('progress', controls);
hook.current.updateProgress('progress', ['linkId'], FILE_CHUNK_SIZE);
expect(hook.current.calculateDownloadBlockLoad()).toBe(undefined);
});
});
it('keeps link progresses', () => {
const { result: hook } = renderHook(() =>
useDownloadControl(testDownloads, mockUpdateWithCallback, mockRemoveFromQueue, mockClearQueue)
);
const controls = { start: jest.fn(), pause: jest.fn(), resume: jest.fn(), cancel: jest.fn() };
act(() => {
hook.current.add('progress', controls);
// Start some progress before we know size.
hook.current.updateProgress('progress', ['linkId1'], 10);
hook.current.updateProgress('progress', ['linkId2'], 20);
hook.current.updateLinkSizes('progress', { linkId1: 12, linkId2: 34 });
// Continue some progress after we know size.
hook.current.updateProgress('progress', ['linkId2'], 5);
expect(hook.current.getLinksProgress()).toMatchObject({
linkId1: { progress: 10, total: 12 },
linkId2: { progress: 25, total: 34 },
});
});
});
});
|
3,047 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads/DownloadProvider/useDownloadQueue.test.ts | import { act, renderHook } from '@testing-library/react-hooks';
import { TransferState } from '../../../components/TransferManager/transfer';
import { LinkDownload } from '../interface';
import { Download, UpdateCallback, UpdateData, UpdateFilter, UpdateState } from './interface';
import useDownloadQueue from './useDownloadQueue';
function makeDownloadLink(name: string, isFile = true): LinkDownload {
return {
isFile,
shareId: 'shareId',
linkId: name,
name,
mimeType: isFile ? 'text/plain' : 'Folder',
size: 1234,
signatureAddress: 'address',
};
}
describe('useDownloadQueue', () => {
let hook: {
current: {
downloads: Download[];
add: (links: LinkDownload[]) => Promise<void>;
updateState: (idOrFilter: UpdateFilter, newStateOrCallback: UpdateState) => void;
updateWithData: (idOrFilter: UpdateFilter, newStateOrCallback: UpdateState, data: UpdateData) => void;
updateWithCallback: (
idOrFilter: UpdateFilter,
newStateOrCallback: UpdateState,
callback: UpdateCallback
) => void;
remove: (idOrFilter: UpdateFilter, callback?: UpdateCallback) => void;
};
};
let fileTransferId: string;
let folderTransferId: string;
let singleTransferIds: string[];
beforeEach(async () => {
const { result } = renderHook(() => useDownloadQueue());
hook = result;
await act(async () => {
await hook.current.add([makeDownloadLink('file.txt')]);
await hook.current.add([makeDownloadLink('folder', false)]);
await hook.current.add([makeDownloadLink('file.txt'), makeDownloadLink('folder', false)]);
});
fileTransferId = hook.current.downloads[0].id;
folderTransferId = hook.current.downloads[1].id;
singleTransferIds = [fileTransferId, folderTransferId];
});
it('adding same file transfer fails', async () => {
await act(async () => {
const promise = hook.current.add([makeDownloadLink('file.txt')]);
await expect(promise).rejects.toThrowError('File "file.txt" is already downloading');
});
});
it('adding same folder transfer fails', async () => {
await act(async () => {
const promise = hook.current.add([makeDownloadLink('folder', false)]);
await expect(promise).rejects.toThrowError('Folder "folder" is already downloading');
});
});
it('adding same files transfer fails', async () => {
await act(async () => {
const promise = hook.current.add([makeDownloadLink('file.txt'), makeDownloadLink('folder', false)]);
await expect(promise).rejects.toThrowError('File selection is already downloading');
});
});
it('adding different transfer', async () => {
await act(async () => {
const promise = hook.current.add([makeDownloadLink('file2.txt')]);
await expect(promise).resolves.toBe(undefined);
});
expect(hook.current.downloads.length).toBe(4);
});
it('updates state using id', () => {
act(() => {
hook.current.updateState(fileTransferId, TransferState.Canceled);
});
expect(hook.current.downloads.map(({ state }) => state)).toMatchObject([
TransferState.Canceled,
TransferState.Pending,
TransferState.Pending,
]);
});
it('updates state using filter', () => {
act(() => {
hook.current.updateState(({ id }) => singleTransferIds.includes(id), TransferState.Canceled);
});
expect(hook.current.downloads.map(({ state }) => state)).toMatchObject([
TransferState.Canceled,
TransferState.Canceled,
TransferState.Pending,
]);
});
it('updates state using callback', () => {
act(() => {
hook.current.updateState(
() => true,
({ id }) => (id === fileTransferId ? TransferState.Error : TransferState.Canceled)
);
});
expect(hook.current.downloads.map(({ state }) => state)).toMatchObject([
TransferState.Error,
TransferState.Canceled,
TransferState.Canceled,
]);
});
it('updates state with data', () => {
act(() => {
hook.current.updateWithData(fileTransferId, TransferState.Error, {
size: 42,
error: new Error('nope'),
signatureIssueLink: makeDownloadLink('name'),
signatureStatus: 2,
});
});
expect(hook.current.downloads[0]).toMatchObject({
state: TransferState.Error,
error: new Error('nope'),
meta: {
filename: 'file.txt',
mimeType: 'text/plain',
size: 42,
},
signatureIssueLink: makeDownloadLink('name'),
signatureStatus: 2,
});
});
it('updates state with callback', () => {
const mockCallback = jest.fn();
act(() => {
hook.current.updateWithCallback(
({ id }) => singleTransferIds.includes(id),
TransferState.Progress,
mockCallback
);
});
expect(mockCallback.mock.calls).toMatchObject([
[{ meta: { filename: 'file.txt' } }],
[{ meta: { filename: 'folder.zip' } }],
]);
});
it('removes transfer from the queue using id', () => {
const mockCallback = jest.fn();
act(() => {
hook.current.remove(fileTransferId, mockCallback);
});
expect(mockCallback.mock.calls).toMatchObject([[{ meta: { filename: 'file.txt' } }]]);
expect(hook.current.downloads).toMatchObject([
{
links: [{ linkId: 'folder' }],
},
{
links: [{ linkId: 'file.txt' }, { linkId: 'folder' }],
},
]);
});
it('removes transfer from the queue using filter', () => {
const mockCallback = jest.fn();
act(() => {
hook.current.remove(({ id }) => singleTransferIds.includes(id), mockCallback);
});
expect(mockCallback.mock.calls).toMatchObject([
[{ meta: { filename: 'file.txt' } }],
[{ meta: { filename: 'folder.zip' } }],
]);
expect(hook.current.downloads).toMatchObject([
{
links: [{ linkId: 'file.txt' }, { linkId: 'folder' }],
},
]);
});
});
|
3,050 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads/download/archiveGenerator.test.ts | import { fromUnixTime } from 'date-fns';
import { ReadableStream } from 'web-streams-polyfill';
import { asyncGeneratorToArray } from '../../../utils/test/generator';
import ArchiveGenerator from './archiveGenerator';
type TestLink = {
isFile: boolean;
name: string;
fileModifyTime?: number;
path?: string[];
expectedName?: string;
expectedPath?: string;
expectedLastModified?: Date;
};
async function* generateLinks(links: TestLink[]) {
for (let link of links) {
if (link.isFile) {
yield {
isFile: link.isFile,
name: link.name,
parentPath: link.path || [],
fileModifyTime: link.fileModifyTime,
stream: new ReadableStream<Uint8Array>(),
};
} else {
yield {
isFile: link.isFile,
name: link.name,
parentPath: link.path || [],
};
}
}
}
describe('ArchiveGenerator', () => {
beforeEach(() => {
jest.clearAllMocks();
});
const checkWritingLinks = async (links: TestLink[]) => {
const archiver = new ArchiveGenerator();
const transformedLinks = await asyncGeneratorToArray(archiver.transformLinksToZipItems(generateLinks(links)));
expect(transformedLinks).toMatchObject(
links.map((link) => {
const path = link.expectedPath || (link.path || []).join('/');
const fileName = link.expectedName || link.name;
const name = path ? `${path}/${fileName}` : fileName;
const lastModified =
link.expectedLastModified || (link.fileModifyTime && fromUnixTime(link.fileModifyTime));
return link.isFile
? {
name,
input: expect.anything(),
lastModified,
}
: {
name,
};
})
);
};
it('generates two files and one folder in the root', async () => {
await checkWritingLinks([
{ isFile: true, name: 'Hello.txt', fileModifyTime: 1692780131 },
{
isFile: true,
name: 'World.txt',
fileModifyTime: 1692780009,
expectedLastModified: new Date('2023-08-23T08:40:09.000Z'),
},
{ isFile: false, name: 'dir' },
]);
});
it('generates two files in the folder', async () => {
await checkWritingLinks([
{ isFile: false, name: 'dir' },
{ isFile: true, name: 'Hello.txt', path: ['dir'] },
{ isFile: true, name: 'World.txt', path: ['dir'] },
]);
});
it('generates two files with the same name', async () => {
await checkWritingLinks([
{ isFile: true, name: 'file.txt' },
{ isFile: true, name: 'file.txt', expectedName: 'file (1).txt' },
]);
});
it('generates two folder with the same name', async () => {
await checkWritingLinks([
{ isFile: false, name: 'dir' },
{ isFile: false, name: 'dir', expectedName: 'dir (1)' },
]);
});
it('generates file and folder with the same name', async () => {
await checkWritingLinks([
{ isFile: true, name: 'name' },
{ isFile: false, name: 'name', expectedName: 'name (1)' },
]);
});
// If file is written first, then folder is renamed.
it('generates file and folder with the same name in the folder', async () => {
await checkWritingLinks([
{ isFile: false, name: 'dir' },
{ isFile: true, name: 'name', path: ['dir'] },
{ isFile: false, name: 'name', path: ['dir'], expectedName: 'name (1)' },
{ isFile: false, name: 'subfolder', path: ['dir', 'name'], expectedPath: 'dir/name (1)' },
]);
});
// If folder is written first, then file is renamed.
it('generates folder and file with the same name in the folder', async () => {
await checkWritingLinks([
{ isFile: false, name: 'dir' },
{ isFile: false, name: 'name', path: ['dir'] },
{ isFile: true, name: 'name', path: ['dir'], expectedName: 'name (1)' },
{ isFile: false, name: 'subfolder', path: ['dir', 'name'] },
]);
});
it('generates many files with with the same name but different case', async () => {
await checkWritingLinks([
{ isFile: true, name: 'file.txt' },
{ isFile: true, name: 'File.txt', expectedName: 'File (1).txt' },
{ isFile: true, name: 'FILE.txt', expectedName: 'FILE (2).txt' },
{ isFile: true, name: 'file.TXT', expectedName: 'file (3).TXT' },
{ isFile: true, name: 'FILE.TXT', expectedName: 'FILE (4).TXT' },
{ isFile: true, name: 'File.Txt', expectedName: 'File (5).Txt' },
{ isFile: true, name: 'FilE.TxT', expectedName: 'FilE (6).TxT' },
]);
});
});
|
3,052 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads/download/concurrentIterator.test.ts | import { FILE_CHUNK_SIZE } from '@proton/shared/lib/drive/constants';
import { wait } from '@proton/shared/lib/helpers/promise';
import { asyncGeneratorToArray } from '../../../utils/test/generator';
import { MAX_DOWNLOADING_BLOCKS_LOAD, MAX_DOWNLOADING_FILES_LOAD } from '../constants';
import { DownloadCallbacks } from '../interface';
import ConcurrentIterator from './concurrentIterator';
import { NestedLinkDownload, StartedNestedLinkDownload } from './interface';
const mockDownloadLinkFile = jest.fn();
jest.mock('./downloadLinkFile', () => {
return (...args: any[]) => {
return mockDownloadLinkFile(...args);
};
});
async function* generateLinks(count: number, size = 123) {
for (let i = 0; i < count; i++) {
yield {
isFile: true,
size,
} as NestedLinkDownload;
}
}
describe('ConcurrentIterator', () => {
const mockStart = jest.fn();
const mockCancel = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
mockDownloadLinkFile.mockReturnValue({
start: mockStart,
cancel: mockCancel,
});
});
const checkPausingGeneratingLinks = async (
generator: AsyncGenerator<StartedNestedLinkDownload>,
callsBeforePause: number,
totalCalls: number
) => {
// Start consuming so we it can generate links and hit the pause.
const linksPromise = asyncGeneratorToArray(generator);
await wait(500); // 500ms should be enough to generate first batch.
// Now its in waiting mode and it waits to finish ongoing downloads.
expect(mockDownloadLinkFile).toBeCalledTimes(callsBeforePause);
expect(mockStart).toBeCalledTimes(callsBeforePause);
mockDownloadLinkFile.mock.calls.forEach(([link, { onProgress, onFinish }]) => {
onProgress('linkId', link.size);
onFinish();
});
// After finishing the previous batch, wait to generate the rest.
// Now without pausing because we don't have more than "two pages".
const links = await linksPromise;
expect(links.length).toBe(totalCalls);
expect(mockDownloadLinkFile).toBeCalledTimes(totalCalls);
expect(mockStart).toBeCalledTimes(totalCalls);
};
it('pauses when reaching MAX_DOWNLOADING_FILES_LOAD', async () => {
const c = new ConcurrentIterator();
const g = c.iterate(generateLinks(MAX_DOWNLOADING_FILES_LOAD * 2), {} as DownloadCallbacks);
await checkPausingGeneratingLinks(g, MAX_DOWNLOADING_FILES_LOAD, MAX_DOWNLOADING_FILES_LOAD * 2);
});
it('pauses when reaching MAX_DOWNLOADING_BLOCKS_LOAD', async () => {
const bigFileSize = FILE_CHUNK_SIZE * MAX_DOWNLOADING_BLOCKS_LOAD * 2;
const c = new ConcurrentIterator();
const g = c.iterate(generateLinks(2, bigFileSize), {} as DownloadCallbacks);
await checkPausingGeneratingLinks(g, 1, 2);
});
it('cancels from pause', async () => {
const bigFileSize = FILE_CHUNK_SIZE * MAX_DOWNLOADING_BLOCKS_LOAD * 2;
const c = new ConcurrentIterator();
const g = c.iterate(generateLinks(5, bigFileSize), {} as DownloadCallbacks);
// Start consuming so we it can generate links and hit the pause.
const linksPromise = asyncGeneratorToArray(g);
await wait(500); // 500ms should be enough to generate first batch.
c.cancel();
const links = await linksPromise;
expect(links.length).toBe(1);
expect(mockDownloadLinkFile).toBeCalledTimes(1);
expect(mockStart).toBeCalledTimes(1);
expect(mockCancel).toBeCalledTimes(1);
});
});
|
3,057 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads/download/downloadBlocks.test.ts | import { ReadableStream } from 'web-streams-polyfill';
import { createApiError, createOfflineError } from '@proton/shared/lib/fetch/ApiError';
import { DriveFileBlock } from '@proton/shared/lib/interfaces/drive/file';
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays';
import { TransferCancel } from '../../../components/TransferManager/transfer';
import { streamToBuffer } from '../../../utils/stream';
import * as constants from '../constants';
import initDownloadBlocks from './downloadBlocks';
const createNotFoundError = () => createApiError('Error', { status: 404, statusText: 'Not found.' } as Response, {});
const TIME_TO_RESET_RETRIES_LOCAL = 50; // Milliseconds.
jest.mock('../constants');
const mockConstants = constants as jest.MockedObject<typeof constants>;
let offlineURL = '';
let expiredURL = '';
let responseDelay = 0;
const createStreamResponse = (chunks: number[][]) =>
new ReadableStream<Uint8Array>({
start(ctrl) {
chunks.forEach((data) => ctrl.enqueue(new Uint8Array(data)));
ctrl.close();
},
});
const createGetBlocksResponse = (blocks: DriveFileBlock[], manifestSignature = '') => {
return {
blocks,
manifestSignature,
thumbnailHashes: [''],
};
};
const mockTransformBlockStream = async (abortSignal: AbortSignal, stream: ReadableStream<Uint8Array>) => {
return {
hash: [] as unknown as Uint8Array,
data: stream,
};
};
const mockDownloadBlock = jest.fn(
(abortController: AbortController, url: string): Promise<ReadableStream<Uint8Array>> => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url === offlineURL) {
reject(createOfflineError({}));
return;
}
if (url === expiredURL) {
reject(createNotFoundError());
return;
}
const response = {
'url:1': createStreamResponse([[1, 2], [3]]),
'url:2': createStreamResponse([[4], [5, 6]]),
'url:3': createStreamResponse([[7, 8, 9]]),
'url:4': createStreamResponse([[10, 11]]),
}[url];
if (!response) {
reject(new Error(`Unexpected url "${url}"`));
return;
}
resolve(response);
}, responseDelay);
});
}
);
describe('initDownload', () => {
beforeAll(() => {
jest.spyOn(global.console, 'warn').mockReturnValue();
});
beforeEach(() => {
mockDownloadBlock.mockClear();
mockConstants.TIME_TO_RESET_RETRIES = TIME_TO_RESET_RETRIES_LOCAL;
responseDelay = 0;
});
it('should download data from remote server using block metadata', async () => {
const downloadControls = initDownloadBlocks(
'filename',
{
getBlocks: async () =>
createGetBlocksResponse([
{
Index: 1,
BareURL: 'url:1',
Token: '1',
Hash: 'aewdsh',
},
{
Index: 2,
BareURL: 'url:2',
Token: '2',
Hash: 'aewdsh',
},
{
Index: 3,
BareURL: 'url:3',
Token: '3',
Hash: 'aewdsh',
},
]),
transformBlockStream: mockTransformBlockStream,
},
mockDownloadBlock
);
const stream = downloadControls.start();
const buffer = mergeUint8Arrays(await streamToBuffer(stream));
expect(buffer).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]));
});
it('should discard downloaded data and finish download on cancel', async () => {
const promise = new Promise<void>((resolve, reject) => {
const downloadControls = initDownloadBlocks(
'filename',
{
getBlocks: async () =>
createGetBlocksResponse([
{
Index: 1,
BareURL: 'url:1',
Token: '1',
Hash: 'aewdsh',
},
]),
transformBlockStream: mockTransformBlockStream,
onError: reject,
onFinish: () => resolve(),
},
mockDownloadBlock
);
downloadControls.start();
downloadControls.cancel();
});
await expect(promise).rejects.toThrowError(TransferCancel);
});
it('should reuse already downloaded data after recovering from network error', async () => {
// Make sure to not reset retries counter during the test.
mockConstants.TIME_TO_RESET_RETRIES = 10000;
offlineURL = 'url:2';
const downloadControls = initDownloadBlocks(
'filename',
{
getBlocks: async () =>
createGetBlocksResponse([
{
Index: 1,
BareURL: 'url:1',
Token: '1',
Hash: 'aewdsh',
},
{
Index: 2,
BareURL: 'url:2',
Token: '2',
Hash: 'ewqcd',
},
{
Index: 3,
BareURL: 'url:3',
Token: '3',
Hash: 'qwesd',
},
{
Index: 4,
BareURL: 'url:4',
Token: '4',
Hash: 'dqweda',
},
]),
transformBlockStream: mockTransformBlockStream,
onNetworkError: (err) => {
expect(err).toEqual(createOfflineError({}));
// Simulate connection is back up and user clicked to resume download.
offlineURL = '';
downloadControls.resume();
},
},
mockDownloadBlock
);
const stream = downloadControls.start();
const buffer = mergeUint8Arrays(await streamToBuffer(stream));
// Every block is streamed only once and in proper order even during interruption.
expect(buffer).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]));
// Non-failing blocks are downloaded only once.
expect(mockDownloadBlock.mock.calls.map(([, url]) => url)).toEqual([
'url:1',
'url:2', // First attempt.
'url:3',
'url:4',
// First retry (retry tries again all blocks in the queue).
'url:2',
'url:3',
'url:4',
// Second retry.
'url:2',
'url:3',
'url:4',
// Third retry.
'url:2',
'url:3',
'url:4',
// Second attempt after resume and fixing the issue.
'url:2',
]);
});
it('should retry on block expiry', async () => {
expiredURL = 'url:1';
let shouldValidateBlock = false;
const downloadControls = initDownloadBlocks(
'filename',
{
getBlocks: async () => {
if (shouldValidateBlock) {
expiredURL = '';
}
shouldValidateBlock = true;
return createGetBlocksResponse([
{
Index: 1,
BareURL: 'url:1',
Token: '1',
Hash: 'aewdsh',
},
]);
},
transformBlockStream: mockTransformBlockStream,
},
mockDownloadBlock
);
const stream = downloadControls.start();
const buffer = mergeUint8Arrays(await streamToBuffer(stream));
// Expired block is streamed once after retry.
expect(buffer).toEqual(new Uint8Array([1, 2, 3]));
// Expired block gets requested.
expect(mockDownloadBlock.mock.calls.map(([, url]) => url)).toEqual(['url:1', 'url:1']);
});
it('should re-request expired blocks', async () => {
// the download speed is sooo slow that the block will expire 4 times
const TIME_BLOCK_EXPIRES = 4;
// making sure response time is greater than
// consecutive retry counter threshold
responseDelay = TIME_TO_RESET_RETRIES_LOCAL * 2;
let blockRetryCount = 0;
expiredURL = 'url:1';
const downloadControls = initDownloadBlocks(
'filename',
{
getBlocks: async () => {
if (blockRetryCount === TIME_BLOCK_EXPIRES) {
expiredURL = '';
}
blockRetryCount++;
return createGetBlocksResponse([
{
Index: 1,
BareURL: 'url:1',
Token: '1',
Hash: 'aewdsh',
},
]);
},
transformBlockStream: mockTransformBlockStream,
},
mockDownloadBlock
);
const stream = downloadControls.start();
const buffer = mergeUint8Arrays(await streamToBuffer(stream));
expect(buffer).toEqual(new Uint8Array([1, 2, 3]));
// initial + TIME_BLOCK_EXPIRES
expect(mockDownloadBlock.mock.calls.length).toBe(1 + TIME_BLOCK_EXPIRES);
});
it('should request new block exactly three times if request fails consequentially', async () => {
expiredURL = 'url:1';
const downloadControls = initDownloadBlocks(
'filename',
{
getBlocks: async () => {
return createGetBlocksResponse([
{
Index: 1,
BareURL: expiredURL,
Token: '1',
Hash: 'aewdsh',
},
]);
},
transformBlockStream: mockTransformBlockStream,
},
mockDownloadBlock
);
const stream = downloadControls.start();
const bufferPromise = streamToBuffer(stream);
await expect(bufferPromise).rejects.toThrowError();
// 1 initial request + 3 retries
expect(mockDownloadBlock.mock.calls.length).toBe(4);
});
});
|
3,060 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_downloads/download/downloadLinkFolder.test.ts | import { ChildrenLinkMeta, LinkDownload } from '../interface';
import { FolderTreeLoader } from './downloadLinkFolder';
type Tree = {
[linkId: string]: Tree | number;
};
/**
* Key is linkId and name.
* Value is either
* - object representing folder's children,
* - or number representing file's size.
*/
const tree: Tree = {
linkId: {
a: {
ab: {
abc: {
'11': 123,
'12': 456,
'13': 789,
},
'21': 12,
'22': 0,
},
},
b: {
bc: {
bcd: {
bcde: {
'30': 147,
'31': 258,
},
'40': 963,
},
},
bd: {
'50': 2,
'51': 3,
},
},
'60': 7,
'61': 9,
},
};
const expectedTotalSize = 2769;
async function stubGetChildren(abortSignal: AbortSignal, shareId: string, linkId: string): Promise<ChildrenLinkMeta[]> {
const subtree = getSubtree(linkId, tree);
if (!subtree) {
throw new Error(`Wrong folder linkId: ${linkId}`);
}
return Object.entries(subtree).map(([linkId, value]) => {
const size = typeof value === 'number' ? value : undefined;
return makeChildrenLinkMeta(linkId, size);
});
}
function getSubtree(linkId: string, tree: Tree): Tree | undefined {
for (const key in tree) {
if (Object.prototype.hasOwnProperty.call(tree, key)) {
const value = tree[key];
if (typeof value === 'number') {
continue;
}
if (key === linkId) {
return value;
}
const found = getSubtree(linkId, value);
if (found) {
return found;
}
}
}
}
function makeChildrenLinkMeta(linkId: string, size?: number): ChildrenLinkMeta {
return {
isFile: size !== undefined,
linkId,
name: linkId,
mimeType: size !== undefined ? 'text/plain' : 'Folder',
size: size || 0,
signatureAddress: 'address',
fileModifyTime: 1692962760,
};
}
describe('FolderTreeLoader', () => {
const linkDownload = { shareId: 'shareId', linkId: 'linkId' } as LinkDownload;
it('calculates size', async () => {
const folderTreeLoader = new FolderTreeLoader(linkDownload);
const promise = folderTreeLoader.load(stubGetChildren);
await expect(promise).resolves.toMatchObject({
size: expectedTotalSize,
});
});
it('iterates all childs', async () => {
const folderTreeLoader = new FolderTreeLoader(linkDownload);
void folderTreeLoader.load(stubGetChildren);
const items = [];
for await (const item of folderTreeLoader.iterateAllChildren()) {
items.push(item);
}
items.sort((a, b) => a.name.localeCompare(b.name));
expect(items).toMatchObject([
{ linkId: '11', parentPath: ['a', 'ab', 'abc'] },
{ linkId: '12', parentPath: ['a', 'ab', 'abc'] },
{ linkId: '13', parentPath: ['a', 'ab', 'abc'] },
{ linkId: '21', parentPath: ['a', 'ab'] },
{ linkId: '22', parentPath: ['a', 'ab'] },
{ linkId: '30', parentPath: ['b', 'bc', 'bcd', 'bcde'] },
{ linkId: '31', parentPath: ['b', 'bc', 'bcd', 'bcde'] },
{ linkId: '40', parentPath: ['b', 'bc', 'bcd'] },
{ linkId: '50', parentPath: ['b', 'bd'] },
{ linkId: '51', parentPath: ['b', 'bd'] },
{ linkId: '60', parentPath: [] },
{ linkId: '61', parentPath: [] },
{ linkId: 'a', parentPath: [] },
{ linkId: 'ab', parentPath: ['a'] },
{ linkId: 'abc', parentPath: ['a', 'ab'] },
{ linkId: 'b', parentPath: [] },
{ linkId: 'bc', parentPath: ['b'] },
{ linkId: 'bcd', parentPath: ['b', 'bc'] },
{ linkId: 'bcde', parentPath: ['b', 'bc', 'bcd'] },
{ linkId: 'bd', parentPath: ['b'] },
]);
});
});
|
3,070 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_events/useDriveEventManager.test.ts | import { act } from 'react-dom/test-utils';
import { RenderResult, renderHook } from '@testing-library/react-hooks';
import { EVENT_TYPES } from '@proton/shared/lib/drive/constants';
import createEventManager, { EventManager } from '@proton/shared/lib/eventManager/eventManager';
import { Api } from '@proton/shared/lib/interfaces';
import { DriveEventsResult } from '@proton/shared/lib/interfaces/drive/events';
import { driveEventsResultToDriveEvents } from '../_api';
import { useDriveEventManagerProvider } from './useDriveEventManager';
const VOLUME_ID_1 = 'volumeId-1';
const VOLUME_ID_2 = 'volumeId-2';
const SHARE_1_EVENT = {
EventType: EVENT_TYPES.CREATE,
Link: { LinkID: 'linkId' },
ContextShareID: 'shareId-1',
};
const SHARE_2_EVENT = {
EventType: EVENT_TYPES.CREATE,
Link: { LinkID: 'linkId' },
ContextShareID: 'shareId-2',
};
const EVENT_PAYLOAD = {
EventID: 'event-id-1',
Events: [SHARE_1_EVENT, SHARE_2_EVENT],
Refresh: 0,
More: 0,
} as DriveEventsResult;
const apiMock = jest.fn().mockImplementation(() => Promise.resolve(EVENT_PAYLOAD));
describe('useDriveEventManager', () => {
let eventManager: EventManager;
let hook: RenderResult<ReturnType<typeof useDriveEventManagerProvider>>;
const renderTestHook = () => {
const { result } = renderHook(() => useDriveEventManagerProvider(apiMock as Api, eventManager));
return result;
};
beforeEach(() => {
apiMock.mockClear();
eventManager = createEventManager({ api: apiMock, eventID: '1' });
hook = renderTestHook();
});
afterEach(() => {
hook.current.clear();
});
it('subscribes to a share by id', async () => {
await act(async () => {
await hook.current.volumes.startSubscription(VOLUME_ID_1);
expect(hook.current.getSubscriptionIds()).toEqual([VOLUME_ID_1]);
await hook.current.volumes.startSubscription(VOLUME_ID_2);
expect(hook.current.getSubscriptionIds()).toEqual([VOLUME_ID_1, VOLUME_ID_2]);
});
});
it('unsubscribes from shares by id', async () => {
await act(async () => {
await hook.current.volumes.startSubscription(VOLUME_ID_1);
await hook.current.volumes.startSubscription(VOLUME_ID_2);
hook.current.volumes.unsubscribe(VOLUME_ID_2);
expect(hook.current.getSubscriptionIds()).toEqual([VOLUME_ID_1]);
});
});
it('registers event handlers', async () => {
const handler = jest.fn().mockImplementation(() => {});
await act(async () => {
await hook.current.volumes.startSubscription(VOLUME_ID_1);
hook.current.eventHandlers.register(handler);
await hook.current.pollEvents.volumes([VOLUME_ID_1]);
expect(handler).toBeCalledTimes(1);
});
});
it('registers multiple event handlers for one share', async () => {
const handler = jest.fn().mockImplementation(() => {});
const handler2 = jest.fn().mockImplementation(() => {});
await act(async () => {
await hook.current.volumes.startSubscription(VOLUME_ID_1);
hook.current.eventHandlers.register(handler);
hook.current.eventHandlers.register(handler2);
await hook.current.pollEvents.volumes([VOLUME_ID_1]);
expect(handler).toBeCalledTimes(1);
expect(handler2).toBeCalledTimes(1);
});
});
it('registers event handlers for multiple shares', async () => {
const handler = jest.fn().mockImplementation(() => {});
await act(async () => {
await hook.current.volumes.startSubscription(VOLUME_ID_2);
await hook.current.volumes.startSubscription(VOLUME_ID_1);
hook.current.eventHandlers.register(handler);
await hook.current.pollEvents.volumes(VOLUME_ID_1);
await hook.current.pollEvents.volumes(VOLUME_ID_2);
expect(handler).toBeCalledTimes(2);
});
});
it('removes handlers', async () => {
const handler = jest.fn().mockImplementation(() => {});
const handler2 = jest.fn().mockImplementation(() => {});
await act(async () => {
await hook.current.volumes.startSubscription(VOLUME_ID_1);
hook.current.eventHandlers.register(handler);
const handlerId = hook.current.eventHandlers.register(handler2);
hook.current.eventHandlers.unregister(handlerId);
await hook.current.pollEvents.volumes(VOLUME_ID_1);
expect(handler).toBeCalledTimes(1);
expect(handler2).toBeCalledTimes(0);
});
});
it('polls event', async () => {
await act(async () => {
await hook.current.volumes.startSubscription(VOLUME_ID_1);
await hook.current.pollEvents.volumes(VOLUME_ID_1);
expect(apiMock).toBeCalledTimes(2); // fetching events + poll itself
});
});
it("can poll events for all shares it's subscribed to", async () => {
const handler = jest.fn().mockImplementation(() => {});
await act(async () => {
await hook.current.volumes.startSubscription(VOLUME_ID_1);
await hook.current.volumes.startSubscription(VOLUME_ID_2);
hook.current.eventHandlers.register(handler);
await hook.current.pollEvents.driveEvents();
expect(handler).toBeCalledTimes(2);
expect(handler).toBeCalledWith(VOLUME_ID_1, driveEventsResultToDriveEvents(EVENT_PAYLOAD));
expect(handler).toBeCalledWith(VOLUME_ID_2, driveEventsResultToDriveEvents(EVENT_PAYLOAD));
});
});
});
|
3,072 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links/extendedAttributes.test.ts | import { FILE_CHUNK_SIZE } from '@proton/shared/lib/drive/constants';
import { mockGlobalFile, testFile } from '../../utils/test/file';
import {
ExtendedAttributes,
ParsedExtendedAttributes,
XAttrCreateParams,
createFileExtendedAttributes,
createFolderExtendedAttributes,
parseExtendedAttributes,
} from './extendedAttributes';
const emptyExtendedAttributes: ParsedExtendedAttributes = {
Common: {
ModificationTime: undefined,
Size: undefined,
BlockSizes: undefined,
},
};
describe('extended attrbiutes', () => {
beforeAll(() => {
jest.spyOn(global.console, 'warn').mockReturnValue();
});
beforeEach(() => {
mockGlobalFile();
});
it('creates the struct from the folder', () => {
const testCases: [Date, object][] = [
[
new Date(1234567890000),
{
Common: {
ModificationTime: '2009-02-13T23:31:30.000Z',
},
},
],
[new Date('2022-22-22'), {}],
];
testCases.forEach(([input, expectedAttributes]) => {
const xattrs = createFolderExtendedAttributes(input);
expect(xattrs).toMatchObject(expectedAttributes);
});
});
it('creates the struct from the file', () => {
const testCases: [XAttrCreateParams, ExtendedAttributes][] = [
[
{
file: testFile('testfile.txt', 123),
},
{
Common: {
ModificationTime: '2009-02-13T23:31:30.000Z',
Size: 123,
BlockSizes: [123],
},
},
],
[
{
file: testFile('testfile.txt', 123),
digests: { sha1: 'abcdef' },
},
{
Common: {
ModificationTime: '2009-02-13T23:31:30.000Z',
Size: 123,
BlockSizes: [123],
Digests: { SHA1: 'abcdef' },
},
},
],
[
{
file: testFile('testfile.txt', FILE_CHUNK_SIZE * 2 + 123),
media: { width: 100, height: 200 },
},
{
Common: {
ModificationTime: '2009-02-13T23:31:30.000Z',
Size: FILE_CHUNK_SIZE * 2 + 123,
BlockSizes: [FILE_CHUNK_SIZE, FILE_CHUNK_SIZE, 123],
},
Media: {
Width: 100,
Height: 200,
},
},
],
];
testCases.forEach(([input, expectedAttributes]) => {
const xattrs = createFileExtendedAttributes(input);
expect(xattrs).toMatchObject(expectedAttributes);
});
});
it('parses the struct', () => {
const testCases: [string, ParsedExtendedAttributes][] = [
['', emptyExtendedAttributes],
['{}', emptyExtendedAttributes],
['a', emptyExtendedAttributes],
[
'{"Common": {"ModificationTime": "2009-02-13T23:31:30+0000"}}',
{
Common: {
ModificationTime: 1234567890,
Size: undefined,
BlockSizes: undefined,
},
},
],
[
'{"Common": {"Size": 123}}',
{
Common: {
ModificationTime: undefined,
Size: 123,
BlockSizes: undefined,
},
},
],
[
'{"Common": {"ModificationTime": "2009-02-13T23:31:30+0000", "Size": 123, "BlockSizes": [1, 2, 3]}}',
{
Common: {
ModificationTime: 1234567890,
Size: 123,
BlockSizes: [1, 2, 3],
},
},
],
[
'{"Common": {"ModificationTime": "aa", "Size": 123}}',
{
Common: {
ModificationTime: undefined,
Size: 123,
BlockSizes: undefined,
},
},
],
[
'{"Common": {"ModificationTime": "2009-02-13T23:31:30+0000", "Size": "aaa"}}',
{
Common: {
ModificationTime: 1234567890,
Size: undefined,
BlockSizes: undefined,
},
},
],
[
'{"Common": {"ModificationTime": "2009-02-13T23:31:30+0000", "BlockSizes": "aaa"}}',
{
Common: {
ModificationTime: 1234567890,
Size: undefined,
BlockSizes: undefined,
},
},
],
[
'{"Common": {}, "Media": {}}',
{
Common: {
ModificationTime: undefined,
Size: undefined,
BlockSizes: undefined,
},
},
],
[
'{"Common": {}, "Media": {"Width": "aa", "Height": "aa"}}',
{
Common: {
ModificationTime: undefined,
Size: undefined,
BlockSizes: undefined,
},
},
],
[
'{"Common": {}, "Media": {"Width": 100, "Height": "aa"}}',
{
Common: {
ModificationTime: undefined,
Size: undefined,
BlockSizes: undefined,
},
},
],
[
'{"Common": {}, "Media": {"Width": 100, "Height": 200}}',
{
Common: {
ModificationTime: undefined,
Size: undefined,
BlockSizes: undefined,
},
Media: {
Width: 100,
Height: 200,
},
},
],
[
'{"Common": {"Digests": {}}',
{
Common: {
ModificationTime: undefined,
Size: undefined,
BlockSizes: undefined,
Digests: undefined,
},
},
],
[
'{"Common": {"Digests": {"SHA1": null}}}',
{
Common: {
ModificationTime: undefined,
Size: undefined,
BlockSizes: undefined,
Digests: undefined,
},
},
],
[
'{"Common": {"Digests": {"SHA1": "abcdef"}}}',
{
Common: {
ModificationTime: undefined,
Size: undefined,
BlockSizes: undefined,
Digests: {
SHA1: 'abcdef',
},
},
},
],
];
testCases.forEach(([input, expectedAttributes]) => {
const xattrs = parseExtendedAttributes(input);
expect(xattrs).toMatchObject(expectedAttributes);
});
});
});
|
3,076 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links/link.test.ts | import { adjustName, splitLinkName } from './link';
describe('adjustName', () => {
it('should add index to a file with extension', () => {
expect(adjustName(3, 'filename', 'ext')).toBe('filename (3).ext');
});
it('should add index to a file without extension', () => {
expect(adjustName(3, 'filename')).toBe('filename (3)');
expect(adjustName(3, 'filename', '')).toBe('filename (3)');
expect(adjustName(3, 'filename.')).toBe('filename. (3)');
expect(adjustName(3, '.filename.')).toBe('.filename. (3)');
});
it('should add index to a file without name', () => {
expect(adjustName(3, '', 'ext')).toBe('.ext (3)');
});
it('should leave zero-index filename with extension unchanged', () => {
expect(adjustName(0, 'filename', 'ext')).toBe('filename.ext');
});
it('should leave zero-index filename without extension unchanged', () => {
expect(adjustName(0, 'filename')).toBe('filename');
expect(adjustName(0, 'filename', '')).toBe('filename');
expect(adjustName(0, 'filename.')).toBe('filename.');
expect(adjustName(0, '.filename.')).toBe('.filename.');
});
it('should leave zero-index filename without name unchanged', () => {
expect(adjustName(0, '', 'ext')).toBe('.ext');
});
});
describe('splitLinkName', () => {
it('should split file name and extension', () => {
expect(splitLinkName('filename.ext')).toEqual(['filename', 'ext']);
});
it('should split file name without extension', () => {
expect(splitLinkName('filename')).toEqual(['filename', '']);
expect(splitLinkName('filename.')).toEqual(['filename.', '']);
});
it('should split file name without name', () => {
expect(splitLinkName('.ext')).toEqual(['', 'ext']);
});
});
|
3,078 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links/useLink.test.ts | import { act, renderHook } from '@testing-library/react-hooks';
import { RESPONSE_CODE } from '@proton/shared/lib/drive/constants';
import { decryptSigned } from '@proton/shared/lib/keys/driveKeys';
import { decryptPassphrase } from '@proton/shared/lib/keys/drivePassphrase';
import { ShareType } from '../_shares';
import { useLinkInner } from './useLink';
jest.mock('@proton/shared/lib/keys/driveKeys');
jest.mock('@proton/shared/lib/keys/drivePassphrase');
const mockRequest = jest.fn();
jest.mock('../_api/useDebouncedRequest', () => {
const useDebouncedRequest = () => {
return mockRequest;
};
return useDebouncedRequest;
});
jest.mock('../_utils/useDebouncedFunction', () => {
const useDebouncedFunction = () => {
return (wrapper: any) => wrapper();
};
return useDebouncedFunction;
});
describe('useLink', () => {
const mockFetchLink = jest.fn();
const mockLinksKeys = {
getPassphrase: jest.fn(),
setPassphrase: jest.fn(),
getPassphraseSessionKey: jest.fn(),
setPassphraseSessionKey: jest.fn(),
getPrivateKey: jest.fn(),
setPrivateKey: jest.fn(),
getSessionKey: jest.fn(),
setSessionKey: jest.fn(),
getHashKey: jest.fn(),
setHashKey: jest.fn(),
};
const mockLinksState = {
getLink: jest.fn(),
setLinks: jest.fn(),
setCachedThumbnail: jest.fn(),
};
const mockGetVerificationKey = jest.fn();
const mockGetSharePrivateKey = jest.fn();
const mockGetShare = jest.fn();
const mockDecryptPrivateKey = jest.fn();
const abortSignal = new AbortController().signal;
let hook: {
current: ReturnType<typeof useLinkInner>;
};
beforeAll(() => {
// Time relative function can have issue with test environments
// To prevent hanging async function we use Timer Mocks from jest
// https://jestjs.io/docs/timer-mocks
jest.useFakeTimers();
});
beforeEach(() => {
jest.resetAllMocks();
global.URL.createObjectURL = jest.fn(() => 'blob:objecturl');
// @ts-ignore
decryptSigned.mockImplementation(({ armoredMessage }) =>
Promise.resolve({ data: `dec:${armoredMessage}`, verified: 1 })
);
// @ts-ignore
decryptPassphrase.mockImplementation(({ armoredPassphrase }) =>
Promise.resolve({
decryptedPassphrase: `decPass:${armoredPassphrase}`,
sessionKey: `sessionKey:${armoredPassphrase}`,
verified: 1,
})
);
mockGetSharePrivateKey.mockImplementation((_, shareId) => `privateKey:${shareId}`);
mockDecryptPrivateKey.mockImplementation(({ armoredKey: nodeKey }) => `privateKey:${nodeKey}`);
const { result } = renderHook(() =>
useLinkInner(
mockFetchLink,
mockLinksKeys,
mockLinksState,
mockGetVerificationKey,
mockGetSharePrivateKey,
mockGetShare,
mockDecryptPrivateKey
)
);
hook = result;
});
it('returns decrypted version from the cache', async () => {
const item = { name: 'name' };
mockLinksState.getLink.mockReturnValue({ decrypted: item });
await act(async () => {
const link = hook.current.getLink(abortSignal, 'shareId', 'linkId');
await expect(link).resolves.toMatchObject(item);
});
expect(mockLinksState.getLink).toBeCalledWith('shareId', 'linkId');
expect(mockFetchLink).not.toBeCalled();
});
it('decrypts when missing decrypted version in the cache', async () => {
mockLinksState.getLink.mockReturnValue({
encrypted: { linkId: 'linkId', parentLinkId: undefined, name: 'name' },
});
await act(async () => {
const link = hook.current.getLink(abortSignal, 'shareId', 'linkId');
await expect(link).resolves.toMatchObject({
linkId: 'linkId',
name: 'dec:name',
});
});
expect(mockLinksState.getLink).toBeCalledWith('shareId', 'linkId');
expect(mockFetchLink).not.toBeCalled();
});
it('decrypts link with parent link', async () => {
const generateLink = (id: string, parentId?: string) => {
return {
linkId: `${id}`,
parentLinkId: parentId,
name: `name ${id}`,
nodeKey: `nodeKey ${id}`,
nodePassphrase: `nodePassphrase ${id}`,
};
};
const links: Record<string, ReturnType<typeof generateLink>> = {
root: generateLink('root'),
parent: generateLink('parent', 'root'),
link: generateLink('link', 'parent'),
};
mockLinksState.getLink.mockImplementation((_, linkId) => ({ encrypted: links[linkId] }));
await act(async () => {
const link = hook.current.getLink(abortSignal, 'shareId', 'link');
await expect(link).resolves.toMatchObject({
linkId: 'link',
name: 'dec:name link',
});
});
expect(mockFetchLink).not.toBeCalled();
expect(mockLinksState.getLink.mock.calls.map(([, linkId]) => linkId)).toMatchObject([
'link', // Called by getLink.
'link', // Called by getEncryptedLink.
'parent', // Called by getLinkPrivateKey.
'parent', // Called by getLinkPassphraseAndSessionKey.
'root', // Called by getLinkPrivateKey.
'root', // Called by getLinkPassphraseAndSessionKey.
]);
// Decrypt passphrases so we can decrypt private keys for the root and the parent.
// @ts-ignore
expect(decryptPassphrase.mock.calls.map(([{ armoredPassphrase }]) => armoredPassphrase)).toMatchObject([
'nodePassphrase root',
'nodePassphrase parent',
]);
expect(mockDecryptPrivateKey.mock.calls.map(([{ armoredKey: nodeKey }]) => nodeKey)).toMatchObject([
'nodeKey root',
'nodeKey parent',
]);
// With the parent key is decrypted the name of the requested link.
expect(
// @ts-ignore
decryptSigned.mock.calls.map(([{ privateKey, armoredMessage }]) => [privateKey, armoredMessage])
).toMatchObject([['privateKey:nodeKey parent', 'name link']]);
});
describe('root name', () => {
const LINK_NAME = 'LINK_NAME';
const tests = [
{ type: ShareType.standard, name: `dec:${LINK_NAME}` },
{ type: ShareType.default, name: 'My files' },
{ type: ShareType.photos, name: 'Photos' },
];
tests.forEach(({ type, name }) => {
it(`detects type ${type} as "${name}"`, async () => {
const link = {
linkId: `root`,
name: LINK_NAME,
nodeKey: `nodeKey root`,
nodePassphrase: `nodePassphrase root`,
};
mockLinksState.getLink.mockImplementation(() => ({ encrypted: link }));
mockGetShare.mockImplementation((_, shareId) => ({
shareId,
rootLinkId: link.linkId,
type,
}));
await act(async () => {
const link = hook.current.getLink(abortSignal, 'shareId', 'root');
await expect(link).resolves.toMatchObject({
linkId: 'root',
name,
});
});
});
});
});
it('fetches link from API and decrypts when missing in the cache', async () => {
mockFetchLink.mockReturnValue(Promise.resolve({ linkId: 'linkId', parentLinkId: undefined, name: 'name' }));
await act(async () => {
const link = hook.current.getLink(abortSignal, 'shareId', 'linkId');
await expect(link).resolves.toMatchObject({
linkId: 'linkId',
name: 'dec:name',
});
});
expect(mockLinksState.getLink).toBeCalledWith('shareId', 'linkId');
expect(mockFetchLink).toBeCalledTimes(1);
});
it('skips failing fetch if already attempted before', async () => {
const err = { data: { Code: RESPONSE_CODE.NOT_FOUND } };
mockFetchLink.mockRejectedValue(err);
const link = hook.current.getLink(abortSignal, 'shareId', 'linkId');
await expect(link).rejects.toMatchObject(err);
const link2 = hook.current.getLink(abortSignal, 'shareId', 'linkId');
await expect(link2).rejects.toMatchObject(err);
const link3 = hook.current.getLink(abortSignal, 'shareId', 'linkId2');
await expect(link3).rejects.toMatchObject(err);
expect(mockLinksState.getLink).toBeCalledWith('shareId', 'linkId');
expect(mockFetchLink).toBeCalledTimes(2); // linkId once and linkId2
});
it('skips load of already cached thumbnail', async () => {
const downloadCallbackMock = jest.fn();
mockLinksState.getLink.mockReturnValue({
decrypted: {
name: 'name',
cachedThumbnailUrl: 'url',
},
});
await act(async () => {
await hook.current.loadLinkThumbnail(abortSignal, 'shareId', 'linkId', downloadCallbackMock);
});
expect(mockRequest).not.toBeCalled();
expect(downloadCallbackMock).not.toBeCalled();
expect(mockLinksState.setCachedThumbnail).not.toBeCalled();
});
it('loads link thumbnail using cached link thumbnail info', async () => {
const downloadCallbackMock = jest.fn().mockReturnValue(
Promise.resolve({
contents: Promise.resolve(undefined),
verifiedPromise: Promise.resolve(1),
})
);
mockLinksState.getLink.mockReturnValue({
decrypted: {
name: 'name',
hasThumbnail: true,
activeRevision: {
thumbnail: {
bareUrl: 'bareUrl',
token: 'token',
},
},
},
});
await act(async () => {
await hook.current.loadLinkThumbnail(abortSignal, 'shareId', 'linkId', downloadCallbackMock);
});
expect(downloadCallbackMock).toBeCalledWith('bareUrl', 'token');
expect(mockLinksState.setCachedThumbnail).toBeCalledWith('shareId', 'linkId', expect.any(String));
expect(mockRequest).not.toBeCalled();
});
it('loads link thumbnail with expired cached link thumbnail info', async () => {
mockRequest.mockReturnValue({
ThumbnailBareURL: 'bareUrl',
ThumbnailToken: 'token2', // Requested new non-expired token.
});
const downloadCallbackMock = jest.fn().mockImplementation((url: string, token: string) =>
token === 'token'
? Promise.reject('token expired')
: Promise.resolve({
contents: Promise.resolve(undefined),
verifiedPromise: Promise.resolve(1),
})
);
mockLinksState.getLink.mockReturnValue({
decrypted: {
name: 'name',
hasThumbnail: true,
activeRevision: {
thumbnail: {
bareUrl: 'bareUrl',
token: 'token', // Expired token.
},
},
},
});
await act(async () => {
await hook.current.loadLinkThumbnail(abortSignal, 'shareId', 'linkId', downloadCallbackMock);
});
expect(downloadCallbackMock).toBeCalledWith('bareUrl', 'token'); // First attempted with expired token.
expect(mockRequest).toBeCalledTimes(1); // Then requested the new token.
expect(downloadCallbackMock).toBeCalledWith('bareUrl', 'token2'); // And the new one used for final download.
expect(mockLinksState.setCachedThumbnail).toBeCalledWith('shareId', 'linkId', expect.any(String));
});
it('loads link thumbnail with its url on API', async () => {
mockRequest.mockReturnValue({
ThumbnailBareURL: 'bareUrl',
ThumbnailToken: 'token',
});
const downloadCallbackMock = jest.fn().mockReturnValue(
Promise.resolve({
contents: Promise.resolve(undefined),
verifiedPromise: Promise.resolve(1),
})
);
mockLinksState.getLink.mockReturnValue({
decrypted: {
name: 'name',
hasThumbnail: true,
activeRevision: {
id: 'revisionId',
},
},
});
await act(async () => {
await hook.current.loadLinkThumbnail(abortSignal, 'shareId', 'linkId', downloadCallbackMock);
});
expect(mockRequest).toBeCalledTimes(1);
expect(downloadCallbackMock).toBeCalledWith('bareUrl', 'token');
expect(mockLinksState.setCachedThumbnail).toBeCalledWith('shareId', 'linkId', expect.any(String));
});
it('decrypts badly signed thumbnail block', async () => {
mockLinksState.getLink.mockReturnValue({
encrypted: {
linkId: 'link',
},
decrypted: {
linkId: 'link',
name: 'name',
hasThumbnail: true,
activeRevision: {
id: 'revisionId',
},
},
});
mockRequest.mockReturnValue({
ThumbnailBareURL: 'bareUrl',
ThumbnailToken: 'token',
});
const downloadCallbackMock = jest.fn().mockReturnValue(
Promise.resolve({
contents: Promise.resolve(undefined),
verifiedPromise: Promise.resolve(2),
})
);
await act(async () => {
await hook.current.loadLinkThumbnail(abortSignal, 'shareId', 'link', downloadCallbackMock);
});
expect(mockLinksState.setLinks).toBeCalledWith('shareId', [
expect.objectContaining({
encrypted: expect.objectContaining({
linkId: 'link',
signatureIssues: { thumbnail: 2 },
}),
}),
]);
});
describe('decrypts link meta data with signature issues', () => {
beforeEach(() => {
const generateLink = (id: string, parentId?: string) => {
return {
linkId: `${id}`,
parentLinkId: parentId,
name: `name ${id}`,
nodeKey: `nodeKey ${id}`,
nodeHashKey: `nodeHashKey ${id}`,
nodePassphrase: `nodePassphrase ${id}`,
};
};
const links: Record<string, ReturnType<typeof generateLink>> = {
root: generateLink('root'),
parent: generateLink('parent', 'root'),
link: generateLink('link', 'parent'),
};
mockLinksState.getLink.mockImplementation((_, linkId) => ({ encrypted: links[linkId] }));
});
it('decrypts badly signed passphrase', async () => {
// @ts-ignore
decryptPassphrase.mockReset();
// @ts-ignore
decryptPassphrase.mockImplementation(({ armoredPassphrase }) =>
Promise.resolve({
decryptedPassphrase: `decPass:${armoredPassphrase}`,
sessionKey: `sessionKey:${armoredPassphrase}`,
verified: 2,
})
);
await act(async () => {
await hook.current.getLink(abortSignal, 'shareId', 'link');
});
['root', 'parent'].forEach((linkId) => {
expect(mockLinksState.setLinks).toBeCalledWith('shareId', [
expect.objectContaining({
encrypted: expect.objectContaining({
linkId,
signatureIssues: { passphrase: 2 },
}),
}),
]);
});
});
it('decrypts badly signed hash', async () => {
// @ts-ignore
decryptSigned.mockReset();
// @ts-ignore
decryptSigned.mockImplementation(({ armoredMessage }) =>
Promise.resolve({ data: `dec:${armoredMessage}`, verified: 2 })
);
mockGetVerificationKey.mockReturnValue([]);
await act(async () => {
await hook.current.getLinkHashKey(abortSignal, 'shareId', 'parent');
});
expect(mockLinksState.setLinks).toBeCalledWith('shareId', [
expect.objectContaining({
encrypted: expect.objectContaining({
linkId: 'parent',
signatureIssues: { hash: 2 },
}),
}),
]);
});
it('decrypts badly signed name', async () => {
// @ts-ignore
decryptSigned.mockReset();
// @ts-ignore
decryptSigned.mockImplementation(({ armoredMessage }) =>
Promise.resolve({ data: `dec:${armoredMessage}`, verified: 2 })
);
await act(async () => {
await hook.current.getLink(abortSignal, 'shareId', 'link');
});
expect(mockLinksState.setLinks).toBeCalledWith('shareId', [
expect.objectContaining({
decrypted: expect.objectContaining({
linkId: 'link',
signatureIssues: { name: 2 },
}),
}),
]);
});
});
});
|
3,082 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links/useLinksActions.test.tsx | import { renderHook } from '@testing-library/react-hooks';
import { RESPONSE_CODE } from '@proton/shared/lib/drive/constants';
import isTruthy from '@proton/utils/isTruthy';
import { VolumesStateProvider } from '../_volumes/useVolumesState';
import { useLinksActions } from './useLinksActions';
jest.mock('@proton/components/hooks/usePreventLeave', () => {
const usePreventLeave = () => {
return {
preventLeave: (fn: any) => fn,
};
};
return usePreventLeave;
});
jest.mock('../_events/useDriveEventManager', () => {
const useDriveEventManager = () => {
return {
pollEvents: {
volumes: () => Promise.resolve(),
},
};
};
return {
useDriveEventManager,
};
});
jest.mock('./useLinksState', () => {
const useLinksState = () => {
return {
lockLinks: () => {},
lockTrash: () => {},
unlockLinks: () => {},
};
};
return useLinksState;
});
jest.mock('../_crypto/useDriveCrypto', () => {
const useDriveCrypto = () => {
return {
getPrimaryAddressKey: () => {},
getOwnAddressAndPrimaryKeys: () => {},
};
};
return useDriveCrypto;
});
jest.mock('./useLink', () => {
const useLink = () => {
return {
getLink: () => {},
getLinkPassphraseAndSessionKey: () => {},
getLinkPrivateKey: () => {},
getLinkHashKey: () => {},
};
};
return useLink;
});
const mockRequest = jest.fn();
const mockGetLinks = jest.fn();
const mockQueryTrashLinks = jest.fn();
const mockQueryRestoreLinks = jest.fn();
const mockQueryDeleteTrashedLinks = jest.fn();
const mockGetShare = jest.fn();
const mockGetDefaultShare = jest.fn();
jest.mock('./useLinks', () => {
const useLink = () => {
return {
getLinks: mockGetLinks,
};
};
return useLink;
});
jest.mock('../_api/useDebouncedRequest', () => {
const useDebouncedRequest = () => {
return mockRequest;
};
return useDebouncedRequest;
});
jest.mock('../_shares/useShare', () => {
const useShare = () => {
return {
getShare: mockGetShare,
};
};
return useShare;
});
jest.mock('../_shares/useDefaultShare', () => {
const useDefaultShare = () => {
return {
getDefaultShare: mockGetDefaultShare,
};
};
return useDefaultShare;
});
const SHARE_ID_0 = 'shareId00';
const SHARE_ID_1 = 'shareId01';
const VOLUME_ID = 'volumeId00';
// TODO: Test suite incomplete
// covers operations allowing using links from multiple shares
describe('useLinksActions', () => {
let hook: {
current: ReturnType<typeof useLinksActions>;
};
beforeEach(() => {
jest.resetAllMocks();
mockRequest.mockImplementation((linkIds: string[]) => {
return Promise.resolve({
Responses: linkIds.map(() => ({
Response: {
Code: RESPONSE_CODE.SUCCESS,
},
})),
});
});
mockQueryTrashLinks.mockImplementation((shareId, parentLinkId, linkIds) => linkIds);
mockQueryRestoreLinks.mockImplementation((shareId, linkIds) => linkIds);
mockQueryDeleteTrashedLinks.mockImplementation((shareId, linkIds) => linkIds);
mockGetShare.mockImplementation((ac, shareId) => ({ shareId }));
mockGetDefaultShare.mockImplementation(() => ({ volumeId: VOLUME_ID }));
const wrapper = ({ children }: { children: React.ReactNode }) => (
<VolumesStateProvider>{children}</VolumesStateProvider>
);
const { result } = renderHook(
() =>
useLinksActions({
queries: {
queryTrashLinks: mockQueryTrashLinks,
queryRestoreLinks: mockQueryRestoreLinks,
queryDeleteTrashedLinks: mockQueryDeleteTrashedLinks,
queryEmptyTrashOfShare: jest.fn(),
queryDeleteChildrenLinks: jest.fn(),
},
}),
{ wrapper }
);
hook = result;
});
it('trashes links from different shares', async () => {
/*
shareId00
└── link00
├── link01
│ ├── link03 x
│ └── link04 x
└── link02
└── link05 x
shareId01
└── link10
├── link01
| └── link12 x <-- non-unique parent link id
└── link11
├── link13
└── link14 x
*/
const ac = new AbortController();
const result = await hook.current.trashLinks(ac.signal, [
{ shareId: SHARE_ID_0, linkId: 'linkId03', parentLinkId: 'linkId01' },
{ shareId: SHARE_ID_0, linkId: 'linkId04', parentLinkId: 'linkId01' },
{ shareId: SHARE_ID_0, linkId: 'linkId05', parentLinkId: 'linkId02' },
{ shareId: SHARE_ID_1, linkId: 'linkId14', parentLinkId: 'linkId11' },
{ shareId: SHARE_ID_1, linkId: 'linkId12', parentLinkId: 'linkId01' },
]);
// ensure api requests are invoked by correct groups
expect(mockQueryTrashLinks).toBeCalledWith(SHARE_ID_0, 'linkId01', ['linkId03', 'linkId04']);
expect(mockQueryTrashLinks).toBeCalledWith(SHARE_ID_0, 'linkId02', ['linkId05']);
expect(mockQueryTrashLinks).toBeCalledWith(SHARE_ID_1, 'linkId01', ['linkId12']);
expect(mockQueryTrashLinks).toBeCalledWith(SHARE_ID_1, 'linkId11', ['linkId14']);
// verify all requested links were processed
expect(result.successes.sort()).toEqual(['linkId03', 'linkId04', 'linkId05', 'linkId12', 'linkId14'].sort());
});
it('restores links from different shares', async () => {
/*
shareId00
└── link00
├── linkId01 <
│ ├── linkId03
│ └── linkId04 <
shareId01
└── linkId10
└── linkId11 <
*/
// emulate partial state
const state: Record<string, any> = {
linkId01: {
rootShareId: SHARE_ID_0,
linkId: 'linkId01',
trashed: 3,
},
linkId04: {
rootShareId: SHARE_ID_0,
linkId: 'linkId04',
trashed: 1,
},
linkId11: {
rootShareId: SHARE_ID_1,
linkId: 'linkId11',
trashed: 3,
},
};
mockGetLinks.mockImplementation(async (signal, ids: { linkId: string }[]) => {
return ids.map((idGroup) => state[idGroup.linkId]).filter(isTruthy);
});
const ac = new AbortController();
const result = await hook.current.restoreLinks(ac.signal, [
{ shareId: SHARE_ID_0, linkId: 'linkId01' },
{ shareId: SHARE_ID_0, linkId: 'linkId04' },
{ shareId: SHARE_ID_1, linkId: 'linkId11' },
]);
expect(mockQueryRestoreLinks).toBeCalledWith(SHARE_ID_0, [
'linkId01',
'linkId04', // this link has been deleted before link linkId, thus restored last
]);
expect(mockQueryRestoreLinks).toBeCalledWith(SHARE_ID_1, ['linkId11']);
expect(result.successes.sort()).toEqual(['linkId01', 'linkId04', 'linkId11'].sort());
});
it('deletes trashed links from different shares', async () => {
/*
shareId00
└── link00
├── linkId01 x
│ ├── linkId03
│ └── linkId04 x
shareId01
└── linkId10
└── linkId11 x
*/
const ac = new AbortController();
const result = await hook.current.deleteTrashedLinks(ac.signal, [
{ shareId: SHARE_ID_0, linkId: 'linkId01' },
{ shareId: SHARE_ID_0, linkId: 'linkId04' },
{ shareId: SHARE_ID_1, linkId: 'linkId11' },
]);
expect(mockQueryDeleteTrashedLinks).toBeCalledWith(SHARE_ID_0, ['linkId01', 'linkId04']);
expect(mockQueryDeleteTrashedLinks).toBeCalledWith(SHARE_ID_1, ['linkId11']);
expect(result.successes.sort()).toEqual(['linkId01', 'linkId04', 'linkId11'].sort());
});
});
|
3,084 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links/useLinksKeys.test.tsx | import { LinksKeys } from './useLinksKeys';
describe('useLinksKeys', () => {
let keys: LinksKeys;
beforeEach(() => {
keys = new LinksKeys();
});
it('returns empty passphrase when not set', () => {
keys.setPassphrase('shareId', 'linkId', 'pass');
expect(keys.getPassphrase('shareId', 'missingLinkId')).toBe(undefined);
});
it('returns the cached passphrase', () => {
keys.setPassphrase('shareId', 'linkId', 'pass');
expect(keys.getPassphrase('shareId', 'linkId')).toBe('pass');
});
it('setting another key for the same link does not remove the other key', () => {
const hashKey = new Uint8Array([1, 2]);
keys.setPassphrase('shareId', 'linkId', 'pass');
keys.setHashKey('shareId', 'linkId', hashKey);
expect(keys.getPassphrase('shareId', 'linkId')).toBe('pass');
expect(keys.getHashKey('shareId', 'linkId')).toBe(hashKey);
});
it('setting the key again overrides the original value', () => {
keys.setPassphrase('shareId', 'linkId', 'pass');
keys.setPassphrase('shareId', 'linkId', 'newpass');
expect(keys.getPassphrase('shareId', 'linkId')).toBe('newpass');
});
});
|
3,086 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links/useLinksQueue.test.tsx | import { act, renderHook } from '@testing-library/react-hooks';
import { useLinksQueue } from './useLinksQueue';
const mockedLoadLinksMeta = jest.fn();
jest.mock('./useLinksListing', () => ({
useLinksListing: () => ({
loadLinksMeta: mockedLoadLinksMeta,
}),
}));
const mockedGetLink = jest.fn();
jest.mock('./useLinksState', () => ({
__esModule: true,
default: () => ({
getLink: mockedGetLink,
}),
}));
jest.useFakeTimers();
jest.spyOn(global, 'setTimeout');
const mockedAbort = jest.fn();
let mockedAbortSignal = { aborted: false };
// @ts-ignore - not mocking the entire AbortSignal, sorry =)
global.AbortController = jest.fn(() => ({
signal: mockedAbortSignal,
abort: mockedAbort,
}));
const SHARE_ID = 'shareId';
const getLinkIds = (count: number) => [...Array(count).keys()].map((id) => `linkId-${id}`);
const getFakeRef: <T>(value: T) => React.MutableRefObject<T> = (value) => ({ current: value });
describe('useLinksQueue', () => {
let hook: {
current: ReturnType<typeof useLinksQueue>;
};
let unmountHook: () => void;
beforeEach(() => {
const { result, unmount } = renderHook(() => useLinksQueue());
hook = result;
unmountHook = unmount;
jest.clearAllTimers();
jest.clearAllMocks();
mockedGetLink.mockReset();
mockedLoadLinksMeta.mockReset();
mockedAbort.mockReset();
mockedAbortSignal.aborted = false;
mockedGetLink.mockImplementation(() => undefined);
});
it('should not add to queue if link is already in state', async () => {
mockedGetLink.mockImplementation((shareId, linkId) => ({
shareId,
linkId,
}));
await act(async () => {
hook.current.addToQueue(SHARE_ID, 'linkId');
});
expect(setTimeout).not.toHaveBeenCalled();
});
it('should not add to queue if linkId is already in queue', async () => {
await act(async () => {
hook.current.addToQueue(SHARE_ID, 'linkId');
hook.current.addToQueue(SHARE_ID, 'linkId');
});
expect(setTimeout).toHaveBeenCalledTimes(1);
});
it('should debounce processing to wait for the queue to fill up', async () => {
const items = getLinkIds(7);
await act(async () => {
items.forEach((item) => hook.current.addToQueue(SHARE_ID, item));
});
jest.runAllTimers();
expect(setTimeout).toHaveBeenCalledTimes(items.length);
expect(mockedLoadLinksMeta).toHaveBeenCalledTimes(1);
});
it('should not load links if the domRef is null', async () => {
await act(async () => {
hook.current.addToQueue(SHARE_ID, 'linkId', getFakeRef(null));
});
jest.runAllTimers();
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(mockedLoadLinksMeta).not.toHaveBeenCalled();
});
it('should abort when the hook is unmounted', async () => {
await act(async () => {
hook.current.addToQueue(SHARE_ID, 'linkId');
});
jest.runAllTimers();
unmountHook();
expect(mockedAbort).toHaveBeenCalled();
});
it('should not load links if aborted', async () => {
mockedAbortSignal.aborted = true;
await act(async () => {
hook.current.addToQueue(SHARE_ID, 'linkId');
});
jest.runAllTimers();
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(mockedLoadLinksMeta).not.toHaveBeenCalled();
});
it('should not infinite loop if loadLinksMeta fails', async () => {
// Silence console errors
const consoleErrorMock = jest.spyOn(console, 'error').mockImplementation(() => {});
mockedLoadLinksMeta.mockRejectedValue(new Error('oh no'));
await act(async () => {
hook.current.addToQueue(SHARE_ID, 'linkId');
});
await jest.runAllTimersAsync();
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(mockedLoadLinksMeta).toHaveBeenCalledTimes(1);
expect(consoleErrorMock).toHaveBeenCalledTimes(1);
consoleErrorMock.mockRestore();
}, 1000);
});
|
3,088 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links/useLinksState.test.tsx | import { act, renderHook } from '@testing-library/react-hooks';
import { EVENT_TYPES } from '@proton/shared/lib/drive/constants';
import { DriveEvents } from '../_events';
import { DecryptedLink, EncryptedLink, LinkShareUrl } from './interface';
import {
Link,
LinksState,
addOrUpdate,
deleteLinks,
setCachedThumbnailUrl,
setLock,
updateByEvents,
useLinksStateProvider,
} from './useLinksState';
jest.mock('../_events/useDriveEventManager', () => {
const useDriveEventManager = () => {
return {
eventHandlers: {
register: () => 'id',
unregister: () => false,
},
};
};
return {
useDriveEventManager,
};
});
function generateTestLink(id: string, parentId: string | undefined, decrypted = false): Link {
return {
encrypted: {
linkId: id,
name: id,
parentLinkId: parentId,
},
decrypted: decrypted
? {
linkId: id,
name: id,
parentLinkId: parentId,
}
: undefined,
} as Link;
}
function getLockedIds(state: LinksState): string[] {
return Object.values(state.shareId.links)
.filter(({ decrypted }) => decrypted?.isLocked)
.map(({ encrypted }) => encrypted.linkId);
}
function generateEvents(events: any[]): DriveEvents {
return {
eventId: 'eventId',
events: events.map(([eventType, encryptedLink]) => ({ eventType, encryptedLink })),
refresh: false,
};
}
describe('useLinksState', () => {
let state: LinksState;
beforeEach(() => {
state = {
shareId: {
links: {
linkId0: generateTestLink('linkId0', undefined),
linkId1: generateTestLink('linkId1', 'linkId0'),
linkId2: generateTestLink('linkId2', 'linkId1'),
linkId3: generateTestLink('linkId3', 'linkId1'),
linkId4: generateTestLink('linkId4', 'linkId0'),
linkId5: generateTestLink('linkId5', 'linkId4'),
linkId6: generateTestLink('linkId6', 'linkId4'),
linkId7: generateTestLink('linkId7', 'linkId0', true),
linkId8: generateTestLink('linkId8', 'linkId7', true),
linkId9: generateTestLink('linkId9', 'linkId7', true),
},
tree: {
linkId0: ['linkId1', 'linkId4', 'linkId7'],
linkId1: ['linkId2', 'linkId3'],
linkId4: ['linkId5', 'linkId6'],
linkId7: ['linkId8', 'linkId9'],
},
},
};
});
it('deletes links', () => {
const result = deleteLinks(state, 'shareId', ['linkId1', 'linkId2', 'linkId6', 'linkId8', 'linkId9']);
// Removed links from links.
expect(Object.keys(result.shareId.links)).toMatchObject(['linkId0', 'linkId4', 'linkId5', 'linkId7']);
// Removed parent from tree.
expect(Object.keys(result.shareId.tree)).toMatchObject(['linkId0', 'linkId4', 'linkId7']);
// Removed children from tree.
expect(result.shareId.tree.linkId4).toMatchObject(['linkId5']);
});
it('adds new encrypted link', () => {
const result = addOrUpdate(state, 'shareId', [
{
encrypted: {
linkId: 'newLink',
name: 'newLink',
parentLinkId: 'linkId1',
} as EncryptedLink,
},
]);
// Added to links.
expect(result.shareId.links.newLink).toMatchObject({
encrypted: { linkId: 'newLink' },
});
// Added to tree as child to its parent.
expect(result.shareId.tree.linkId1).toMatchObject(['linkId2', 'linkId3', 'newLink']);
});
it('adds link to new share', () => {
const result = addOrUpdate(state, 'shareId2', [
{
encrypted: {
linkId: 'newLink',
name: 'newLink',
parentLinkId: 'linkId1',
} as EncryptedLink,
},
]);
// Added new link to links.
expect(result.shareId2.links.newLink).toMatchObject({
encrypted: { linkId: 'newLink' },
});
// Added parent to tree.
expect(Object.keys(result.shareId2.tree)).toMatchObject(['linkId1']);
expect(result.shareId2.tree.linkId1).toMatchObject(['newLink']);
});
it('updates encrypted link', () => {
const result = addOrUpdate(state, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'new name',
parentLinkId: 'linkId0',
} as EncryptedLink,
},
]);
expect(result.shareId.links.linkId7).toMatchObject({
decrypted: { linkId: 'linkId7', name: 'linkId7', isStale: true },
encrypted: { linkId: 'linkId7' },
});
});
it('updates encrypted link without need to re-decrypt', () => {
const result = addOrUpdate(state, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'linkId7',
parentLinkId: 'linkId0',
} as EncryptedLink,
},
]);
expect(result.shareId.links.linkId7).toMatchObject({
decrypted: { linkId: 'linkId7', name: 'linkId7', isStale: false },
encrypted: { linkId: 'linkId7' },
});
});
it('updates encrypted link with different parent', () => {
const result = addOrUpdate(state, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'linkId7',
parentLinkId: 'linkId6',
} as EncryptedLink,
},
]);
// Updated link in links.
expect(result.shareId.links.linkId7).toMatchObject({
decrypted: { linkId: 'linkId7', isStale: true }, // Changing parent requires to re-decrypt again.
encrypted: { linkId: 'linkId7' },
});
// Updated original parent tree.
expect(result.shareId.tree.linkId0).toMatchObject(['linkId1', 'linkId4']);
// Updated new parent tree.
expect(result.shareId.tree.linkId6).toMatchObject(['linkId7']);
});
it('updates decrypted link', () => {
const result = addOrUpdate(state, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'new name',
parentLinkId: 'linkId0',
} as EncryptedLink,
decrypted: {
linkId: 'linkId7',
name: 'new name',
parentLinkId: 'linkId0',
} as DecryptedLink,
},
]);
expect(result.shareId.links.linkId7).toMatchObject({
decrypted: { linkId: 'linkId7', name: 'new name' },
encrypted: { linkId: 'linkId7' },
});
});
it('updates trashed link', () => {
const result1 = addOrUpdate(state, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'linkId7',
parentLinkId: 'linkId0',
trashed: 12345678,
} as EncryptedLink,
},
{
encrypted: {
linkId: 'linkId8',
name: 'linkId8',
parentLinkId: 'linkId7',
trashed: 123456789,
} as EncryptedLink,
},
]);
expect(result1.shareId.links.linkId7).toMatchObject({
decrypted: { linkId: 'linkId7', name: 'linkId7', isStale: false },
encrypted: { linkId: 'linkId7' },
});
// Trashed link is removed from the parent.
expect(result1.shareId.tree.linkId0).toMatchObject(['linkId1', 'linkId4']);
// Trashed parent trashes automatically also children.
expect(result1.shareId.links.linkId7.encrypted.trashed).toBe(12345678);
expect(result1.shareId.links.linkId7.encrypted.trashedByParent).toBeFalsy();
expect(result1.shareId.links.linkId8.encrypted.trashed).toBe(123456789);
expect(result1.shareId.links.linkId8.encrypted.trashedByParent).toBeFalsy();
expect(result1.shareId.links.linkId9.encrypted.trashed).toBe(12345678);
expect(result1.shareId.links.linkId9.encrypted.trashedByParent).toBeTruthy();
// Restoring from trash re-adds link back to its parent.
const result2 = addOrUpdate(result1, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'linkId7',
parentLinkId: 'linkId0',
trashed: null,
} as EncryptedLink,
},
]);
expect(result2.shareId.tree.linkId0).toMatchObject(['linkId1', 'linkId4', 'linkId7']);
// Restoring from trash removes also trashed flag to its children which were trashed with it.
expect(result1.shareId.links.linkId7.encrypted.trashed).toBe(null);
expect(result1.shareId.links.linkId7.encrypted.trashedByParent).toBeFalsy();
expect(result1.shareId.links.linkId8.encrypted.trashed).toBe(123456789);
expect(result1.shareId.links.linkId8.encrypted.trashedByParent).toBeFalsy();
expect(result1.shareId.links.linkId9.encrypted.trashed).toBe(null);
expect(result1.shareId.links.linkId9.encrypted.trashedByParent).toBeFalsy();
});
it('updates trashed folder and adds files to it', () => {
const result1 = addOrUpdate(state, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'linkId7',
parentLinkId: 'linkId0',
trashed: 12345678,
} as EncryptedLink,
},
{
encrypted: {
linkId: 'linkId7a',
name: 'linkId7a',
parentLinkId: 'linkId7',
} as EncryptedLink,
},
]);
// Children of trashed parent is added to tree structure.
expect(result1.shareId.tree.linkId7).toMatchObject(['linkId8', 'linkId9', 'linkId7a']);
// Trashed parent trashes automatically also children.
expect(result1.shareId.links.linkId7.encrypted.trashed).toBe(12345678);
expect(result1.shareId.links.linkId7.encrypted.trashedByParent).toBeFalsy();
expect(result1.shareId.links.linkId7a.encrypted.trashed).toBe(12345678);
expect(result1.shareId.links.linkId7a.encrypted.trashedByParent).toBeTruthy();
// Restoring from trash re-adds link back to its parent.
const result2 = addOrUpdate(result1, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'linkId7',
parentLinkId: 'linkId0',
trashed: null,
} as EncryptedLink,
},
]);
// Trashed parent trashes automatically also children.
expect(result2.shareId.links.linkId7.encrypted.trashed).toBe(null);
expect(result2.shareId.links.linkId7.encrypted.trashedByParent).toBeFalsy();
expect(result2.shareId.links.linkId7a.encrypted.trashed).toBe(null);
expect(result2.shareId.links.linkId7a.encrypted.trashedByParent).toBeFalsy();
});
it('updates encrypted link with signature issue', () => {
// First, it sets signature issue.
const result1 = addOrUpdate(state, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'linkId7',
parentLinkId: 'linkId0',
signatureIssues: { name: 2 },
} as unknown as EncryptedLink,
},
]);
expect(result1.shareId.links.linkId7).toMatchObject({
decrypted: { linkId: 'linkId7', signatureIssues: { name: 2 } },
encrypted: { linkId: 'linkId7', signatureIssues: { name: 2 } },
});
// Second, it keeps it even if we do another update which doesnt change
// how the link is encrypted (keys and encrypted data are the same).
const result2 = addOrUpdate(result1, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'linkId7',
parentLinkId: 'linkId0',
} as unknown as EncryptedLink,
},
]);
expect(result2.shareId.links.linkId7).toMatchObject({
decrypted: { linkId: 'linkId7', signatureIssues: { name: 2 } },
encrypted: { linkId: 'linkId7', signatureIssues: { name: 2 } },
});
// Third, signature issue is cleared if keys or encrypted data is changed.
const result3 = addOrUpdate(result2, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'linkId7',
parentLinkId: 'linkId0',
nodeKey: 'anotherKey',
} as unknown as EncryptedLink,
},
]);
expect(result3.shareId.links.linkId7).toMatchObject({
decrypted: { linkId: 'linkId7', signatureIssues: undefined },
encrypted: { linkId: 'linkId7', signatureIssues: undefined },
});
});
it('updates decrypted link with signature issue', () => {
const result = addOrUpdate(state, 'shareId', [
{
encrypted: {
linkId: 'linkId7',
name: 'linkId7',
parentLinkId: 'linkId0',
} as unknown as EncryptedLink,
decrypted: {
linkId: 'linkId7',
name: 'linkId7',
parentLinkId: 'linkId0',
signatureIssues: { name: 2 },
} as unknown as DecryptedLink,
},
]);
expect(result.shareId.links.linkId7).toMatchObject({
decrypted: { linkId: 'linkId7', signatureIssues: { name: 2 } },
encrypted: { linkId: 'linkId7', signatureIssues: { name: 2 } },
});
});
it('locks and unlocks links', () => {
const result1 = setLock(state, 'shareId', ['linkId7', 'linkId8'], true);
expect(getLockedIds(result1)).toMatchObject(['linkId7', 'linkId8']);
const result2 = setLock(state, 'shareId', ['linkId8'], false);
expect(getLockedIds(result2)).toMatchObject(['linkId7']);
});
it('locks and unlocks trashed links', () => {
(state.shareId.links.linkId7.decrypted as DecryptedLink).trashed = 1234;
(state.shareId.links.linkId8.decrypted as DecryptedLink).trashed = 5678;
const result1 = setLock(state, 'shareId', 'trash', true);
expect(getLockedIds(result1)).toMatchObject(['linkId7', 'linkId8']);
const result2 = setLock(state, 'shareId', 'trash', false);
expect(getLockedIds(result2)).toMatchObject([]);
});
it('preserves lock for newly added trashed link', () => {
const result1 = setLock(state, 'shareId', 'trash', true);
const result2 = addOrUpdate(result1, 'shareId', [
{
encrypted: {
linkId: 'linkId100',
name: 'linkId100',
parentLinkId: 'linkId0',
trashed: 12345678,
} as EncryptedLink,
decrypted: {
linkId: 'linkId100',
name: 'linkId100',
parentLinkId: 'linkId0',
trashed: 12345678,
} as DecryptedLink,
},
{
encrypted: {
linkId: 'linkId101',
name: 'linkId101',
parentLinkId: 'linkId0',
trashed: 12345678900, // Way in future after setLock was called.
} as EncryptedLink,
decrypted: {
linkId: 'linkId101',
name: 'linkId101',
parentLinkId: 'linkId0',
trashed: 12345678900,
} as DecryptedLink,
},
]);
// linkId101 was deleted after our empty action, so is not locked.
expect(getLockedIds(result2)).toMatchObject(['linkId100']);
});
it('sets cached thumbnail', () => {
const result = setCachedThumbnailUrl(state, 'shareId', 'linkId7', 'cachedurl');
expect(result.shareId.links.linkId7.decrypted).toMatchObject({ cachedThumbnailUrl: 'cachedurl' });
});
it('preserves cached lock flag', () => {
const state2 = setLock(state, 'shareId', ['linkId7'], true);
const link = {
linkId: 'linkId7',
name: 'new name',
parentLinkId: 'linkId0',
};
const result = addOrUpdate(state2, 'shareId', [
{
encrypted: link as EncryptedLink,
decrypted: link as DecryptedLink,
},
]);
expect(result.shareId.links.linkId7.decrypted).toMatchObject({ isLocked: true });
});
it('preserves cached thumbnail', () => {
const state2 = setCachedThumbnailUrl(state, 'shareId', 'linkId7', 'cachedurl');
const link = {
linkId: 'linkId7',
name: 'new name',
parentLinkId: 'linkId0',
};
const result = addOrUpdate(state2, 'shareId', [
{
encrypted: link as EncryptedLink,
decrypted: link as DecryptedLink,
},
]);
expect(result.shareId.links.linkId7.decrypted).toMatchObject({ cachedThumbnailUrl: 'cachedurl' });
});
it('does not preserve cached thumbnail when revision changed', () => {
const state2 = setCachedThumbnailUrl(state, 'shareId', 'linkId7', 'cachedurl');
const link = {
linkId: 'linkId7',
name: 'new name',
parentLinkId: 'linkId0',
activeRevision: { id: 'newId' },
};
const result = addOrUpdate(state2, 'shareId', [
{
encrypted: link as EncryptedLink,
decrypted: link as DecryptedLink,
},
]);
expect(result.shareId.links.linkId7.decrypted).toMatchObject({ cachedThumbnailUrl: undefined });
});
it('preserves latest share url num accesses', () => {
expect(state.shareId.links.linkId7.decrypted?.shareUrl?.numAccesses).toBe(undefined);
// First set the numAccesses and check its set.
const linkWithAccesses = {
linkId: 'linkId7',
name: 'new name',
parentLinkId: 'linkId0',
shareUrl: {
id: 'shareUrlId',
numAccesses: 0, // Test with zero to make sure zero is also well handled.
},
};
const result1 = addOrUpdate(state, 'shareId', [
{
encrypted: linkWithAccesses as EncryptedLink,
decrypted: linkWithAccesses as DecryptedLink,
},
]);
expect(result1.shareId.links.linkId7.decrypted?.shareUrl?.numAccesses).toBe(0);
// Then set newer link without numAccesses which stil preserves the previous value.
const linkWithoutAccesses = {
linkId: 'linkId7',
name: 'newer name',
parentLinkId: 'linkId0',
shareUrl: {
id: 'shareUrlId',
},
};
const result2 = addOrUpdate(state, 'shareId', [
{
encrypted: linkWithoutAccesses as EncryptedLink,
decrypted: linkWithoutAccesses as DecryptedLink,
},
]);
expect(result2.shareId.links.linkId7.decrypted?.shareUrl?.numAccesses).toBe(0);
});
it('sets zero num accesses for fresh new share url', () => {
(state.shareId.links.linkId7.decrypted as DecryptedLink).shareUrl = undefined;
(state.shareId.links.linkId8.decrypted as DecryptedLink).shareUrl = {
id: 'shareUrlId',
} as LinkShareUrl;
const link7 = {
linkId: 'linkId7',
name: 'new name',
parentLinkId: 'linkId0',
shareUrl: {
id: 'shareUrlId1',
},
};
const link8 = {
linkId: 'linkId8',
name: 'new name',
parentLinkId: 'linkId7',
shareUrl: {
id: 'shareUrlId2',
},
};
const result = addOrUpdate(state, 'shareId', [
{
encrypted: link7 as EncryptedLink,
decrypted: link7 as DecryptedLink,
},
{
encrypted: link8 as EncryptedLink,
decrypted: link8 as DecryptedLink,
},
]);
// Link 7 had no shareUrl before, that means it is freshly created, so set to 0.
expect(result.shareId.links.linkId7.decrypted?.shareUrl?.numAccesses).toBe(0);
// Whereas link 8 had shareUrl before, so the update is about something else, and we need to keep undefined.
expect(result.shareId.links.linkId8.decrypted?.shareUrl?.numAccesses).toBe(undefined);
});
it('processes events', () => {
const result = updateByEvents(
state,
generateEvents([
[
EVENT_TYPES.CREATE,
{ linkId: 'newLink', name: 'newLink', parentLinkId: 'linkId0', rootShareId: 'shareId' },
],
[EVENT_TYPES.DELETE, { linkId: 'linkId1' }],
[EVENT_TYPES.DELETE, { linkId: 'linkId4' }],
[
EVENT_TYPES.UPDATE,
{ linkId: 'linkId7', name: 'new name', parentLinkId: 'linkId0', rootShareId: 'shareId' },
],
])
);
expect(Object.keys(result.shareId.links)).toMatchObject([
'linkId0',
'linkId7',
'linkId8',
'linkId9',
'newLink',
]);
expect(Object.keys(result.shareId.tree)).toMatchObject(['linkId0', 'linkId7']);
expect(result.shareId.links.linkId7).toMatchObject({
decrypted: { linkId: 'linkId7', name: 'linkId7', isStale: true },
encrypted: { linkId: 'linkId7' },
});
});
it('skips events from non-present share', () => {
const result = updateByEvents(
state,
generateEvents([
[
EVENT_TYPES.CREATE,
{ linkId: 'newLink', name: 'newLink', parentLinkId: 'linkId0', rootShareId: 'shareId2' },
],
])
);
expect(Object.keys(result)).toMatchObject(['shareId']);
});
describe('hook', () => {
let hook: {
current: ReturnType<typeof useLinksStateProvider>;
};
beforeEach(() => {
const { result } = renderHook(() => useLinksStateProvider());
hook = result;
act(() => {
state.shareId.links.linkId6.encrypted.shareUrl = {
id: 'shareUrlId',
token: 'token',
isExpired: false,
createTime: 12345,
expireTime: null,
};
state.shareId.links.linkId7.encrypted.trashed = 12345;
state.shareId.links.linkId8.encrypted.trashed = 12345;
state.shareId.links.linkId8.encrypted.trashedByParent = true;
state.shareId.links.linkId9.encrypted.trashed = 12345;
state.shareId.links.linkId9.encrypted.trashedByParent = true;
hook.current.setLinks('shareId', Object.values(state.shareId.links));
});
});
it('returns children of the parent', () => {
const links = hook.current.getChildren('shareId', 'linkId1');
expect(links.map((link) => link.encrypted.linkId)).toMatchObject(['linkId2', 'linkId3']);
});
it('returns trashed links', () => {
const links = hook.current.getTrashed('shareId');
expect(links.map((link) => link.encrypted.linkId)).toMatchObject(['linkId7']);
});
it('returns shared links', () => {
const links = hook.current.getSharedByLink('shareId');
expect(links.map((link) => link.encrypted.linkId)).toMatchObject(['linkId6']);
});
});
});
|
3,093 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links/useLinksListing/useLinksListing.test.tsx | import { act, renderHook } from '@testing-library/react-hooks';
import { SORT_DIRECTION } from '@proton/shared/lib/constants';
import { VolumesStateProvider } from '../../_volumes/useVolumesState';
import { EncryptedLink } from '../interface';
import { LinksStateProvider } from '../useLinksState';
import { useLinksListingProvider } from './useLinksListing';
import { PAGE_SIZE } from './useLinksListingHelpers';
const LINKS = [...Array(PAGE_SIZE * 2 - 1)].map((_, x) => ({ linkId: `children${x}`, parentLinkId: 'parentLinkId' }));
function linksToApiLinks(links: { linkId: string; parentLinkId: string }[]) {
return links.map(({ linkId, parentLinkId }) => ({ LinkID: linkId, ParentLinkID: parentLinkId }));
}
jest.mock('../../_utils/errorHandler', () => {
return {
useErrorHandler: () => ({
showErrorNotification: jest.fn(),
showAggregatedErrorNotification: jest.fn(),
}),
};
});
const mockRequest = jest.fn();
jest.mock('../../_api/useDebouncedRequest', () => {
const useDebouncedRequest = () => {
return mockRequest;
};
return useDebouncedRequest;
});
jest.mock('../../_events/useDriveEventManager', () => {
const useDriveEventManager = () => {
return {
eventHandlers: {
register: () => 'id',
unregister: () => false,
},
};
};
return {
useDriveEventManager,
};
});
jest.mock('../../_shares/useShare', () => {
const useLink = () => {
return {};
};
return useLink;
});
const mockDecrypt = jest.fn();
jest.mock('../useLink', () => {
const useLink = () => {
return {
decryptLink: mockDecrypt,
};
};
return useLink;
});
describe('useLinksListing', () => {
const abortSignal = new AbortController().signal;
let hook: {
current: ReturnType<typeof useLinksListingProvider>;
};
beforeEach(() => {
jest.resetAllMocks();
mockDecrypt.mockImplementation((_abortSignal: AbortSignal, _shareId: string, encrypted: EncryptedLink) =>
Promise.resolve(encrypted)
);
const wrapper = ({ children }: { children: React.ReactNode }) => (
<VolumesStateProvider>
<LinksStateProvider>{children}</LinksStateProvider>
</VolumesStateProvider>
);
const { result } = renderHook(() => useLinksListingProvider(), { wrapper });
hook = result;
});
it('fetches children all pages with the same sorting', async () => {
mockRequest.mockReturnValueOnce({ Links: linksToApiLinks(LINKS.slice(0, PAGE_SIZE)) });
mockRequest.mockReturnValueOnce({ Links: linksToApiLinks(LINKS.slice(PAGE_SIZE)) });
await act(async () => {
await hook.current.fetchChildrenNextPage(abortSignal, 'shareId', 'parentLinkId', {
sortField: 'createTime',
sortOrder: SORT_DIRECTION.ASC,
});
await hook.current.fetchChildrenNextPage(abortSignal, 'shareId', 'parentLinkId', {
sortField: 'createTime',
sortOrder: SORT_DIRECTION.ASC,
});
});
// Check fetch calls - two pages.
expect(mockRequest.mock.calls.map(([{ params }]) => params)).toMatchObject([
{ Page: 0, Sort: 'CreateTime', Desc: 0 },
{ Page: 1, Sort: 'CreateTime', Desc: 0 },
]);
expect(hook.current.getCachedChildren(abortSignal, 'shareId', 'parentLinkId')).toMatchObject({
links: LINKS,
isDecrypting: false,
});
// Check decrypt calls - all links were decrypted.
expect(mockDecrypt.mock.calls.map(([, , { linkId }]) => linkId)).toMatchObject(
LINKS.map(({ linkId }) => linkId)
);
});
it('fetches from the beginning when sorting changes', async () => {
const links = LINKS.slice(0, PAGE_SIZE);
mockRequest.mockReturnValue({ Links: linksToApiLinks(links) });
await act(async () => {
await hook.current.fetchChildrenNextPage(abortSignal, 'shareId', 'parentLinkId', {
sortField: 'createTime',
sortOrder: SORT_DIRECTION.ASC,
});
await hook.current.fetchChildrenNextPage(abortSignal, 'shareId', 'parentLinkId', {
sortField: 'createTime',
sortOrder: SORT_DIRECTION.DESC,
});
});
// Check fetch calls - twice starting from the first page.
expect(mockRequest.mock.calls.map(([{ params }]) => params)).toMatchObject([
{ Page: 0, Sort: 'CreateTime', Desc: 0 },
{ Page: 0, Sort: 'CreateTime', Desc: 1 },
]);
expect(hook.current.getCachedChildren(abortSignal, 'shareId', 'parentLinkId')).toMatchObject({
links,
isDecrypting: false,
});
// Check decrypt calls - the second call returned the same links, no need to decrypt them twice.
expect(mockDecrypt.mock.calls.map(([, , { linkId }]) => linkId)).toMatchObject(
links.map(({ linkId }) => linkId)
);
});
it('skips fetch if all was fetched', async () => {
const links = LINKS.slice(0, 5);
mockRequest.mockReturnValue({ Links: linksToApiLinks(links) });
await act(async () => {
await hook.current.fetchChildrenNextPage(abortSignal, 'shareId', 'parentLinkId');
await hook.current.fetchChildrenNextPage(abortSignal, 'shareId', 'parentLinkId');
});
// Check fetch calls - first call fetched all, no need to call the second.
expect(mockRequest).toBeCalledTimes(1);
expect(hook.current.getCachedChildren(abortSignal, 'shareId', 'parentLinkId')).toMatchObject({
links,
isDecrypting: false,
});
});
it('loads the whole folder', async () => {
mockRequest.mockReturnValueOnce({ Links: linksToApiLinks(LINKS.slice(0, PAGE_SIZE)) });
mockRequest.mockReturnValueOnce({ Links: linksToApiLinks(LINKS.slice(PAGE_SIZE)) });
await act(async () => {
await hook.current.loadChildren(abortSignal, 'shareId', 'parentLinkId');
});
expect(mockRequest.mock.calls.map(([{ params }]) => params)).toMatchObject([
{ Page: 0, Sort: 'CreateTime', Desc: 0 },
{ Page: 1, Sort: 'CreateTime', Desc: 0 },
]);
});
it('continues the load of the whole folder where it ended', async () => {
mockRequest.mockReturnValueOnce({ Links: linksToApiLinks(LINKS.slice(0, PAGE_SIZE)) });
mockRequest.mockReturnValueOnce({ Links: linksToApiLinks(LINKS.slice(PAGE_SIZE)) });
await act(async () => {
await hook.current.fetchChildrenNextPage(abortSignal, 'shareId', 'parentLinkId', {
sortField: 'metaDataModifyTime', // Make sure it is not default.
sortOrder: SORT_DIRECTION.ASC,
});
await hook.current.loadChildren(abortSignal, 'shareId', 'parentLinkId');
});
expect(mockRequest.mock.calls.map(([{ params }]) => params)).toMatchObject([
{ Page: 0, Sort: 'ModifyTime', Desc: 0 }, // Done by fetchChildrenNextPage.
{ Page: 1, Sort: 'ModifyTime', Desc: 0 }, // Done by loadChildren, continues with the same sorting.
]);
});
it("can count link's children", async () => {
const PAGE_LENGTH = 5;
const links = LINKS.slice(0, PAGE_LENGTH);
mockRequest.mockReturnValueOnce({ Links: linksToApiLinks(links) });
await act(async () => {
await hook.current.fetchChildrenNextPage(abortSignal, 'shareId', 'parentLinkId');
});
expect(mockRequest).toBeCalledTimes(1);
expect(hook.current.getCachedChildrenCount('shareId', 'parentLinkId')).toBe(PAGE_LENGTH);
});
});
|
3,095 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links/useLinksListing/useLinksListingGetter.test.tsx | import { act, renderHook } from '@testing-library/react-hooks';
import { wait } from '@proton/shared/lib/helpers/promise';
import { VolumesStateProvider } from '../../_volumes/useVolumesState';
import { EncryptedLink } from '../interface';
import { useLinksListingProvider } from './useLinksListing';
jest.mock('../../_utils/errorHandler', () => {
return {
useErrorHandler: () => ({
showErrorNotification: jest.fn(),
showAggregatedErrorNotification: jest.fn(),
}),
};
});
const mockRequest = jest.fn();
jest.mock('../../_api/useDebouncedRequest', () => {
const useDebouncedRequest = () => {
return mockRequest;
};
return useDebouncedRequest;
});
jest.mock('../../_events/useDriveEventManager', () => {
const useDriveEventManager = () => {
return {
eventHandlers: {
register: () => 'id',
unregister: () => false,
},
};
};
return {
useDriveEventManager,
};
});
jest.mock('../../_shares/useShare', () => {
const useLink = () => {
return {};
};
return useLink;
});
const mockDecrypt = jest.fn();
jest.mock('../useLink', () => {
const useLink = () => {
return {
decryptLink: mockDecrypt,
};
};
return useLink;
});
const mockGetChildren = jest.fn();
jest.mock('../useLinksState', () => {
const useLinksState = () => {
return {
setLinks: jest.fn(),
getChildren: mockGetChildren,
};
};
return useLinksState;
});
describe('useLinksListing', () => {
const abortSignal = new AbortController().signal;
let hook: {
current: ReturnType<typeof useLinksListingProvider>;
};
beforeEach(() => {
jest.resetAllMocks();
mockDecrypt.mockImplementation((abortSignal: AbortSignal, shareId: string, encrypted: EncryptedLink) =>
Promise.resolve(encrypted)
);
mockGetChildren.mockReturnValue([
{ encrypted: { linkId: 'onlyEncrypted' } },
{ encrypted: { linkId: 'decrypted' }, decrypted: { isStale: false } },
{ encrypted: { linkId: 'stale' }, decrypted: { isStale: true } },
]);
const wrapper = ({ children }: { children: React.ReactNode }) => (
<VolumesStateProvider>{children}</VolumesStateProvider>
);
const { result } = renderHook(() => useLinksListingProvider(), { wrapper });
hook = result;
});
it('decrypts all non-decrypted links if listing is not fetching', async () => {
act(() => {
hook.current.getCachedChildren(abortSignal, 'shareId', 'parentLinkId');
});
expect(mockDecrypt.mock.calls.map(([, , { linkId }]) => linkId)).toMatchObject(['onlyEncrypted', 'stale']);
});
it('re-decrypts only stale links if listing is fetching (and decrypting)', async () => {
// Make some delay to make sure fetching is in progress when
// getCachedChildren is called.
mockRequest.mockImplementation(async () => {
await wait(200);
return { Links: [] };
});
await act(async () => {
const fetchPromise = hook.current.fetchChildrenNextPage(abortSignal, 'shareId', 'parentLinkId');
await wait(100); // Wait till previous call sets inProgress.
hook.current.getCachedChildren(abortSignal, 'shareId', 'parentLinkId');
await fetchPromise;
});
expect(mockDecrypt.mock.calls.map(([, , { linkId }]) => linkId)).toMatchObject(['stale']);
});
});
|
3,098 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links/useLinksListing/useSharedLinksListing.test.tsx | import { act, renderHook } from '@testing-library/react-hooks';
import { VolumesStateProvider } from '../../_volumes/useVolumesState';
import { LinksStateProvider } from '../useLinksState';
import { PAGE_SIZE } from './useLinksListingHelpers';
import { useSharedLinksListing } from './useSharedLinksListing';
jest.mock('@proton/shared/lib/api/drive/volume', () => ({
queryVolumeSharedLinks: jest.fn(),
}));
const mockRequest = jest.fn();
jest.mock('../../_api/useDebouncedRequest', () => {
const useDebouncedRequest = () => {
return mockRequest;
};
return useDebouncedRequest;
});
jest.mock('../../_utils/errorHandler', () => {
return {
useErrorHandler: () => ({
showErrorNotification: jest.fn(),
showAggregatedErrorNotification: jest.fn(),
}),
};
});
jest.mock('../useLink', () => {
const useLink = () => {
return {
decryptLink: jest.fn(),
};
};
return useLink;
});
const queryVolumeSharedLinksMock = require('@proton/shared/lib/api/drive/volume').queryVolumeSharedLinks as jest.Mock;
const generateArrayOfRandomStrings = (size: number): string[] => {
return Array.from({ length: size }, () => Math.random().toString(36).substring(2));
};
describe('useSharedLinksListing', () => {
let hook: {
current: ReturnType<typeof useSharedLinksListing>;
};
beforeEach(() => {
jest.resetAllMocks();
const wrapper = ({ children }: { children: React.ReactNode }) => (
<VolumesStateProvider>
<LinksStateProvider>{children}</LinksStateProvider>
</VolumesStateProvider>
);
const { result } = renderHook(() => useSharedLinksListing(), { wrapper });
hook = result;
jest.resetAllMocks();
});
it('should fetch the first page of shared links for a given volume', async () => {
const volumeId = '1';
const page = 0;
const response = {
ShareURLContexts: [
{
ContextShareID: '1',
LinkIDs: generateArrayOfRandomStrings(10),
ShareURLs: generateArrayOfRandomStrings(10),
},
],
};
mockRequest.mockResolvedValue(response);
await act(async () => {
await hook.current.loadSharedLinks(new AbortController().signal, volumeId, () =>
Promise.resolve({ links: [], parents: [], errors: [] })
);
});
expect(queryVolumeSharedLinksMock).toHaveBeenCalledWith(volumeId, { Page: page, PageSize: PAGE_SIZE });
});
it('should increment the page count when fetching the next page of shared links', async () => {
const volumeId = '1';
const page = 0;
let firstResponse = {
ShareURLContexts: [
{
ContextShareID: '1',
LinkIDs: generateArrayOfRandomStrings(PAGE_SIZE),
ShareURLs: generateArrayOfRandomStrings(PAGE_SIZE),
},
],
};
let secondResponse = {
ShareURLContexts: [
{
ContextShareID: '1',
LinkIDs: generateArrayOfRandomStrings(1),
ShareURLs: generateArrayOfRandomStrings(1),
},
],
};
mockRequest.mockResolvedValueOnce(firstResponse).mockResolvedValueOnce(secondResponse);
const { loadSharedLinks } = hook.current;
await act(async () => {
await loadSharedLinks(new AbortController().signal, volumeId, () =>
Promise.resolve({ links: [], parents: [], errors: [] })
);
});
expect(queryVolumeSharedLinksMock).toHaveBeenCalledWith(volumeId, { Page: page + 1, PageSize: PAGE_SIZE });
// verify that the script terminates successfully
expect(queryVolumeSharedLinksMock).toBeCalledTimes(2);
});
});
|
3,100 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_links/useLinksListing/useTrashedLinksListing.test.tsx | import { act, renderHook } from '@testing-library/react-hooks';
import { VolumesStateProvider } from '../../_volumes/useVolumesState';
import { LinksStateProvider } from '../useLinksState';
import { PAGE_SIZE } from './useLinksListingHelpers';
import { useTrashedLinksListing } from './useTrashedLinksListing';
jest.mock('@proton/shared/lib/api/drive/volume', () => ({
queryVolumeTrash: jest.fn(),
}));
const mockRequest = jest.fn();
jest.mock('../../_api/useDebouncedRequest', () => {
const useDebouncedRequest = () => {
return mockRequest;
};
return useDebouncedRequest;
});
jest.mock('../../_utils/errorHandler', () => {
return {
useErrorHandler: () => ({
showErrorNotification: jest.fn(),
showAggregatedErrorNotification: jest.fn(),
}),
};
});
jest.mock('../useLink', () => {
const useLink = () => {
return {
decryptLink: jest.fn(),
};
};
return useLink;
});
const queryVolumeTrashMock = require('@proton/shared/lib/api/drive/volume').queryVolumeTrash as jest.Mock;
const generateArrayOfRandomStrings = (size: number): string[] => {
return Array.from({ length: size }, () => Math.random().toString(36).substring(2));
};
describe('useTrashedLinksListing', () => {
let hook: {
current: ReturnType<typeof useTrashedLinksListing>;
};
beforeEach(() => {
jest.resetAllMocks();
const wrapper = ({ children }: { children: React.ReactNode }) => (
<VolumesStateProvider>
<LinksStateProvider>{children}</LinksStateProvider>
</VolumesStateProvider>
);
const { result } = renderHook(() => useTrashedLinksListing(), { wrapper });
hook = result;
jest.resetAllMocks();
});
it('should fetch the first page of trashed links for a given volume', async () => {
const volumeId = '1';
const page = 0;
const response = {
Trash: [{ ShareID: '1', LinkIDs: generateArrayOfRandomStrings(10) }],
};
mockRequest.mockResolvedValue(response);
await act(async () => {
await hook.current.loadTrashedLinks(new AbortController().signal, volumeId, () =>
Promise.resolve({ links: [], parents: [], errors: [] })
);
});
expect(queryVolumeTrashMock).toHaveBeenCalledWith(volumeId, { Page: page, PageSize: PAGE_SIZE });
});
it('should increment the page count when fetching the next page of trashed links', async () => {
const volumeId = '1';
const page = 0;
let firstResponse = {
Trash: [{ ShareID: '1', LinkIDs: generateArrayOfRandomStrings(PAGE_SIZE) }],
};
let secondResponse = {
Trash: [{ ShareID: '1', LinkIDs: generateArrayOfRandomStrings(1) }],
};
mockRequest.mockResolvedValueOnce(firstResponse).mockResolvedValueOnce(secondResponse);
const { loadTrashedLinks } = hook.current;
await act(async () => {
await loadTrashedLinks(new AbortController().signal, volumeId, () =>
Promise.resolve({ links: [], parents: [], errors: [] })
);
});
expect(queryVolumeTrashMock).toHaveBeenCalledWith(volumeId, { Page: page + 1, PageSize: PAGE_SIZE });
// verify that the script terminates successfully
expect(queryVolumeTrashMock).toBeCalledTimes(2);
});
});
|
3,107 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_photos/usePhotosRecovery.test.ts | import { act, renderHook } from '@testing-library/react-hooks';
import { SupportedMimeTypes } from '@proton/shared/lib/drive/constants';
import { getItem, removeItem, setItem } from '@proton/shared/lib/helpers/storage';
import { DecryptedLink, useLinksActions, useLinksListing } from '../_links';
import useSharesState from '../_shares/useSharesState';
import { usePhotos } from './PhotosProvider';
import { RECOVERY_STATE, usePhotosRecovery } from './usePhotosRecovery';
function generateDecryptedLink(linkId = 'linkId'): DecryptedLink {
return {
encryptedName: 'name',
name: 'name',
linkId,
createTime: 323212,
digests: { sha1: '' },
fileModifyTime: 323212,
parentLinkId: 'parentLinkId',
isFile: true,
mimeType: SupportedMimeTypes.jpg,
hash: 'hash',
size: 233,
metaDataModifyTime: 323212,
trashed: 0,
hasThumbnail: false,
isShared: false,
rootShareId: 'rootShareId',
};
}
jest.mock('../_links', () => {
const useLinksActions = jest.fn();
const useLinksListing = jest.fn();
return { useLinksActions, useLinksListing };
});
jest.mock('../_shares/useSharesState');
jest.mock('./PhotosProvider', () => {
return {
usePhotos: jest.fn(),
};
});
jest.mock('../_utils', () => ({
waitFor: jest.fn().mockImplementation(async (callback) => {
callback();
}),
}));
jest.mock('@proton/shared/lib/helpers/storage', () => ({
getItem: jest.fn(),
removeItem: jest.fn(),
setItem: jest.fn(),
}));
jest.mock('../../utils/errorHandling');
const mockedRemoveItem = jest.mocked(removeItem);
const mockedGetItem = jest.mocked(getItem);
const mockedSetItem = jest.mocked(setItem);
const getAllResultState = (
all: (
| Error
| {
needsRecovery: boolean;
countOfUnrecoveredLinksLeft: number;
countOfFailedLinks: number;
start: () => void;
state: RECOVERY_STATE;
}
)[]
) => {
const allResultState: {
state: RECOVERY_STATE;
}[] = all.map((allResult: any) => allResult.state);
return allResultState;
};
describe('usePhotosRecovery', () => {
const links = [generateDecryptedLink('linkId1'), generateDecryptedLink('linkId2')];
const mockedUsePhotos = jest.mocked(usePhotos);
const mockedUseLinksListing = jest.mocked(useLinksListing);
const mockedUseLinksActions = jest.mocked(useLinksActions);
const mockedUseShareState = jest.mocked(useSharesState);
const mockedGetCachedChildren = jest.fn();
const mockedLoadChildren = jest.fn();
const mockedMoveLinks = jest.fn();
const mockedDeletePhotosShare = jest.fn();
// @ts-ignore
mockedUseLinksListing.mockReturnValue({
loadChildren: mockedLoadChildren,
getCachedChildren: mockedGetCachedChildren,
});
// @ts-ignore
mockedUsePhotos.mockReturnValue({
shareId: 'shareId',
linkId: 'linkId',
deletePhotosShare: mockedDeletePhotosShare,
});
// @ts-ignore
mockedUseLinksActions.mockReturnValue({
moveLinks: mockedMoveLinks,
});
// @ts-ignore
mockedUseShareState.mockReturnValue({
getRestoredPhotosShares: () => [
{
shareId: 'shareId',
rootLinkId: 'rootLinkId',
volumeId: 'volumeId',
creator: 'creator',
isLocked: false,
isDefault: false,
isVolumeSoftDeleted: false,
possibleKeyPackets: ['dsad'],
type: 4,
state: 1,
},
],
});
beforeAll(() => {});
beforeEach(() => {
jest.clearAllMocks();
mockedDeletePhotosShare.mockResolvedValue(undefined);
mockedLoadChildren.mockResolvedValue(undefined);
mockedMoveLinks.mockImplementation(
async (abortSignal: AbortSignal, { linkIds, onMoved }: { linkIds: string[]; onMoved?: () => void }) => {
// Reproduce the async behavior of moveLinks
linkIds.forEach(() => setTimeout(() => onMoved?.(), 10));
}
);
});
it('should pass all state if files need to be recovered', async () => {
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Decrypting step
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Preparing step
mockedGetCachedChildren.mockReturnValueOnce({ links: [], isDecrypting: false }); // Deleting step
const { result, waitFor } = renderHook(() => usePhotosRecovery());
act(() => {
result.current.start();
});
await waitFor(() => expect(result.current.countOfUnrecoveredLinksLeft).toEqual(2));
await waitFor(() => expect(result.current.countOfUnrecoveredLinksLeft).toEqual(0));
expect(result.current.state).toEqual('SUCCEED');
expect(mockedGetCachedChildren).toHaveBeenCalledTimes(3);
expect(mockedMoveLinks).toHaveBeenCalledTimes(1);
expect(mockedLoadChildren).toHaveBeenCalledTimes(1);
expect(mockedDeletePhotosShare).toHaveBeenCalledTimes(1);
expect(result.current.countOfUnrecoveredLinksLeft).toEqual(0);
expect(getAllResultState(result.all)).toStrictEqual([
'READY',
'READY',
'STARTED',
'DECRYPTING',
'DECRYPTED',
'PREPARING',
'PREPARING',
'PREPARING', // 3 times Preparing because of React states changes
'PREPARED',
'MOVING',
'MOVED',
'MOVED',
'MOVED',
'CLEANING',
'SUCCEED',
]);
expect(mockedRemoveItem).toHaveBeenCalledTimes(1);
expect(mockedRemoveItem).toHaveBeenCalledWith('photos-recovery-state');
});
it('should pass and set errors count if some moves failed', async () => {
mockedGetCachedChildren.mockClear();
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Decrypting step
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Preparing step
mockedGetCachedChildren.mockReturnValueOnce({ links: [links[0]], isDecrypting: false }); // Deleting step
mockedMoveLinks.mockImplementation(
async (
abortSignal: AbortSignal,
{ linkIds, onMoved, onError }: { linkIds: string[]; onMoved?: () => void; onError?: () => void }
) => {
linkIds.forEach((linkId) => {
if (linkId === 'linkId2') {
onError?.();
} else {
onMoved?.();
}
});
}
);
const { result, waitFor } = renderHook(() => usePhotosRecovery());
act(() => {
result.current.start();
});
await waitFor(() => expect(result.current.countOfUnrecoveredLinksLeft).toEqual(2));
expect(result.current.countOfFailedLinks).toEqual(1);
expect(result.current.countOfUnrecoveredLinksLeft).toEqual(0);
expect(result.current.state).toEqual('FAILED');
expect(mockedDeletePhotosShare).toHaveBeenCalledTimes(0);
expect(getAllResultState(result.all)).toStrictEqual([
'READY',
'READY',
'STARTED',
'DECRYPTING',
'DECRYPTED',
'PREPARING',
'PREPARING',
'PREPARING', // 3 times Preparing because of React states changes
'PREPARED',
'MOVING',
'MOVED',
'CLEANING',
'FAILED',
]);
expect(mockedGetItem).toHaveBeenCalledTimes(1);
expect(mockedSetItem).toHaveBeenCalledTimes(2);
expect(mockedSetItem).toHaveBeenCalledWith('photos-recovery-state', 'progress');
expect(mockedSetItem).toHaveBeenCalledWith('photos-recovery-state', 'failed');
});
it('should failed if deleteShare failed', async () => {
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Decrypting step
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Preparing step
mockedGetCachedChildren.mockReturnValueOnce({ links: [], isDecrypting: false }); // Deleting step
mockedDeletePhotosShare.mockRejectedValue(undefined);
const { result, waitFor } = renderHook(() => usePhotosRecovery());
act(() => {
result.current.start();
});
await waitFor(() => expect(result.current.state).toEqual('FAILED'));
expect(mockedDeletePhotosShare).toHaveBeenCalledTimes(1);
expect(getAllResultState(result.all)).toStrictEqual([
'READY',
'READY',
'STARTED',
'DECRYPTING',
'DECRYPTED',
'PREPARING',
'PREPARING',
'PREPARING', // 3 times Preparing because of React states changes
'PREPARED',
'MOVING',
'MOVED',
'MOVED',
'MOVED',
'CLEANING',
'FAILED',
]);
expect(mockedGetItem).toHaveBeenCalledTimes(1);
expect(mockedSetItem).toHaveBeenCalledTimes(2);
expect(mockedSetItem).toHaveBeenCalledWith('photos-recovery-state', 'progress');
expect(mockedSetItem).toHaveBeenCalledWith('photos-recovery-state', 'failed');
});
it('should failed if loadChildren failed', async () => {
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Decrypting step
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Preparing step
mockedGetCachedChildren.mockReturnValueOnce({ links: [], isDecrypting: false }); // Deleting step
mockedLoadChildren.mockRejectedValue(undefined);
const { result, waitFor } = renderHook(() => usePhotosRecovery());
act(() => {
result.current.start();
});
await waitFor(() => expect(result.current.state).toEqual('FAILED'));
expect(mockedDeletePhotosShare).toHaveBeenCalledTimes(0);
expect(mockedGetCachedChildren).toHaveBeenCalledTimes(0);
expect(getAllResultState(result.all)).toStrictEqual(['READY', 'READY', 'STARTED', 'DECRYPTING', 'FAILED']);
expect(mockedGetItem).toHaveBeenCalledTimes(1);
expect(mockedSetItem).toHaveBeenCalledTimes(2);
expect(mockedSetItem).toHaveBeenCalledWith('photos-recovery-state', 'progress');
expect(mockedSetItem).toHaveBeenCalledWith('photos-recovery-state', 'failed');
});
it('should failed if moveLinks helper failed', async () => {
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Decrypting step
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Preparing step
mockedGetCachedChildren.mockReturnValueOnce({ links: [], isDecrypting: false }); // Deleting step
mockedMoveLinks.mockRejectedValue(undefined);
const { result, waitFor } = renderHook(() => usePhotosRecovery());
act(() => {
result.current.start();
});
await waitFor(() => expect(result.current.state).toEqual('FAILED'));
expect(mockedDeletePhotosShare).toHaveBeenCalledTimes(0);
expect(mockedMoveLinks).toHaveBeenCalledTimes(1);
expect(mockedGetCachedChildren).toHaveBeenCalledTimes(2);
expect(getAllResultState(result.all)).toStrictEqual([
'READY',
'READY',
'STARTED',
'DECRYPTING',
'DECRYPTED',
'PREPARING',
'PREPARING',
'PREPARING', // 3 times Preparing because of React states changes
'PREPARED',
'MOVING',
'FAILED',
]);
expect(mockedGetItem).toHaveBeenCalledTimes(1);
expect(mockedSetItem).toHaveBeenCalledTimes(2);
expect(mockedSetItem).toHaveBeenCalledWith('photos-recovery-state', 'progress');
expect(mockedSetItem).toHaveBeenCalledWith('photos-recovery-state', 'failed');
});
it('should start the process if localStorage value was set to progress', async () => {
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Decrypting step
mockedGetCachedChildren.mockReturnValueOnce({ links, isDecrypting: false }); // Preparing step
mockedGetCachedChildren.mockReturnValueOnce({ links: [], isDecrypting: false }); // Deleting step
mockedGetItem.mockReturnValueOnce('progress');
const { result, waitFor } = renderHook(() => usePhotosRecovery());
await waitFor(() => expect(result.current.state).toEqual('SUCCEED'));
expect(getAllResultState(result.all)).toStrictEqual([
'READY',
'STARTED',
'DECRYPTING',
'DECRYPTED',
'PREPARING',
'PREPARING',
'PREPARING',
'PREPARED',
'MOVING',
'MOVED',
'MOVED',
'MOVED',
'CLEANING',
'SUCCEED',
]);
expect(mockedGetItem).toHaveBeenCalledTimes(1);
});
it('should set state to failed if localStorage value was set to failed', async () => {
mockedGetItem.mockReturnValueOnce('failed');
const { result, waitFor } = renderHook(() => usePhotosRecovery());
await waitFor(() => expect(result.current.state).toEqual('FAILED'));
expect(getAllResultState(result.all)).toStrictEqual(['READY', 'FAILED']);
});
});
|
3,109 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_photos | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_photos/utils/convertSubjectAreaToSubjectCoordinates.test.ts | import { convertSubjectAreaToSubjectCoordinates } from './convertSubjectAreaToSubjectCoordinates';
describe('convertSubjectAreaToSubjectCoordinates()', () => {
it("should correctly convert exif's SubjectArea with X,Y to SubjectCoordinates", () => {
const subjectArea = [232, 643];
expect(convertSubjectAreaToSubjectCoordinates(subjectArea)).toEqual({
top: 643,
left: 232,
bottom: 643,
right: 232,
});
});
it("should correctly convert exif's SubjectArea with X,Y,Diameter to SubjectCoordinates", () => {
const subjectArea = [232, 643, 142];
expect(convertSubjectAreaToSubjectCoordinates(subjectArea)).toEqual({
top: 572,
left: 161,
bottom: 714,
right: 303,
});
});
it("should correctly convert exif's SubjectArea X,Y,Width,Height to SubjectCoordinates", () => {
const subjectArea = [232, 643, 142, 432];
expect(convertSubjectAreaToSubjectCoordinates(subjectArea)).toEqual({
top: 427,
left: 161,
bottom: 859,
right: 303,
});
});
});
|
3,112 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_photos | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_photos/utils/formatExifDateTime.test.ts | import { formatExifDateTime } from './formatExifDateTime';
describe('formatExifDateTime()', () => {
it("should correctly format exif's DateTime to standard Date format", () => {
const exifDateTime = '2023:07:21 22:12:01';
expect(formatExifDateTime(exifDateTime)).toEqual('2023-07-21 22:12:01');
});
it("should throw an error if exif's DateTime format is incorrect", () => {
const exifDateTime = '2023-07:21-22:12:01';
expect(() => formatExifDateTime(exifDateTime)).toThrowError(
`The DateTime passed is not in the right format (received: ${exifDateTime}, expected: YYYY:MM:DD HH:MM:SS)`
);
});
});
|
3,116 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_photos | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_photos/utils/sortWithCategories.test.ts | import { fromUnixTime, getUnixTime } from 'date-fns';
import { PhotoLink } from '../interface';
import { sortWithCategories } from './sortWithCategories';
jest.mock('@proton/shared/lib/i18n', () => ({
dateLocale: {
code: 'en-US',
formatLong: {
time: jest.fn(),
},
},
}));
describe('sortWithCategories()', () => {
beforeAll(() => {
const unixDate = 1694096758; // Thu Sep 07 14:25:58 2023 UTC
jest.useFakeTimers().setSystemTime(fromUnixTime(unixDate));
});
afterAll(() => {
jest.useRealTimers();
});
it('should return sorted list with categories of photos', () => {
const photos: PhotoLink[] = [
{
linkId: '9d6c33a79feba8dd2fd768f58f450a7f2ff3ec2e',
name: 'This month',
activeRevision: {
photo: {
linkId: '9d6c33a79feba8dd2fd768f58f450a7f2ff3ec2e',
captureTime: getUnixTime(new Date()), // Today
},
},
},
{
linkId: '1a44a587ffbb4d38a04f68af1ddf6b30a74ff3b7',
name: '8 March 2022',
activeRevision: {
photo: {
linkId: '1a44a587ffbb4d38a04f68af1ddf6b30a74ff3b7',
captureTime: 1646743628, // 08/03/2022
},
},
},
{
linkId: '6d2a5651f974cc67d99cbdabd00560967a7bad10',
name: '7 July 2023',
activeRevision: {
photo: {
linkId: '6d2a5651f974cc67d99cbdabd00560967a7bad10',
captureTime: 1688731320, // 07/07/2023
},
},
},
{
linkId: '8ac290ecd3dcfe51ac2e81ba1dbbcc8b6a20b199',
name: '7 May 2022',
activeRevision: {
photo: {
linkId: '8ac290ecd3dcfe51ac2e81ba1dbbcc8b6a20b199',
captureTime: 1651924920, // 07/05/2022
},
},
},
];
const flattenPhotos = sortWithCategories([...photos]); // Destructure to keep origin reference
expect(flattenPhotos).toEqual([
'This month',
photos[0],
'July',
photos[2],
'May 2022',
photos[3],
'March 2022',
photos[1],
]);
});
});
|
3,120 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_revisions/useRevisions.test.ts | import { renderHook } from '@testing-library/react-hooks';
import { VERIFICATION_STATUS } from '@proton/crypto';
import { getIsConnectionIssue } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { sendErrorReport } from '../../utils/errorHandling';
import { useDriveCrypto } from '../_crypto';
import { useDownload } from '../_downloads';
import { useLink } from '../_links';
import { ParsedExtendedAttributes, decryptExtendedAttributes } from '../_links/extendedAttributes';
import useRevisions from './useRevisions';
jest.mock('../_crypto');
jest.mock('../_downloads', () => ({
useDownload: jest.fn(),
}));
jest.mock('../_links', () => ({
useLink: jest.fn(),
}));
jest.mock('../_links/extendedAttributes');
jest.mock('../../utils/errorHandling');
jest.mock('@proton/shared/lib/api/helpers/apiErrorHelper');
const mockedGetVerificationKey = jest.fn();
const mockedGetLinkPrivateKey = jest.fn();
const mockedDecryptExtendedAttributes = jest.mocked(decryptExtendedAttributes);
const mockedSendErrorReport = jest.mocked(sendErrorReport);
const mockedGetIsConnectionIssue = jest.mocked(getIsConnectionIssue);
jest.mocked(useDriveCrypto).mockImplementation(() => ({
...jest.requireMock('../_crypto').useDriveCrypto,
getVerificationKey: mockedGetVerificationKey,
}));
jest.mocked(useLink).mockImplementation(() => ({
...jest.requireMock('../_links').useDriveCrypto,
getLinkPrivateKey: mockedGetLinkPrivateKey,
}));
const mockedCheckFirstBlockSignature = jest.fn();
jest.mocked(useDownload).mockImplementation(() => ({
...jest.requireMock('../_downloads').useDownload,
checkFirstBlockSignature: mockedCheckFirstBlockSignature,
}));
jest.mocked(decryptExtendedAttributes);
const revisionXattrs: ParsedExtendedAttributes = {
Common: {
ModificationTime: 1681715947,
},
};
const revisionEncryptedXattrs = 'encryptedXattrs';
const revisionSignatureAddress = 'revisionSignatureAddress';
const shareId = 'shareId';
const linkId = 'linkId';
describe('useRevision', () => {
let abortSignal: AbortSignal;
beforeEach(() => {
abortSignal = new AbortController().signal;
});
it('getRevisionDecryptedXattrs', async () => {
mockedGetVerificationKey.mockResolvedValue(['key']);
mockedGetLinkPrivateKey.mockResolvedValue('privateKey');
mockedDecryptExtendedAttributes.mockResolvedValue({
xattrs: revisionXattrs,
verified: VERIFICATION_STATUS.SIGNED_AND_VALID,
});
const {
result: {
current: { getRevisionDecryptedXattrs },
},
} = renderHook(() => useRevisions(shareId, linkId));
const result = await getRevisionDecryptedXattrs(abortSignal, revisionEncryptedXattrs, revisionSignatureAddress);
expect(mockedGetVerificationKey).toHaveBeenCalledWith(revisionSignatureAddress);
expect(mockedGetLinkPrivateKey).toHaveBeenCalledWith(abortSignal, shareId, linkId);
expect(mockedDecryptExtendedAttributes).toHaveBeenCalledWith(revisionEncryptedXattrs, 'privateKey', ['key']);
expect(result).toStrictEqual({
xattrs: revisionXattrs,
signatureIssues: {
xattrs: VERIFICATION_STATUS.SIGNED_AND_VALID,
},
});
});
it('getRevisionDecryptedXattrs should sendErrorReport if a promise failed', async () => {
mockedDecryptExtendedAttributes.mockResolvedValue({
xattrs: revisionXattrs,
verified: VERIFICATION_STATUS.SIGNED_AND_VALID,
});
mockedGetVerificationKey.mockResolvedValue(['key']);
const error = new Error('getLinkPrivateKey error');
mockedGetLinkPrivateKey.mockRejectedValue(error);
const {
result: {
current: { getRevisionDecryptedXattrs },
},
} = renderHook(() => useRevisions(shareId, linkId));
const result = await getRevisionDecryptedXattrs(abortSignal, revisionEncryptedXattrs, revisionSignatureAddress);
expect(result).toBeUndefined();
expect(mockedSendErrorReport).toHaveBeenCalledWith(error);
});
it('checkRevisionSignature result should be undefined if no issues', async () => {
const revisionId = 'revisionId';
mockedCheckFirstBlockSignature.mockResolvedValueOnce(undefined);
const {
result: {
current: { checkRevisionSignature },
},
} = renderHook(() => useRevisions(shareId, linkId));
const result = await checkRevisionSignature(abortSignal, revisionId);
expect(mockedCheckFirstBlockSignature).toHaveBeenCalledWith(abortSignal, shareId, linkId, revisionId);
expect(result).toBeUndefined();
});
it('checkRevisionSignature should throw an error if there is connection issues', async () => {
const revisionId = 'revisionId';
const error = new Error('Network error');
mockedCheckFirstBlockSignature.mockRejectedValue(error);
mockedGetIsConnectionIssue.mockReturnValue(true);
const {
result: {
current: { checkRevisionSignature },
},
} = renderHook(() => useRevisions(shareId, linkId));
const errorResult = checkRevisionSignature(abortSignal, revisionId);
await expect(errorResult).rejects.toThrowError(error);
expect(mockedGetIsConnectionIssue).toHaveBeenCalledWith(error);
});
it('checkRevisionSignature should sendErrorReport and return signatureIssues', async () => {
const revisionId = 'revisionId';
const error = new Error('checkFirstBlockSignature error');
mockedCheckFirstBlockSignature.mockRejectedValue(error);
mockedGetIsConnectionIssue.mockReturnValue(false);
const {
result: {
current: { checkRevisionSignature },
},
} = renderHook(() => useRevisions(shareId, linkId));
const result = await checkRevisionSignature(abortSignal, revisionId);
expect(mockedSendErrorReport).toHaveBeenCalledWith(error);
expect(result).toStrictEqual({
contentKeyPacket: VERIFICATION_STATUS.NOT_SIGNED,
blocks: VERIFICATION_STATUS.NOT_SIGNED,
thumbnail: VERIFICATION_STATUS.NOT_SIGNED,
});
});
});
|
3,137 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_search | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_search/indexing/useKeysCache.test.ts | import { CryptoApiInterface, CryptoProxy, PrivateKeyReference } from '@proton/crypto';
import { LinkType } from '@proton/shared/lib/interfaces/drive/link';
import { KeyCache, createKeysCache } from './useKeysCache';
const linkMock = {
CreateTime: 123456,
Hash: '',
Index: 0,
LinkID: 'link-mock-id',
MIMEType: '',
ModifyTime: 1234,
Name: '',
ParentLinkID: null,
Size: 123,
State: 0,
Type: LinkType.FOLDER,
};
const DECRYPTED_NAME = 'a smell of petroleum prevails throughout';
const PRIVATE_KEY = 'private-key';
const mockedCryptoApi = {
importPrivateKey: jest.fn().mockImplementation(() => PRIVATE_KEY),
} as any as CryptoApiInterface;
jest.mock('@proton/shared/lib/keys/driveKeys', () => ({
decryptUnsigned: jest.fn().mockImplementation(() => DECRYPTED_NAME),
}));
jest.mock('@proton/shared/lib/keys/drivePassphrase', () => ({
decryptPassphrase: jest.fn().mockImplementation(() => ({
decryptedPassphrase: '',
})),
}));
describe('useKeysCache', () => {
let keyCache: KeyCache;
beforeAll(() => {
CryptoProxy.setEndpoint(mockedCryptoApi);
});
afterAll(async () => {
await CryptoProxy.releaseEndpoint();
});
beforeEach(() => {
keyCache = createKeysCache('key' as unknown as PrivateKeyReference);
});
it('caches decrypted links', async () => {
const { name } = await keyCache.decryptAndCacheLink(linkMock, {} as unknown as PrivateKeyReference);
expect(name).toEqual(DECRYPTED_NAME);
const key = keyCache.getCachedPrivateKey(linkMock.LinkID);
expect(key).toEqual(PRIVATE_KEY);
});
it("returns undefined when unknown link's keys are requested", async () => {
const result = keyCache.getCachedPrivateKey('new-link-id');
expect(result).toBe(undefined);
});
});
|
3,140 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_settings/sorting.test.ts | import { SORT_DIRECTION } from '@proton/shared/lib/constants';
import { SortField } from '../_views/utils/useSorting';
import * as sorting from './sorting';
describe('sorting', () => {
it('should return SortSetting identifier given SortParams', () => {
expect(sorting.getSetting({ sortField: SortField.name, sortOrder: SORT_DIRECTION.DESC })).toBe(-1);
expect(sorting.getSetting({ sortField: SortField.size, sortOrder: SORT_DIRECTION.ASC })).toBe(2);
expect(sorting.getSetting({ sortField: SortField.fileModifyTime, sortOrder: SORT_DIRECTION.ASC })).toBe(4);
});
it('should return SortParams given SortSetting identifier', () => {
expect(sorting.parseSetting(1)).toEqual({
sortField: 'name',
sortOrder: SORT_DIRECTION.ASC,
});
expect(sorting.parseSetting(-2)).toEqual({
sortField: 'size',
sortOrder: SORT_DIRECTION.DESC,
});
expect(sorting.parseSetting(-4)).toEqual({
sortField: 'fileModifyTime',
sortOrder: SORT_DIRECTION.DESC,
});
});
});
|
3,145 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_shares/shareUrl.test.ts | import { SharedURLFlags } from '@proton/shared/lib/interfaces/drive/sharing';
import { hasCustomPassword, hasGeneratedPasswordIncluded, splitGeneratedAndCustomPassword } from './shareUrl';
describe('Password flags checks', () => {
describe('Missing data check', () => {
it('returns false if flags are undefined', () => {
expect(hasCustomPassword({})).toEqual(false);
expect(hasGeneratedPasswordIncluded({})).toEqual(false);
});
it('returns false if SharedURLInfo is abscent', () => {
expect(hasCustomPassword()).toEqual(false);
expect(hasGeneratedPasswordIncluded()).toEqual(false);
});
});
describe('hasCustomPassword', () => {
it('returns true is CustomPassword flag is present', () => {
expect(hasCustomPassword({ flags: 0 | SharedURLFlags.CustomPassword })).toEqual(true);
expect(
hasCustomPassword({ flags: SharedURLFlags.GeneratedPasswordIncluded | SharedURLFlags.CustomPassword })
).toEqual(true);
expect(hasCustomPassword({ flags: 0 })).toEqual(false);
});
});
describe('hasGeneratedPasswordIncluded', () => {
it('returns true is CustomPassword flag is present', () => {
expect(hasGeneratedPasswordIncluded({ flags: 0 | SharedURLFlags.GeneratedPasswordIncluded })).toEqual(true);
expect(
hasGeneratedPasswordIncluded({
flags: SharedURLFlags.GeneratedPasswordIncluded | SharedURLFlags.CustomPassword,
})
).toEqual(true);
expect(hasGeneratedPasswordIncluded({ flags: 0 })).toEqual(false);
});
});
});
describe('splitGeneratedAndCustomPassword', () => {
it('no custom password returns only generated password', () => {
expect(splitGeneratedAndCustomPassword('1234567890ab', { flags: 0 })).toEqual(['1234567890ab', '']);
});
it('legacy custom password returns only custom password', () => {
expect(splitGeneratedAndCustomPassword('abc', { flags: SharedURLFlags.CustomPassword })).toEqual(['', 'abc']);
});
it('new custom password returns both generated and custom password', () => {
expect(
splitGeneratedAndCustomPassword('1234567890ababc', {
flags: SharedURLFlags.CustomPassword | SharedURLFlags.GeneratedPasswordIncluded,
})
).toEqual(['1234567890ab', 'abc']);
});
});
|
3,149 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_shares/useDefaultShare.test.tsx | import { act, renderHook } from '@testing-library/react-hooks';
import { VolumesStateProvider } from '../_volumes/useVolumesState';
import useDefaultShare from './useDefaultShare';
const mockRequest = jest.fn();
const mockCreateVolume = jest.fn();
const mockGetDefaultShareId = jest.fn();
const mockGetShare = jest.fn();
const mockGetShareWithKey = jest.fn();
jest.mock('../_api/useDebouncedRequest', () => {
const useDebouncedRequest = () => {
return mockRequest;
};
return useDebouncedRequest;
});
jest.mock('../_utils/useDebouncedFunction', () => {
const useDebouncedFunction = () => {
return (wrapper: any) => wrapper();
};
return useDebouncedFunction;
});
jest.mock('./useSharesState', () => {
const useSharesState = () => {
return {
setShares: () => {},
getDefaultShareId: mockGetDefaultShareId,
};
};
return {
...jest.requireActual('./useSharesState'),
__esModule: true,
default: useSharesState,
};
});
jest.mock('../_shares/useShare', () => {
const useLink = () => {
return {
getShare: mockGetShare,
getShareWithKey: mockGetShareWithKey,
};
};
return useLink;
});
jest.mock('./useVolume', () => {
const useVolume = () => {
return {
createVolume: mockCreateVolume,
};
};
return useVolume;
});
describe('useDefaultShare', () => {
let hook: {
current: ReturnType<typeof useDefaultShare>;
};
const defaultShareId = Symbol('shareId');
const ac = new AbortController();
beforeEach(() => {
jest.resetAllMocks();
mockCreateVolume.mockImplementation(async () => {
return { shareId: defaultShareId };
});
mockRequest.mockImplementation(async () => {
return { Shares: [] };
});
const wrapper = ({ children }: { children: React.ReactNode }) => (
<VolumesStateProvider>{children}</VolumesStateProvider>
);
const { result } = renderHook(() => useDefaultShare(), { wrapper });
hook = result;
});
it('creates a volume if existing shares are locked/soft deleted', async () => {
mockGetDefaultShareId.mockImplementation(() => {
// no valid shares were found
return undefined;
});
await act(async () => {
await hook.current.getDefaultShare();
});
expect(mockCreateVolume.mock.calls.length).toBe(1);
expect(mockGetShareWithKey).toHaveBeenCalledWith(expect.anything(), defaultShareId);
});
it('creates a volume if no shares exist', async () => {
mockRequest.mockImplementation(async () => {
return { Shares: [] };
});
await act(async () => {
await hook.current.getDefaultShare();
});
expect(mockCreateVolume.mock.calls.length).toBe(1);
expect(mockGetShareWithKey).toHaveBeenCalledWith(expect.anything(), defaultShareId);
});
it("creates a volume if default share doesn't exist", async () => {
mockRequest.mockImplementation(async () => {
return {
Shares: [
{
isDefault: false,
},
],
};
});
await act(async () => {
await hook.current.getDefaultShare();
});
expect(mockCreateVolume.mock.calls.length).toBe(1);
expect(mockGetShareWithKey).toHaveBeenCalledWith(expect.anything(), defaultShareId);
});
it('says share is available by default', async () => {
mockGetShare.mockImplementation(async () => ({}));
await act(async () => {
const isAvailable = await hook.current.isShareAvailable(ac.signal, 'shareId');
expect(isAvailable).toBeTruthy();
});
});
it('says share is not available if locked', async () => {
mockGetShare.mockImplementation(async () => {
return {
isLocked: true,
};
});
await act(async () => {
const isAvailable = await hook.current.isShareAvailable(ac.signal, 'shareId');
expect(isAvailable).toBeFalsy();
});
});
it('says share is not available if soft deleted', async () => {
mockGetShare.mockImplementation(async () => {
return {
isVolumeSoftDeleted: true,
};
});
await act(async () => {
const isAvailable = await hook.current.isShareAvailable(ac.signal, 'shareId');
expect(isAvailable).toBeFalsy();
});
});
});
|
3,155 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_shares/useSharesKeys.test.tsx | import { SharesKeysStorage } from './useSharesKeys';
describe('useSharesKeys', () => {
let keys: SharesKeysStorage;
beforeEach(() => {
keys = new SharesKeysStorage();
});
it('returns empty passphrase when not set', () => {
// @ts-ignore: We simplify types in tests, so we don't have to construct OpenPGP key.
keys.set('shareId', 'pk', 'sk');
const passphrase = keys.get('missingShareId');
expect(passphrase).toBe(undefined);
});
it('returns the cached passphrase', () => {
// @ts-ignore: We simplify types in tests, so we don't have to construct OpenPGP key.
keys.set('shareId', 'pk', 'sk');
const passphrase = keys.get('shareId');
expect(passphrase).toMatchObject({
privateKey: 'pk',
sessionKey: 'sk',
});
});
});
|
3,157 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_shares/useSharesState.test.tsx | import { act, renderHook } from '@testing-library/react-hooks';
import { Share, ShareState, ShareType } from './interface';
import { useSharesStateProvider } from './useSharesState';
function createTestShare(
shareId: string,
volumeId: string,
flags = {
isLocked: false,
isDefault: false,
isVolumeSoftDeleted: false,
type: ShareType.standard,
state: ShareState.active,
}): Share {
return {
shareId,
rootLinkId: 'linkId',
volumeId,
creator: 'creator',
...flags,
possibleKeyPackets: [],
};
}
describe('useSharesState', () => {
let hook: {
current: ReturnType<typeof useSharesStateProvider>;
};
const mainShare1 = createTestShare('mainShare1', 'volume1', {
isLocked: true,
isDefault: true,
isVolumeSoftDeleted: false,
type: ShareType.default,
state: ShareState.active,
});
const device1 = createTestShare('device1', 'volume1', {
isLocked: true,
isDefault: false,
isVolumeSoftDeleted: false,
type: ShareType.device,
state: ShareState.active,
});
const device2 = createTestShare('device2', 'volume1', {
isLocked: true,
isDefault: false,
isVolumeSoftDeleted: false,
type: ShareType.device,
state: ShareState.active,
});
const share1 = createTestShare('share1', 'volume1', {
isLocked: true,
isDefault: false,
isVolumeSoftDeleted: false,
type: ShareType.standard,
state: ShareState.active,
});
const mainShare2 = createTestShare('mainShare2', 'volume2', {
isLocked: true,
isDefault: true,
isVolumeSoftDeleted: false,
type: ShareType.default,
state: ShareState.active,
});
const device3 = createTestShare('device3', 'volume2', {
isLocked: true,
isDefault: false,
isVolumeSoftDeleted: false,
type: ShareType.device,
state: ShareState.active,
});
const share2 = createTestShare('share2', 'volume2', {
isLocked: true,
isDefault: false,
isVolumeSoftDeleted: false,
type: ShareType.standard,
state: ShareState.active,
});
const mainShare3 = createTestShare('mainShare3', 'volume3', {
isLocked: false,
isDefault: true,
isVolumeSoftDeleted: false,
type: ShareType.default,
state: ShareState.active,
});
const device4 = createTestShare('device4', 'volume3', {
isLocked: false,
isDefault: false,
isVolumeSoftDeleted: false,
type: ShareType.device,
state: ShareState.active,
});
const mainShare4 = createTestShare('mainShare4', 'volume4', {
isLocked: true,
isDefault: true,
isVolumeSoftDeleted: true,
type: ShareType.default,
state: ShareState.active,
});
const device5 = createTestShare('device5', 'volume4', {
isLocked: true,
isDefault: false,
isVolumeSoftDeleted: true,
type: ShareType.device,
state: ShareState.active,
});
beforeEach(() => {
jest.resetAllMocks();
const { result } = renderHook(() => useSharesStateProvider());
hook = result;
act(() => {
hook.current.setShares([
mainShare1,
device1,
device2,
share1,
mainShare2,
device3,
share2,
mainShare3,
device4,
mainShare4,
device5,
]);
});
});
it('returns only locked undeleted shares with its devices', async () => {
const lockedShares = hook.current.getLockedShares();
expect(lockedShares).toMatchObject([
{
defaultShare: mainShare1,
devices: [device1, device2],
},
{
defaultShare: mainShare2,
devices: [device3],
},
]);
});
});
|
3,161 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_shares | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_shares/useLockedVolume/useLockedVolume.test.tsx | import { act, renderHook } from '@testing-library/react-hooks';
import { User } from '@proton/shared/lib/interfaces';
import { getDecryptedUserKeysHelper } from '@proton/shared/lib/keys';
import { getUserKey } from '@proton/shared/test/keys/keyDataHelper';
import { generateAddress, releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../utils/test/crypto';
import { VolumesStateProvider } from '../../_volumes/useVolumesState';
import { LockedVolumeForRestore } from '../interface';
import useSharesState from '../useSharesState';
import useLockedVolume, { useLockedVolumeInner } from './useLockedVolume';
const mockRequest = jest.fn();
jest.mock('../../_api/useDebouncedRequest', () => {
const useDebouncedRequest = () => {
return mockRequest;
};
return useDebouncedRequest;
});
jest.mock('../../_utils/useDebouncedFunction', () => {
const useDebouncedFunction = () => {
return (wrapper: any) => wrapper();
};
return useDebouncedFunction;
});
jest.mock('@proton/components/hooks/usePreventLeave', () => {
const usePreventLeave = () => {
return (wrapper: any) => wrapper();
};
return usePreventLeave;
});
const SHARE_MOCK_1 = {
shareId: 'shareId1',
lockedVolumeId: 'volumeId1',
linkDecryptedPassphrase: 'passphrase',
};
const SHARE_MOCK_2 = {
shareId: 'shareId2',
lockedVolumeId: 'volumeId2',
linkDecryptedPassphrase: 'passphrase',
};
const LOCKED_VOLUME_MOCK_1 = {
lockedVolumeId: 'volumeId1',
defaultShare: SHARE_MOCK_1,
devices: [],
photos: [],
};
const LOCKED_VOLUME_MOCK_2 = {
lockedVolumeId: 'volumeId2',
defaultShare: SHARE_MOCK_2,
devices: [],
photos: [],
};
const mockGetLockedShares = jest.fn();
const mockGetShareWithKey = jest.fn();
const sharesStateMock: ReturnType<typeof useSharesState> = {
getLockedShares: mockGetLockedShares,
removeShares: jest.fn(),
setShares: jest.fn(),
getShare: jest.fn(),
getDefaultShareId: jest.fn(),
setLockedVolumesForRestore: jest.fn(),
lockedVolumesForRestore: [],
getDefaultPhotosShareId: jest.fn(),
getRestoredPhotosShares: jest.fn(),
};
const generateAddressKeys = async () => {
const keyPassword = 'password';
const userKeysFull = await Promise.all([getUserKey('a', keyPassword, 2), getUserKey('b', keyPassword, 2)]);
const UserKeys = userKeysFull.map(({ Key }) => Key);
const User1 = {
Keys: UserKeys.slice(0, 1),
} as unknown as User;
const decryptedUserKeys = await getDecryptedUserKeysHelper(User1, keyPassword);
return [
{
address: await generateAddress(UserKeys, '[email protected]'),
keys: decryptedUserKeys,
},
];
};
const useHook = (props: any = {}) => {
return useLockedVolumeInner({
sharesState: sharesStateMock,
getShareWithKey: jest.fn(),
addressesKeys: [],
getDefaultShare: jest.fn(),
getOwnAddressAndPrimaryKeys: jest.fn(),
prepareVolumeForRestore: jest.fn(),
getLinkPrivateKey: jest.fn(),
getLinkHashKey: jest.fn(),
getDeviceByShareId: jest.fn(),
...props,
});
};
describe('useLockedVolume', () => {
const abortSignal = new AbortController().signal;
let hook: {
current: ReturnType<typeof useLockedVolume>;
};
const wrapper = ({ children }: { children: React.ReactNode }) => (
<VolumesStateProvider>{children}</VolumesStateProvider>
);
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(() => {
jest.resetAllMocks();
mockGetLockedShares.mockImplementation(() => {
return [];
});
});
describe('prepareVolumesForRestore', () => {
it("should return locked volumes if there's no private keys associated with address", async () => {
const { result } = renderHook(() => useHook(), { wrapper });
hook = result;
sharesStateMock.lockedVolumesForRestore = [LOCKED_VOLUME_MOCK_1, LOCKED_VOLUME_MOCK_2];
await act(async () => {
const result = await hook.current.prepareVolumesForRestore(abortSignal);
expect(result).toMatchObject([LOCKED_VOLUME_MOCK_1, LOCKED_VOLUME_MOCK_2]);
});
});
it("should return locked volumes if there's no locked unprepared shares", async () => {
const addressesKeys = await generateAddressKeys();
const { result } = renderHook(
() =>
useHook({
addressesKeys,
}),
{ wrapper }
);
hook = result;
sharesStateMock.lockedVolumesForRestore = [LOCKED_VOLUME_MOCK_1, LOCKED_VOLUME_MOCK_2];
await act(async () => {
const result = await hook.current.prepareVolumesForRestore(abortSignal);
expect(result).toMatchObject([LOCKED_VOLUME_MOCK_1, LOCKED_VOLUME_MOCK_2]);
});
});
it("should return locked volumes if there's no new prepared shares", async () => {
mockGetLockedShares.mockImplementation(() => {
return [{ defaultShare: { shareId: 'shareId' }, devices: [], photos: [] }];
});
mockGetShareWithKey.mockImplementation(() => {
return [{ shareId: 'shareId' }];
});
const addressesKeys = await generateAddressKeys();
const { result } = renderHook(
() =>
useHook({
addressesKeys,
getShareWithKey: mockGetShareWithKey,
}),
{ wrapper }
);
hook = result;
sharesStateMock.lockedVolumesForRestore = [LOCKED_VOLUME_MOCK_1, LOCKED_VOLUME_MOCK_2];
await act(async () => {
const result = await hook.current.prepareVolumesForRestore(abortSignal);
expect(result).toMatchObject([LOCKED_VOLUME_MOCK_1, LOCKED_VOLUME_MOCK_2]);
});
});
it('should return extended volume list with new prepared volumes', async () => {
mockGetLockedShares.mockImplementation(() => {
return [{ defaultShare: { shareId: 'shareId' }, devices: [], photos: [] }];
});
mockGetShareWithKey.mockImplementation(() => {
return [{ shareId: 'shareId' }];
});
const lockedVolumeForRestore = {
lockedVolumeId: 'volumeId',
defaultShare: {
shareId: 'shareId',
linkDecryptedPassphrase: 'passphrase',
},
} as LockedVolumeForRestore;
const addressesKeys = await generateAddressKeys();
const { result } = renderHook(
() =>
useHook({
addressesKeys,
getShareWithKey: mockGetShareWithKey,
prepareVolumeForRestore: async () => lockedVolumeForRestore,
}),
{ wrapper }
);
hook = result;
sharesStateMock.lockedVolumesForRestore = [LOCKED_VOLUME_MOCK_1, LOCKED_VOLUME_MOCK_2];
await act(async () => {
const result = await hook.current.prepareVolumesForRestore(abortSignal);
expect(result).toMatchObject([LOCKED_VOLUME_MOCK_1, LOCKED_VOLUME_MOCK_2, lockedVolumeForRestore]);
});
});
});
});
|
3,163 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_shares | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_shares/useLockedVolume/utils.test.ts | import { DecryptedKey, User } from '@proton/shared/lib/interfaces';
import { getDecryptedUserKeysHelper } from '@proton/shared/lib/keys';
import { getUserKey } from '@proton/shared/test/keys/keyDataHelper';
import { generateAddress, releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../utils/test/crypto';
import { getPossibleAddressPrivateKeys } from './utils';
const DEFAULT_KEYPASSWORD = '1';
jest.setTimeout(20000);
describe('useLockedVolume -- utils', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
describe('getPossibleAddressPrivateKeys()', () => {
it('return empty array if no matching keys found', async () => {
const keyPassword = DEFAULT_KEYPASSWORD;
const userKeysFull = await Promise.all([getUserKey('a', keyPassword, 2), getUserKey('b', keyPassword, 2)]);
const UserKeys = userKeysFull.map(({ Key }) => Key);
const decryptedUserKeys: DecryptedKey[] = [];
const addressesKeys = [
{
address: await generateAddress(UserKeys, '[email protected]'),
keys: decryptedUserKeys,
},
];
expect(getPossibleAddressPrivateKeys(addressesKeys).length).toBe(0);
});
it('return only matching decrypted keys', async () => {
const keyPassword = DEFAULT_KEYPASSWORD;
const user1KeysFull = await Promise.all([getUserKey('a', keyPassword, 2), getUserKey('b', keyPassword, 2)]);
const user2KeysFull = await Promise.all([getUserKey('c', keyPassword, 2), getUserKey('d', keyPassword, 2)]);
const User1Keys = user1KeysFull.map(({ Key }) => Key);
const User2Keys = user2KeysFull.map(({ Key }) => Key);
const User1 = {
Keys: User1Keys.slice(0, 1),
} as unknown as User;
const User2 = {
Keys: User2Keys.slice(0, 1),
} as unknown as User;
const decryptedUserKeysUser1 = await getDecryptedUserKeysHelper(User1, keyPassword);
const decryptedUserKeysUser2 = await getDecryptedUserKeysHelper(User2, keyPassword);
const addressesKeysUser1 = [
{
address: await generateAddress(User1Keys, '[email protected]'),
keys: decryptedUserKeysUser1,
},
];
const addressesKeysUser2 = [
{
address: await generateAddress(User2Keys, '[email protected]'),
keys: decryptedUserKeysUser2,
},
];
expect(getPossibleAddressPrivateKeys(addressesKeysUser1)).toMatchObject(
decryptedUserKeysUser1.map((decryptedKey) => decryptedKey.privateKey)
);
expect(getPossibleAddressPrivateKeys(addressesKeysUser2)).toMatchObject(
decryptedUserKeysUser2.map((decryptedKey) => decryptedKey.privateKey)
);
});
});
});
|
3,181 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/UploadProvider/useUploadConflict.test.tsx | import { ReactNode } from 'react';
import { act, renderHook } from '@testing-library/react-hooks';
import { ModalsProvider } from '@proton/components';
import { TransferState } from '../../../components/TransferManager/transfer';
import { mockGlobalFile, testFile } from '../../../utils/test/file';
import { TransferConflictStrategy } from '../interface';
import { FileUpload, FolderUpload } from './interface';
import useUploadConflict from './useUploadConflict';
const mockModal = jest.fn();
const mockShowModal = jest.fn();
jest.mock('../../../components/modals/ConflictModal.tsx', () => ({
useConflictModal: () => [mockModal, mockShowModal],
}));
describe('useUploadConflict', () => {
const mockUpdateState = jest.fn();
const mockUpdateWithData = jest.fn();
const mockCancelUploads = jest.fn();
let abortController: AbortController;
const renderConflict = () => {
const fileUploads: FileUpload[] = ['file1', 'file2'].map((id) => ({
id,
shareId: 'shareId',
startDate: new Date(),
state: TransferState.Conflict,
file: testFile(`${id}.txt`),
meta: {
filename: `${id}.txt`,
mimeType: 'txt',
},
}));
const folderUploads: FolderUpload[] = [];
const wrapper = ({ children }: { children: ReactNode }) => <ModalsProvider>{children}</ModalsProvider>;
const { result } = renderHook(
() => useUploadConflict(fileUploads, folderUploads, mockUpdateState, mockUpdateWithData, mockCancelUploads),
{ wrapper }
);
return result;
};
beforeEach(() => {
mockGlobalFile();
mockModal.mockClear();
mockShowModal.mockClear();
mockUpdateState.mockClear();
mockUpdateWithData.mockClear();
mockCancelUploads.mockClear();
abortController = new AbortController();
});
it('aborts promise returned by file conflict handler', async () => {
const hook = renderConflict();
await act(async () => {
const conflictHandler = hook.current.getFileConflictHandler('file1');
const promise = conflictHandler(abortController.signal);
expect(mockUpdateWithData.mock.calls).toMatchObject([
['file1', 'conflict', { originalIsFolder: undefined }],
]);
abortController.abort();
await expect(promise).rejects.toThrowError('Upload was canceled');
});
});
it('updates with info about original item', async () => {
const hook = renderConflict();
await act(async () => {
const conflictHandler = hook.current.getFileConflictHandler('file1');
const originalIsDraft = true;
const originalIsFolder = false;
const promise = conflictHandler(abortController.signal, originalIsDraft, originalIsFolder);
expect(mockUpdateWithData.mock.calls).toMatchObject([
['file1', 'conflict', { originalIsDraft, originalIsFolder }],
]);
abortController.abort();
await expect(promise).rejects.toThrowError('Upload was canceled');
});
});
it('waits and resolves in conflict strategy for one', async () => {
mockShowModal.mockImplementation(({ apply }) => {
apply(TransferConflictStrategy.Rename, false);
});
const hook = renderConflict();
await act(async () => {
const conflictHandler = hook.current.getFileConflictHandler('file1');
const promise = conflictHandler(abortController.signal);
await expect(promise).resolves.toBe(TransferConflictStrategy.Rename);
expect(mockUpdateState.mock.calls.length).toBe(1);
expect(mockUpdateState.mock.calls[0][0]).toBe('file1');
expect(mockCancelUploads.mock.calls.length).toBe(0);
});
});
it('waits and resolves in conflict strategy for all', async () => {
mockShowModal.mockImplementation(({ apply }) => {
apply(TransferConflictStrategy.Rename, true);
});
const hook = renderConflict();
await act(async () => {
const conflictHandler1 = hook.current.getFileConflictHandler('file1');
const promise1 = conflictHandler1(abortController.signal);
await expect(promise1).resolves.toBe(TransferConflictStrategy.Rename);
expect(mockUpdateState.mock.calls.length).toBe(1);
expect(mockUpdateState.mock.calls[0][0]).not.toBe('file1'); // It is dynamic function check later.
expect(mockCancelUploads.mock.calls.length).toBe(0);
const conflictHandler2 = hook.current.getFileConflictHandler('file2');
const promise2 = conflictHandler2(abortController.signal);
await expect(promise2).resolves.toBe(TransferConflictStrategy.Rename);
// Only conflicting files are updated for file resolver.
const updateState = mockUpdateState.mock.calls[0][0];
[
[TransferState.Conflict, testFile('a.txt'), true],
[TransferState.Conflict, undefined, false],
[TransferState.Progress, testFile('a.txt'), false],
[TransferState.Progress, undefined, false],
].forEach(([state, file, expectedResult]) => {
expect(updateState({ state, file })).toBe(expectedResult);
});
});
});
it('waits and cancels all uploads', async () => {
mockShowModal.mockImplementation(({ cancelAll }) => {
cancelAll();
});
const hook = renderConflict();
await act(async () => {
const conflictHandler1 = hook.current.getFileConflictHandler('file1');
const promise1 = conflictHandler1(abortController.signal);
await expect(promise1).resolves.toBe(TransferConflictStrategy.Skip);
const conflictHandler2 = hook.current.getFileConflictHandler('file2');
const promise2 = conflictHandler2(abortController.signal);
await expect(promise2).resolves.toBe(TransferConflictStrategy.Skip);
expect(mockUpdateState.mock.calls.length).toBe(0);
expect(mockCancelUploads.mock.calls.length).toBe(1);
});
});
});
|
3,183 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/UploadProvider/useUploadControl.test.ts | import { act, renderHook } from '@testing-library/react-hooks';
import { FILE_CHUNK_SIZE } from '@proton/shared/lib/drive/constants';
import { TransferState } from '../../../components/TransferManager/transfer';
import { mockGlobalFile, testFile } from '../../../utils/test/file';
import { MAX_BLOCKS_PER_UPLOAD } from '../constants';
import { UploadFileControls, UploadFolderControls } from '../interface';
import { FileUpload, UpdateFilter } from './interface';
import useUploadControl from './useUploadControl';
function makeFileUpload(id: string, state: TransferState, filename: string, size = 2 * FILE_CHUNK_SIZE): FileUpload {
const file = testFile(filename, size);
return {
id,
shareId: 'shareId',
startDate: new Date(),
state,
file,
meta: {
filename: file.name,
mimeType: file.type,
size: file.size,
},
};
}
describe('useUploadControl', () => {
const mockUpdateWithCallback = jest.fn();
const mockRemoveFromQueue = jest.fn();
const mockClearQueue = jest.fn();
let hook: {
current: {
add: (id: string, uploadControls: UploadFileControls | UploadFolderControls) => void;
remove: (id: string) => void;
updateProgress: (id: string, increment: number) => void;
calculateRemainingUploadBytes: () => number;
calculateFileUploadLoad: () => number;
pauseUploads: (idOrFilter: UpdateFilter) => void;
resumeUploads: (idOrFilter: UpdateFilter) => void;
cancelUploads: (idOrFilter: UpdateFilter) => void;
removeUploads: (idOrFilter: UpdateFilter) => void;
};
};
beforeEach(() => {
mockUpdateWithCallback.mockClear();
mockRemoveFromQueue.mockClear();
mockClearQueue.mockClear();
mockGlobalFile();
const fileUploads: FileUpload[] = [
makeFileUpload('init', TransferState.Initializing, 'init.txt'),
makeFileUpload('pending', TransferState.Pending, 'pending.txt'),
makeFileUpload('progress', TransferState.Progress, 'progress.txt', 2 * FILE_CHUNK_SIZE + 42),
makeFileUpload('empty', TransferState.Progress, 'empty.txt', 0),
makeFileUpload('big', TransferState.Progress, 'big.txt', 100 * FILE_CHUNK_SIZE),
makeFileUpload('done', TransferState.Done, 'done.txt'),
];
const { result } = renderHook(() =>
useUploadControl(fileUploads, mockUpdateWithCallback, mockRemoveFromQueue, mockClearQueue)
);
hook = result;
});
it('calculates remaining upload bytes', () => {
const controls = { start: jest.fn(), cancel: jest.fn() };
act(() => {
hook.current.add('progress', controls);
hook.current.updateProgress('progress', FILE_CHUNK_SIZE);
hook.current.updateProgress('progress', 47);
hook.current.updateProgress('progress', -5);
expect(hook.current.calculateRemainingUploadBytes()).toBe(
// 2 init + 2 pending + 1 progress (+42 extra) + 100 big
105 * FILE_CHUNK_SIZE + 42
);
});
});
it('calculates file upload load', () => {
const controls = { start: jest.fn(), cancel: jest.fn() };
act(() => {
hook.current.add('progress', controls);
hook.current.updateProgress('progress', FILE_CHUNK_SIZE);
expect(hook.current.calculateFileUploadLoad()).toBe(
// progress (3 - 1 done) + empty (always at least one) + big (max MAX_BLOCKS_PER_UPLOAD)
2 + 1 + MAX_BLOCKS_PER_UPLOAD
);
});
});
});
|
3,188 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/UploadProvider/useUploadQueue.add.test.ts | import { act, renderHook } from '@testing-library/react-hooks';
import { TransferState } from '../../../components/TransferManager/transfer';
import { mockGlobalFile, testFile } from '../../../utils/test/file';
import { UploadFileList } from '../interface';
import { FileUpload, FolderUpload, UploadQueue } from './interface';
import useUploadQueue, { addItemToQueue } from './useUploadQueue';
function createEmptyQueue(): UploadQueue {
return {
shareId: 'shareId',
linkId: 'parentId',
files: [],
folders: [],
};
}
describe('useUploadQueue::add', () => {
let hook: {
current: {
fileUploads: FileUpload[];
folderUploads: FolderUpload[];
add: (shareId: string, parentId: string, fileList: UploadFileList) => void;
};
};
beforeEach(() => {
mockGlobalFile();
const { result } = renderHook(() => useUploadQueue());
hook = result;
});
it('creates new upload queue', () => {
act(() => {
hook.current.add('shareId', 'parentId', [{ path: [], folder: 'folder' }]);
hook.current.add('shareId2', 'parentId2', [{ path: [], folder: 'folder' }]);
});
expect(hook.current.folderUploads).toMatchObject([
{
name: 'folder',
shareId: 'shareId',
parentId: 'parentId',
},
{
name: 'folder',
shareId: 'shareId2',
parentId: 'parentId2',
},
]);
});
it('merges upload queue', () => {
act(() => {
hook.current.add('shareId', 'parentId', [{ path: [], folder: 'folder' }]);
hook.current.add('shareId', 'parentId', [{ path: [], folder: 'folder2' }]);
});
expect(hook.current.folderUploads).toMatchObject([
{
name: 'folder',
shareId: 'shareId',
parentId: 'parentId',
},
{
name: 'folder2',
shareId: 'shareId',
parentId: 'parentId',
},
]);
});
it('throws error when adding file with empty name', () => {
expect(() => {
addItemToQueue('shareId', createEmptyQueue(), { path: [], file: testFile('') });
}).toThrow('File or folder is missing a name');
});
it('throws error when adding folder with empty name', () => {
expect(() => {
addItemToQueue('shareId', createEmptyQueue(), { path: [], folder: '' });
}).toThrow('File or folder is missing a name');
});
it('throws error when adding file to non-existing folder', () => {
expect(() => {
addItemToQueue('shareId', createEmptyQueue(), { path: ['folder'], file: testFile('a.txt') });
}).toThrow('Wrong file or folder structure');
});
it('throws error when adding the same file again', () => {
const queue = createEmptyQueue();
addItemToQueue('shareId', queue, { path: [], file: testFile('a.txt') });
expect(() => {
addItemToQueue('shareId', queue, { path: [], file: testFile('a.txt') });
}).toThrow('File or folder "a.txt" is already uploading');
addItemToQueue('shareId', queue, { path: [], folder: 'folder' });
addItemToQueue('shareId', queue, { path: ['folder'], file: testFile('a.txt') });
expect(() => {
addItemToQueue('shareId', queue, { path: ['folder'], file: testFile('a.txt') });
}).toThrow('File or folder "a.txt" is already uploading');
});
it('throws error when adding the same folder again', () => {
const queue = createEmptyQueue();
addItemToQueue('shareId', queue, { path: [], folder: 'folder' });
expect(() => {
addItemToQueue('shareId', queue, { path: [], folder: 'folder' });
}).toThrow('File or folder "folder" is already uploading');
addItemToQueue('shareId', queue, { path: ['folder'], folder: 'subfolder' });
expect(() => {
addItemToQueue('shareId', queue, { path: ['folder'], folder: 'subfolder' });
}).toThrow('File or folder "subfolder" is already uploading');
});
it('throws error when adding the same folder again with unfinished childs', () => {
const queue = createEmptyQueue();
addItemToQueue('shareId', queue, { path: [], folder: 'folder' });
addItemToQueue('shareId', queue, { path: ['folder'], file: testFile('a.txt') });
queue.folders[0].state = TransferState.Done;
expect(() => {
addItemToQueue('shareId', queue, { path: [], folder: 'folder' });
}).toThrow('File or folder "folder" is already uploading');
queue.folders[0].files[0].state = TransferState.Done;
addItemToQueue('shareId', queue, { path: [], folder: 'folder' });
});
it('adds files to the latest folder', () => {
const queue = createEmptyQueue();
addItemToQueue('shareId', queue, { path: [], folder: 'folder' });
queue.folders[0].state = TransferState.Done;
addItemToQueue('shareId', queue, { path: [], folder: 'folder' });
addItemToQueue('shareId', queue, { path: ['folder'], file: testFile('b.txt') });
expect(queue.folders[0].files.length).toBe(0);
expect(queue.folders[1].files.length).toBe(1);
expect(queue.folders[1].files[0].meta.filename).toBe('b.txt');
});
it('adds files to already prepared filter with pending state', () => {
const queue = createEmptyQueue();
addItemToQueue('shareId', queue, { path: [], folder: 'folder' });
// The first file, before folder is done, is set to init state.
addItemToQueue('shareId', queue, { path: ['folder'], file: testFile('a.txt') });
expect(queue.folders[0].files[0]).toMatchObject({
meta: { filename: 'a.txt' },
state: TransferState.Initializing,
});
// The second file, after folder is done, is set to pending state.
queue.folders[0].state = TransferState.Done;
queue.folders[0].linkId = 'folderId';
addItemToQueue('shareId', queue, { path: ['folder'], file: testFile('b.txt') });
expect(queue.folders[0].files[1]).toMatchObject({
meta: { filename: 'b.txt' },
state: TransferState.Pending,
});
});
});
|
3,189 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/UploadProvider/useUploadQueue.attributes.test.ts | import { act, renderHook } from '@testing-library/react-hooks';
import { TransferState } from '../../../components/TransferManager/transfer';
import { mockGlobalFile, testFile } from '../../../utils/test/file';
import { UploadFileList } from '../interface';
import { FileUpload, FolderUpload } from './interface';
import useUploadQueue from './useUploadQueue';
describe("useUploadQueue' attributes", () => {
let hook: {
current: {
hasUploads: boolean;
fileUploads: FileUpload[];
folderUploads: FolderUpload[];
allUploads: (FileUpload | FolderUpload)[];
add: (shareId: string, parentId: string, fileList: UploadFileList) => void;
};
};
beforeEach(() => {
mockGlobalFile();
const { result } = renderHook(() => useUploadQueue());
hook = result;
});
it('returns empty queue', () => {
expect(hook.current.hasUploads).toBe(false);
expect(hook.current.fileUploads).toMatchObject([]);
expect(hook.current.folderUploads).toMatchObject([]);
expect(hook.current.allUploads).toMatchObject([]);
});
it('returns folder only', () => {
act(() => {
hook.current.add('shareId', 'parentId', [{ path: [], folder: 'folder' }]);
});
const expectedFolder = {
// We don't check ID and startDate.
shareId: 'shareId',
parentId: 'parentId',
state: TransferState.Pending,
name: 'folder',
files: [],
folders: [],
meta: {
filename: 'folder',
size: 0,
mimeType: 'Folder',
},
};
expect(hook.current.hasUploads).toBe(true);
expect(hook.current.fileUploads).toMatchObject([]);
expect(hook.current.folderUploads).toMatchObject([expectedFolder]);
expect(hook.current.allUploads).toMatchObject([expectedFolder]);
});
it('returns file only', () => {
const file = testFile('file.txt');
const dsStore = testFile('.DS_Store');
act(() => {
hook.current.add('shareId', 'parentId', [
{ path: [], file },
{ path: [], file: dsStore }, // .DS_Store files are ignored.
]);
});
const expectedFile = {
// We don't check ID and startDate.
shareId: 'shareId',
parentId: 'parentId',
state: TransferState.Pending,
file,
meta: {
filename: file.name,
mimeType: file.type,
size: file.size,
},
};
expect(hook.current.hasUploads).toBe(true);
expect(hook.current.fileUploads).toMatchObject([expectedFile]);
expect(hook.current.folderUploads).toMatchObject([]);
expect(hook.current.allUploads).toMatchObject([expectedFile]);
});
it('returns both files and folders', () => {
const file = testFile('file.txt');
act(() => {
hook.current.add('shareId', 'parentId', [
{ path: [], folder: 'folder' },
{ path: ['folder'], file },
]);
});
expect(hook.current.hasUploads).toBe(true);
expect(hook.current.fileUploads).toMatchObject([
{
state: TransferState.Initializing,
parentId: undefined,
},
]);
expect(hook.current.folderUploads).toMatchObject([
{
state: TransferState.Pending,
parentId: 'parentId',
files: [{ meta: { filename: 'file.txt' } }],
},
]);
expect(hook.current.allUploads.length).toBe(2);
});
});
|
3,190 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/UploadProvider/useUploadQueue.remove.test.ts | import { act, renderHook } from '@testing-library/react-hooks';
import { mockGlobalFile, testFile } from '../../../utils/test/file';
import { UploadFileList } from '../interface';
import { FileUpload, FolderUpload, UpdateCallback, UpdateFilter } from './interface';
import useUploadQueue from './useUploadQueue';
describe('useUploadQueue::remove', () => {
const mockCallback = jest.fn();
let hook: {
current: {
fileUploads: FileUpload[];
folderUploads: FolderUpload[];
add: (shareId: string, parentId: string, fileList: UploadFileList) => void;
remove: (idOrFilter: UpdateFilter, callback?: UpdateCallback) => void;
};
};
let firstFileId: string;
let firstFolderId: string;
let secondIds: string[];
beforeEach(() => {
mockCallback.mockClear();
mockGlobalFile();
const { result } = renderHook(() => useUploadQueue());
hook = result;
act(() => {
hook.current.add('shareId', 'parentId', [
{ path: [], folder: 'folder1' },
{ path: [], folder: 'folder2' },
{ path: [], folder: 'folder3' },
{ path: [], file: testFile('file1.txt') },
{ path: ['folder1'], file: testFile('file2.txt') },
{ path: ['folder1'], file: testFile('file3.txt') },
{ path: ['folder2'], file: testFile('file4.txt') },
]);
});
firstFileId = hook.current.fileUploads[0].id;
firstFolderId = hook.current.folderUploads[0].id;
secondIds = [hook.current.fileUploads[1].id, hook.current.folderUploads[1].id];
});
it('removes file from the queue using id', () => {
act(() => {
hook.current.remove(firstFileId, mockCallback);
});
expect(mockCallback.mock.calls).toMatchObject([[{ meta: { filename: 'file1.txt' } }]]);
expect(hook.current.folderUploads).toMatchObject([
{ meta: { filename: 'folder1' } },
{ meta: { filename: 'folder2' } },
{ meta: { filename: 'folder3' } },
]);
expect(hook.current.fileUploads).toMatchObject([
{ meta: { filename: 'file2.txt' } },
{ meta: { filename: 'file3.txt' } },
{ meta: { filename: 'file4.txt' } },
]);
});
it('removes folder from the queue using id', () => {
act(() => {
hook.current.remove(firstFolderId, mockCallback);
});
expect(mockCallback.mock.calls).toMatchObject([
[{ meta: { filename: 'folder1' } }],
[{ meta: { filename: 'file2.txt' } }],
[{ meta: { filename: 'file3.txt' } }],
]);
expect(hook.current.folderUploads).toMatchObject([
{ meta: { filename: 'folder2' } },
{ meta: { filename: 'folder3' } },
]);
expect(hook.current.fileUploads).toMatchObject([
{ meta: { filename: 'file1.txt' } },
{ meta: { filename: 'file4.txt' } },
]);
});
it('removes file and folder from the queue using filter', () => {
act(() => {
hook.current.remove(({ id }) => secondIds.includes(id), mockCallback);
});
expect(mockCallback.mock.calls).toMatchObject([
[{ meta: { filename: 'folder2' } }],
[{ meta: { filename: 'file4.txt' } }],
[{ meta: { filename: 'file2.txt' } }],
]);
expect(hook.current.folderUploads).toMatchObject([
{ meta: { filename: 'folder1' } },
{ meta: { filename: 'folder3' } },
]);
expect(hook.current.fileUploads).toMatchObject([
{ meta: { filename: 'file1.txt' } },
{ meta: { filename: 'file3.txt' } },
]);
});
});
|
3,192 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/UploadProvider/useUploadQueue.update.test.ts | import { act, renderHook } from '@testing-library/react-hooks';
import { TransferState } from '../../../components/TransferManager/transfer';
import { mockGlobalFile, testFile } from '../../../utils/test/file';
import { UploadFileList } from '../interface';
import { FileUpload, FolderUpload, UpdateCallback, UpdateData, UpdateFilter, UpdateState } from './interface';
import useUploadQueue from './useUploadQueue';
describe("useUploadQueue's update functions", () => {
let hook: {
current: {
fileUploads: FileUpload[];
folderUploads: FolderUpload[];
add: (shareId: string, parentId: string, fileList: UploadFileList) => void;
updateState: (idOrFilter: UpdateFilter, newStateOrCallback: UpdateState) => void;
updateWithData: (idOrFilter: UpdateFilter, newStateOrCallback: UpdateState, data: UpdateData) => void;
updateWithCallback: (
idOrFilter: UpdateFilter,
newStateOrCallback: UpdateState,
callback: UpdateCallback
) => void;
};
};
let firstFileId: string;
let firstFolderId: string;
let secondFileId: string;
let secondIds: string[];
beforeEach(() => {
mockGlobalFile();
const { result } = renderHook(() => useUploadQueue());
hook = result;
act(() => {
hook.current.add('shareId', 'parentId', [
{ path: [], folder: 'folder1' },
{ path: [], folder: 'folder2' },
{ path: [], folder: 'folder3' },
{ path: [], file: testFile('file1.txt') },
{ path: ['folder1'], file: testFile('file2.txt') },
{ path: ['folder1'], file: testFile('file3.txt') },
{ path: ['folder2'], file: testFile('file4.txt') },
]);
});
firstFileId = hook.current.fileUploads[0].id;
firstFolderId = hook.current.folderUploads[0].id;
secondFileId = hook.current.fileUploads[1].id;
secondIds = [secondFileId, hook.current.folderUploads[1].id];
});
it('updates file state using id', () => {
act(() => {
hook.current.updateState(firstFileId, TransferState.Canceled);
});
expect(hook.current.fileUploads.map(({ state }) => state)).toMatchObject([
TransferState.Canceled,
TransferState.Initializing,
TransferState.Initializing,
TransferState.Initializing,
]);
});
it('updates folder state using id', () => {
act(() => {
hook.current.updateState(firstFolderId, TransferState.Canceled);
});
expect(hook.current.folderUploads.map(({ state }) => state)).toMatchObject([
TransferState.Canceled,
TransferState.Pending,
TransferState.Pending,
]);
});
it('updates file and folder state using filter', () => {
act(() => {
hook.current.updateState(({ id }) => secondIds.includes(id), TransferState.Canceled);
});
expect(hook.current.fileUploads.map(({ state }) => state)).toMatchObject([
TransferState.Pending,
TransferState.Canceled,
TransferState.Initializing,
TransferState.Canceled,
]);
expect(hook.current.folderUploads.map(({ state }) => state)).toMatchObject([
TransferState.Pending,
TransferState.Canceled,
TransferState.Pending,
]);
});
it('updates file and folder by callback', () => {
act(() => {
hook.current.updateState(
() => true,
({ state }) => (state === TransferState.Pending ? TransferState.Error : TransferState.Canceled)
);
});
expect(hook.current.fileUploads.map(({ state }) => state)).toMatchObject([
TransferState.Error,
TransferState.Canceled,
TransferState.Canceled,
TransferState.Canceled,
]);
expect(hook.current.folderUploads.map(({ state }) => state)).toMatchObject([
TransferState.Error,
TransferState.Error,
TransferState.Error,
]);
});
it('updates file state with data', () => {
act(() => {
hook.current.updateWithData(firstFileId, TransferState.Progress, {
name: 'file1 (1).txt',
mimeType: 'txt2',
originalIsDraft: true,
});
});
expect(hook.current.fileUploads[0]).toMatchObject({
state: TransferState.Progress,
meta: {
filename: 'file1 (1).txt',
mimeType: 'txt2',
size: 42,
},
originalIsDraft: true,
});
});
it('updates folder state with data', () => {
act(() => {
hook.current.updateWithData(firstFolderId, TransferState.Progress, {
folderId: 'folderId',
originalIsDraft: true,
});
});
expect(hook.current.folderUploads[0]).toMatchObject({
state: TransferState.Progress,
linkId: 'folderId',
originalIsDraft: true,
});
expect(
hook.current.fileUploads.map(({ parentId, state, meta }) => [meta.filename, state, parentId])
).toMatchObject([
['file1.txt', TransferState.Pending, 'parentId'],
['file2.txt', TransferState.Pending, 'folderId'],
['file3.txt', TransferState.Pending, 'folderId'],
['file4.txt', TransferState.Initializing, undefined],
]);
});
it('updates folder but keeps sub files and folders cancelled', () => {
act(() => {
hook.current.updateState(() => true, TransferState.Canceled);
hook.current.updateWithData(firstFolderId, TransferState.Progress, {
folderId: 'folderId',
});
});
expect(
hook.current.fileUploads.map(({ parentId, state, meta }) => [meta.filename, state, parentId])
).toMatchObject([
['file1.txt', TransferState.Canceled, 'parentId'],
['file2.txt', TransferState.Canceled, 'folderId'],
['file3.txt', TransferState.Canceled, 'folderId'],
['file4.txt', TransferState.Canceled, undefined],
]);
});
it('updates states with error', () => {
const error = new Error('some failuer');
act(() => {
hook.current.updateWithData(({ id }) => secondIds.includes(id), TransferState.Error, {
error,
});
});
expect(hook.current.fileUploads.map(({ state, error, meta }) => [meta.filename, state, error])).toMatchObject([
['file1.txt', TransferState.Pending, undefined],
['file2.txt', TransferState.Error, error],
['file3.txt', TransferState.Initializing, undefined],
['file4.txt', TransferState.Initializing, undefined],
]);
expect(hook.current.folderUploads.map(({ state, error, meta }) => [meta.filename, state, error])).toMatchObject(
[
['folder1', TransferState.Pending, undefined],
['folder2', TransferState.Error, error],
['folder3', TransferState.Pending, undefined],
]
);
});
it('updates state with callback', () => {
const mockCallback = jest.fn();
act(() => {
hook.current.updateWithCallback(
({ state }) => state === TransferState.Pending,
TransferState.Progress,
mockCallback
);
});
expect(mockCallback.mock.calls).toMatchObject([
[{ parentId: 'parentId', meta: { filename: 'file1.txt' } }],
[{ parentId: 'parentId', meta: { filename: 'folder1' } }],
[{ parentId: 'parentId', meta: { filename: 'folder2' } }],
[{ parentId: 'parentId', meta: { filename: 'folder3' } }],
]);
});
it('updates state to cancel for folder recursively to not hang children forever', () => {
act(() => {
hook.current.updateState(firstFolderId, TransferState.Canceled);
});
expect(hook.current.folderUploads.map(({ state, meta }) => [meta.filename, state])).toMatchObject([
['folder1', TransferState.Canceled],
['folder2', TransferState.Pending],
['folder3', TransferState.Pending],
]);
expect(hook.current.fileUploads.map(({ state, meta }) => [meta.filename, state])).toMatchObject([
['file1.txt', TransferState.Pending],
['file2.txt', TransferState.Canceled],
['file3.txt', TransferState.Canceled],
['file4.txt', TransferState.Initializing],
]);
});
it('restarts child also restarts parent folder recursively to not hang forever', () => {
act(() => {
hook.current.updateState(firstFolderId, TransferState.Canceled);
hook.current.updateState(secondFileId, TransferState.Initializing);
});
expect(hook.current.folderUploads.map(({ state, meta }) => [meta.filename, state])).toMatchObject([
['folder1', TransferState.Pending],
['folder2', TransferState.Pending],
['folder3', TransferState.Pending],
]);
expect(hook.current.fileUploads.map(({ state, meta }) => [meta.filename, state])).toMatchObject([
['file1.txt', TransferState.Pending],
['file2.txt', TransferState.Initializing],
['file3.txt', TransferState.Canceled],
['file4.txt', TransferState.Initializing],
]);
});
});
|
3,194 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/media/getMediaInfo.test.ts | import { getMediaInfo } from './getMediaInfo';
describe('makeThumbnail', () => {
it('does nothing when mime type is not supported', async () => {
await expect(getMediaInfo(new Promise((resolve) => resolve('png')), new Blob(), true)).resolves.toEqual(
undefined
);
await expect(
getMediaInfo(new Promise((resolve) => resolve('image/jpeeg')), new Blob(), false)
).resolves.toEqual(undefined);
});
});
|
3,196 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/media/image.test.ts | import { SupportedMimeTypes, THUMBNAIL_MAX_SIZE } from '@proton/shared/lib/drive/constants';
import { scaleImageFile } from './image';
import { ThumbnailType } from './interface';
describe('scaleImageFile', () => {
beforeEach(() => {
global.URL.createObjectURL = jest.fn(() => 'url');
// Image under test does not handle events.
// @ts-ignore
global.Image = class {
addEventListener(type: string, listener: (value?: any) => void) {
if (type === 'load') {
listener();
}
}
};
// @ts-ignore
global.HTMLCanvasElement.prototype.getContext = jest.fn(() => {
return {
drawImage: jest.fn(),
fillRect: jest.fn(),
};
});
global.HTMLCanvasElement.prototype.toBlob = jest.fn((callback) => {
callback(new Blob(['abc']));
});
});
it('returns the scaled image', async () => {
await expect(scaleImageFile({ file: new Blob(), mimeType: SupportedMimeTypes.jpg })).resolves.toEqual({
width: undefined,
height: undefined,
thumbnails: [
{
thumbnailData: new Uint8Array([97, 98, 99]),
thumbnailType: ThumbnailType.PREVIEW,
},
],
});
});
it('returns multiple scaled image', async () => {
await expect(
scaleImageFile({
file: new Blob(),
mimeType: SupportedMimeTypes.jpg,
thumbnailTypes: [ThumbnailType.PREVIEW, ThumbnailType.HD_PREVIEW],
})
).resolves.toEqual({
width: undefined,
height: undefined,
thumbnails: [
{
thumbnailData: new Uint8Array([97, 98, 99]),
thumbnailType: ThumbnailType.PREVIEW,
},
{
thumbnailData: new Uint8Array([97, 98, 99]),
thumbnailType: ThumbnailType.HD_PREVIEW,
},
],
});
});
it('fails due to problem to load the image', async () => {
// @ts-ignore
global.Image = class {
addEventListener(type: string, listener: (value?: any) => void) {
if (type === 'error') {
listener(new Error('Failed to load image'));
}
}
};
await expect(scaleImageFile({ file: new Blob(), mimeType: SupportedMimeTypes.jpg })).rejects.toEqual(
new Error('Image cannot be loaded')
);
});
it('fails due to no small enough thumbnail', async () => {
global.HTMLCanvasElement.prototype.toBlob = jest.fn((callback) => {
callback(new Blob(['x'.repeat(THUMBNAIL_MAX_SIZE + 1)]));
});
await expect(scaleImageFile({ file: new Blob(), mimeType: SupportedMimeTypes.jpg })).rejects.toEqual(
new Error('Cannot create small enough thumbnail')
);
});
it('fails due to no blob', async () => {
global.HTMLCanvasElement.prototype.toBlob = jest.fn((callback) => {
callback(null);
});
await expect(scaleImageFile({ file: new Blob(), mimeType: SupportedMimeTypes.jpg })).rejects.toEqual(
new Error('Blob not available')
);
});
});
|
3,201 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/media/util.test.ts | import { THUMBNAIL_MAX_SIDE } from '@proton/shared/lib/drive/constants';
import { calculateThumbnailSize } from './util';
describe('calculateThumbnailSize', () => {
it('keeps smaller images as is', () => {
expect(calculateThumbnailSize({ width: 200, height: 200 })).toEqual([200, 200]);
});
it('resize bigger images', () => {
expect(calculateThumbnailSize({ width: 5120, height: 20 })).toEqual([512, 2]);
expect(calculateThumbnailSize({ width: 5120, height: 200 })).toEqual([512, 20]);
expect(calculateThumbnailSize({ width: 5120, height: 2000 })).toEqual([512, 200]);
expect(calculateThumbnailSize({ width: 20, height: 5120 })).toEqual([2, 512]);
expect(calculateThumbnailSize({ width: 200, height: 5120 })).toEqual([20, 512]);
expect(calculateThumbnailSize({ width: 2000, height: 5120 })).toEqual([200, 512]);
expect(calculateThumbnailSize({ width: 5120, height: 5120 })).toEqual([512, 512]);
});
it('always returns integer', () => {
expect(calculateThumbnailSize({ width: 2000, height: 123 })).toEqual([512, 32]);
expect(calculateThumbnailSize({ width: 123, height: 2000 })).toEqual([32, 512]);
});
it('never go over max side length', () => {
const tooLong = THUMBNAIL_MAX_SIDE + 1.6;
expect(
calculateThumbnailSize({
width: tooLong,
height: tooLong,
})
).toEqual([THUMBNAIL_MAX_SIDE, THUMBNAIL_MAX_SIDE]);
const notThatLong = THUMBNAIL_MAX_SIDE - 1.6;
expect(
calculateThumbnailSize({
width: notThatLong,
height: notThatLong,
})
).toEqual([THUMBNAIL_MAX_SIDE - 1, THUMBNAIL_MAX_SIDE - 1]);
});
it('never returns zero even for extreme aspect ratio', () => {
expect(calculateThumbnailSize({ width: 5120, height: 1 })).toEqual([512, 1]);
expect(calculateThumbnailSize({ width: 1, height: 5120 })).toEqual([1, 512]);
});
});
|
3,206 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/worker/buffer.test.ts | import noop from '@proton/utils/noop';
import { MAX_ENCRYPTED_BLOCKS, MAX_UPLOADING_BLOCKS, MAX_UPLOAD_JOBS } from '../constants';
import { EncryptedBlock } from '../interface';
import { ThumbnailType } from '../media';
import UploadWorkerBuffer from './buffer';
import {
createBlock,
createLink,
createThumbnailBlock,
createThumbnailUploadingBlock,
createUploadingBlock,
waitFor,
} from './testHelpers';
function mockGenerator(start: number, end: number) {
let position = 0;
async function* generator(): AsyncGenerator<EncryptedBlock> {
for (let idx = start; idx <= end; idx++) {
position = idx;
yield createBlock(idx);
}
}
const waitForPosition = (expectedPosition: number) => {
return waitFor(() => position === expectedPosition);
};
return {
generator,
waitForPosition,
};
}
describe('upload worker buffer', () => {
const mockRequestBlockCreation = jest.fn();
let buffer: UploadWorkerBuffer;
beforeEach(() => {
mockRequestBlockCreation.mockClear();
buffer = new UploadWorkerBuffer();
});
afterEach(() => {
// Set everything to simulated finished job to stop all the running promises.
buffer.requestingBlockLinks = false;
buffer.encryptionFinished = true;
buffer.uploadingFinished = true;
buffer.encryptedBlocks.clear();
buffer.thumbnailsEncryptedBlocks.clear();
// To stop wait in generateUploadingBlocks.
buffer.uploadingBlocks = [createUploadingBlock(1)];
});
it('keeps encrypted buffer filled', async () => {
const expectedKeys = [];
for (let idx = 0; idx < MAX_ENCRYPTED_BLOCKS; idx++) {
buffer.encryptedBlocks.set(idx, createBlock(idx));
expectedKeys.push(idx);
}
const { generator, waitForPosition } = mockGenerator(1000, 1002);
buffer.feedEncryptedBlocks(generator()).finally(noop);
await waitForPosition(1000);
buffer.encryptedBlocks.delete(0);
await waitForPosition(1001);
buffer.encryptedBlocks.delete(1);
await waitForPosition(1002);
expectedKeys.shift();
expectedKeys.shift();
expectedKeys.push(1000);
expectedKeys.push(1001);
await expect(Array.from(buffer.encryptedBlocks.keys())).toMatchObject(expectedKeys);
});
it('reads next encrypted block if both encrypted and upload buffer is not full', async () => {
const expectedKeys = [];
for (let idx = 0; idx < MAX_ENCRYPTED_BLOCKS - 2; idx++) {
buffer.encryptedBlocks.set(idx, createBlock(idx));
expectedKeys.push(idx);
}
for (let idx = 0; idx < MAX_UPLOADING_BLOCKS; idx++) {
buffer.uploadingBlocks.push(createUploadingBlock(idx));
}
const { generator, waitForPosition } = mockGenerator(1000, 1005);
buffer.feedEncryptedBlocks(generator()).finally(noop);
await waitForPosition(1000);
buffer.uploadingBlocks.shift();
await waitForPosition(1002);
expectedKeys.push(1000);
expectedKeys.push(1001);
await expect(Array.from(buffer.encryptedBlocks.keys())).toMatchObject(expectedKeys);
});
it('creates block links with the first file block', () => {
buffer.encryptedBlocks.set(1, createBlock(1));
buffer.runBlockLinksCreation(mockRequestBlockCreation);
expect(mockRequestBlockCreation.mock.calls).toMatchObject([[[createBlock(1)], []]]);
});
it('creates thumbnails and block links', async () => {
buffer.thumbnailsEncryptedBlocks.set(0, createThumbnailBlock(0, ThumbnailType.PREVIEW));
buffer.thumbnailsEncryptedBlocks.set(1, createThumbnailBlock(1, ThumbnailType.HD_PREVIEW));
buffer.encryptedBlocks.set(1, createBlock(1));
buffer.encryptedBlocks.set(2, createBlock(2));
buffer.runBlockLinksCreation(mockRequestBlockCreation);
expect(mockRequestBlockCreation.mock.calls).toMatchObject([
[
[createBlock(1), createBlock(2)],
[createThumbnailBlock(0, ThumbnailType.PREVIEW), createThumbnailBlock(1, ThumbnailType.HD_PREVIEW)],
],
]);
});
it('creates block links when upload buffer is low', async () => {
for (let idx = 0; idx < MAX_UPLOAD_JOBS; idx++) {
buffer.uploadingBlocks.push(createUploadingBlock(idx));
}
buffer.runBlockLinksCreation(mockRequestBlockCreation);
expect(mockRequestBlockCreation.mock.calls.length).toBe(0);
});
it('creates block links when encrypted buffer is full', async () => {
const expectedBlocks = [];
for (let idx = 1; idx <= MAX_ENCRYPTED_BLOCKS; idx++) {
buffer.encryptedBlocks.set(idx, createBlock(idx));
expectedBlocks.push(createBlock(idx));
}
for (let idx = 0; idx < MAX_UPLOAD_JOBS; idx++) {
buffer.uploadingBlocks.push(createUploadingBlock(idx));
}
buffer.runBlockLinksCreation(mockRequestBlockCreation);
expect(mockRequestBlockCreation.mock.calls).toMatchObject([[expectedBlocks, []]]);
});
it('moves block from encrypted buffer to uploading buffer once link is created', async () => {
buffer.thumbnailsEncryptedBlocks.set(0, createThumbnailBlock(0, ThumbnailType.PREVIEW));
buffer.thumbnailsEncryptedBlocks.set(1, createThumbnailBlock(1, ThumbnailType.HD_PREVIEW));
buffer.encryptedBlocks.set(1, createBlock(1));
buffer.encryptedBlocks.set(2, createBlock(2));
buffer.setThumbnailBlockLinks([createLink(0)]);
buffer.setFileBlockLinks([createLink(1)]);
buffer.requestingBlockLinks = false;
expect(Array.from(buffer.thumbnailsEncryptedBlocks.keys())).toMatchObject([1]);
expect(Array.from(buffer.encryptedBlocks.keys())).toMatchObject([2]);
expect(buffer.uploadingBlocks).toMatchObject([
createThumbnailUploadingBlock(0, buffer.uploadingBlocks[0].isTokenExpired, ThumbnailType.PREVIEW),
createUploadingBlock(1, buffer.uploadingBlocks[1].isTokenExpired),
]);
});
it('stops generating uploading blocks when buffers are emtpy and both encryption and uploading finished', async () => {
buffer.encryptionFinished = true;
buffer.uploadingFinished = true;
const { done } = await buffer.generateUploadingBlocks().next();
expect(done).toBe(true);
});
it('does not stop generating uploading blocks when encrypted blocks are present', async () => {
buffer.encryptionFinished = true;
buffer.uploadingFinished = true;
buffer.encryptedBlocks.set(1, createBlock(1));
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('OK'), 100);
buffer
.generateUploadingBlocks()
.next()
.then(() => reject(new Error('Generator continued/finished')))
.catch((err) => reject(err));
});
await expect(promise).resolves.toBe('OK');
});
it('finishes uploading block and adds it to the hashes and tokens', async () => {
const block = createUploadingBlock(1);
buffer.uploadingBlocks.push(block);
const {
value: { finish },
} = await buffer.generateUploadingBlocks().next();
expect(buffer.blockHashes).toMatchObject([]);
finish();
expect(buffer.blockHashes).toMatchObject([{ index: 1, hash: block.block.hash }]);
});
it('retries uploading block by adding it back to encrypted buffer', async () => {
const block = createUploadingBlock(1);
buffer.uploadingBlocks.push(block);
const {
value: { onTokenExpiration },
} = await buffer.generateUploadingBlocks().next();
expect(buffer.encryptedBlocks).toMatchObject(new Map());
onTokenExpiration();
expect(buffer.encryptedBlocks).toMatchObject(new Map([[1, block.block]]));
expect(buffer.blockHashes).toMatchObject([]);
});
it('waits for blocks to be processed', async () => {
buffer.encryptionFinished = true;
buffer.uploadingBlocks.push(createUploadingBlock(1));
const generator = buffer.generateUploadingBlocks();
const {
value: { finish },
} = await generator.next();
// Ask for next item to make the generator run the check if all blocks
// are finished. It should not be finished until all blocks are done
// and finish callback for each of them was called.
const finishedGenerator = generator.next();
expect(buffer.uploadingFinished).toBeFalsy();
finish();
// Await just to be sure it was finished. If there is nothing in the
// queue, it runs a loop until anything appears in the queue or all
// blocks are completed (finish was called).
await finishedGenerator;
expect(buffer.uploadingFinished).toBeTruthy();
});
it('gets hash in proper order', () => {
buffer.blockHashes = [3, 2, 4, 1].map((index) => ({ index, hash: new Uint8Array([index]) }));
expect(buffer.hash).toMatchObject(new Uint8Array([1, 2, 3, 4]));
});
});
|
3,208 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/worker/encryption.test.ts | import { CryptoProxy } from '@proton/crypto';
import { FILE_CHUNK_SIZE } from '@proton/shared/lib/drive/constants';
import noop from '@proton/utils/noop';
import {
generatePrivateKey,
generateSessionKey,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from '../../../utils/test/crypto';
import { asyncGeneratorToArray } from '../../../utils/test/generator';
import { EncryptedBlock, ThumbnailEncryptedBlock } from '../interface';
import { ThumbnailInfo, ThumbnailType } from '../media';
import { generateEncryptedBlocks, generateThumbnailEncryptedBlocks } from './encryption';
import { Verifier } from './interface';
import { createVerifier } from './verifier';
jest.setTimeout(20000);
describe('block generator', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
const setupPromise = async () => {
const privateKey = await generatePrivateKey();
const sessionKey = await generateSessionKey();
return {
// We don't test crypto, so no need to have properly two keys.
addressPrivateKey: privateKey,
privateKey,
sessionKey,
};
};
// This is obviously not a good or complete mock implementation
// but should be sufficient for our implementation
const mockHasher: any = {
process: noop,
finish: () => ({ result: new Uint8Array([1, 2, 3, 4]) }),
};
// Mock implementation of a verifier that always succeeds
const mockVerifier: Verifier = () => {
return Promise.resolve(new Uint8Array(Array(32)));
};
it('should generate all file blocks', async () => {
const lastBlockSize = 123;
const file = new File(['x'.repeat(2 * FILE_CHUNK_SIZE + lastBlockSize)], 'foo.txt');
const { addressPrivateKey, privateKey, sessionKey } = await setupPromise();
const generator = generateEncryptedBlocks(
file,
addressPrivateKey,
privateKey,
sessionKey,
noop,
mockHasher,
mockVerifier
);
const blocks = await asyncGeneratorToArray<EncryptedBlock>(generator);
expect(blocks.length).toBe(3);
expect(blocks.map((block) => block.index)).toMatchObject([1, 2, 3]);
expect(blocks.map((block) => block.originalSize)).toMatchObject([
FILE_CHUNK_SIZE,
FILE_CHUNK_SIZE,
lastBlockSize,
]);
});
it('should generate all thumbnails blocks', async () => {
const thumbnailData: ThumbnailInfo[] = [
{
thumbnailData: new Uint8Array([1, 2, 3, 3, 2, 1]),
thumbnailType: ThumbnailType.PREVIEW,
},
{
thumbnailData: new Uint8Array([1, 2, 3, 3, 2, 1]),
thumbnailType: ThumbnailType.HD_PREVIEW,
},
];
const { addressPrivateKey, sessionKey } = await setupPromise();
const generator = generateThumbnailEncryptedBlocks(thumbnailData, addressPrivateKey, sessionKey);
const blocks = await asyncGeneratorToArray<ThumbnailEncryptedBlock>(generator);
expect(blocks.length).toBe(2);
expect(blocks.map((block) => block.index)).toMatchObject([0, 1]);
// Thumbnail has always zero original size to not mess up the progress.
expect(blocks.map((block) => block.originalSize)).toMatchObject([0, 0]);
});
it('should throw and log if there is a consistent encryption error', async () => {
const lastBlockSize = 123;
const file = new File(['x'.repeat(2 * FILE_CHUNK_SIZE + lastBlockSize)], 'foo.txt');
const { addressPrivateKey, privateKey, sessionKey } = await setupPromise();
const encryptSpy = jest.spyOn(CryptoProxy, 'encryptMessage').mockImplementation(async () => {
// Return some garbage data which will fail validation
return {
message: new Uint8Array([1, 2, 3]),
signature: new Uint8Array([1, 2, 3]),
encryptedSignature: new Uint8Array([1, 2, 3]),
};
});
const notifySentry = jest.fn();
const verifier = createVerifier({
verificationCode: new Uint8Array([1, 2, 3]),
verifierSessionKey: sessionKey,
});
const generator = generateEncryptedBlocks(
file,
addressPrivateKey,
privateKey,
sessionKey,
notifySentry,
mockHasher,
verifier
);
const blocks = asyncGeneratorToArray(generator);
await expect(blocks).rejects.toThrow();
expect(encryptSpy).toBeCalled();
expect(notifySentry).toBeCalled();
encryptSpy.mockRestore();
});
it('should retry and log if there is an encryption error once', async () => {
const lastBlockSize = 123;
const file = new File(['x'.repeat(2 * FILE_CHUNK_SIZE + lastBlockSize)], 'foo.txt');
const { addressPrivateKey, privateKey, sessionKey } = await setupPromise();
let mockCalled = false;
const encryptSpy = jest.spyOn(CryptoProxy, 'encryptMessage').mockImplementation(async () => {
// Remove the mock after the first call
encryptSpy.mockRestore();
// Since we restore the mock, we can't use .toBeCalled()
mockCalled = true;
// Return some garbage data which will fail validation
return {
message: new Uint8Array([1, 2, 3]),
signature: new Uint8Array([1, 2, 3]),
encryptedSignature: new Uint8Array([1, 2, 3]),
};
});
const notifySentry = jest.fn();
const verifier = createVerifier({
verificationCode: new Uint8Array([1, 2, 3]),
verifierSessionKey: sessionKey,
});
const generator = generateEncryptedBlocks(
file,
addressPrivateKey,
privateKey,
sessionKey,
notifySentry,
mockHasher,
verifier
);
const blocks = await asyncGeneratorToArray<EncryptedBlock>(generator);
expect(blocks.length).toBe(3);
expect(blocks.map((block) => block.index)).toMatchObject([1, 2, 3]);
expect(blocks.map((block) => block.originalSize)).toMatchObject([
FILE_CHUNK_SIZE,
FILE_CHUNK_SIZE,
lastBlockSize,
]);
// Make sure we logged the error
expect(mockCalled).toBe(true);
expect(notifySentry).toBeCalled();
});
it('should call the hasher correctly', async () => {
const hasher: any = {
process: jest.fn(),
finish: jest.fn(() => {
return new Uint8Array([0, 0, 0, 0]);
}),
};
const lastBlockSize = 123;
const file = new File(['x'.repeat(2 * FILE_CHUNK_SIZE + lastBlockSize)], 'foo.txt');
const { addressPrivateKey, privateKey, sessionKey } = await setupPromise();
const generator = generateEncryptedBlocks(
file,
addressPrivateKey,
privateKey,
sessionKey,
noop,
hasher,
mockVerifier
);
const blocks = await asyncGeneratorToArray(generator);
expect(blocks.length).toBe(3);
// it should have processed the same amount as the blocks
expect(hasher.process).toHaveBeenCalledTimes(3);
// the finish function is called by the worker at a higher level
expect(hasher.finish).not.toHaveBeenCalled();
});
describe('verifier usage', () => {
[0, 1, 17, 6 * 1024 * 1024].forEach(async (fileSize) => {
const blockCount = Math.ceil(fileSize / FILE_CHUNK_SIZE);
it(`should call the verifier and attach ${blockCount} tokens for ${fileSize} bytes`, async () => {
const { addressPrivateKey, privateKey, sessionKey } = await setupPromise();
const file = new File(['a'.repeat(fileSize)], 'foo.txt');
const verifier = jest.fn(mockVerifier);
const generator = generateEncryptedBlocks(
file,
addressPrivateKey,
privateKey,
sessionKey,
noop,
mockHasher,
verifier
);
const blocks = await asyncGeneratorToArray(generator);
expect(blocks.length).toBe(blockCount);
expect(verifier).toHaveBeenCalledTimes(blockCount);
blocks.forEach((block) => {
if (!('verificationToken' in block)) {
fail('Verification token should be in generated block data');
}
expect(block.verificationToken).toStrictEqual(new Uint8Array(new Array(32)));
});
});
});
it(`should throw if the verifier throws and notify sentry`, async () => {
const { addressPrivateKey, privateKey, sessionKey } = await setupPromise();
const file = new File(['a'.repeat(32)], 'foo.txt');
const verifier = jest.fn(() => Promise.reject(new Error('oh no')));
const notifySentry = jest.fn();
const generator = generateEncryptedBlocks(
file,
addressPrivateKey,
privateKey,
sessionKey,
notifySentry,
mockHasher,
verifier
);
const blocks = asyncGeneratorToArray(generator);
await expect(blocks).rejects.toThrow();
expect(notifySentry).toBeCalled();
});
});
});
|
3,213 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/worker/upload.test.ts | import { MAX_RETRIES_BEFORE_FAIL } from '../constants';
import { UploadingBlockControl } from './interface';
import { Pauser } from './pauser';
import { createUploadingBlockControl } from './testHelpers';
import startUploadJobs, { XHRError } from './upload';
describe('upload jobs', () => {
const mockUploadBlockFinishCallback = jest.fn();
const mockUploadBlockExpiredCallback = jest.fn();
const mockProgressCallback = jest.fn();
const mockNetworkErrorCallback = jest.fn();
let pauser: Pauser;
beforeAll(() => {
jest.spyOn(global.console, 'warn').mockReturnValue();
});
beforeEach(() => {
jest.clearAllMocks();
pauser = new Pauser();
});
it('calls upload for each block', async () => {
const blocksCount = 10;
const expectedLinks: string[] = [];
async function* generator(): AsyncGenerator<UploadingBlockControl> {
for (let idx = 0; idx < blocksCount; idx++) {
const block = createUploadingBlockControl(
idx,
mockUploadBlockFinishCallback,
mockUploadBlockExpiredCallback
);
expectedLinks.push(block.uploadLink);
yield block;
}
}
const mockUploadBlockCallback = jest.fn();
await startUploadJobs(
pauser,
generator(),
mockProgressCallback,
mockNetworkErrorCallback,
mockUploadBlockCallback
);
expect(mockUploadBlockCallback).toBeCalledTimes(blocksCount);
expect(mockUploadBlockCallback.mock.calls.map((call) => call[0])).toMatchObject(expectedLinks);
expect(mockUploadBlockFinishCallback).toBeCalledTimes(blocksCount);
expect(mockUploadBlockExpiredCallback).not.toBeCalled();
});
it('retries the same block when paused', async () => {
async function* generator(): AsyncGenerator<UploadingBlockControl> {
yield createUploadingBlockControl(1, mockUploadBlockFinishCallback, mockUploadBlockExpiredCallback);
}
const mockUploadBlockCallback = jest.fn(() => {
if (mockUploadBlockCallback.mock.calls.length === 1) {
pauser.pause();
setTimeout(() => pauser.resume(), 500);
throw new Error('Upload aborted');
}
return Promise.resolve();
});
await startUploadJobs(
pauser,
generator(),
mockProgressCallback,
mockNetworkErrorCallback,
mockUploadBlockCallback
);
expect(pauser.isPaused).toBe(false);
expect(mockUploadBlockCallback).toBeCalledTimes(2); // First call and after resume.
// @ts-ignore
expect(mockUploadBlockCallback.mock.calls.map((call) => call[0])).toMatchObject(['link1', 'link1']);
expect(mockUploadBlockFinishCallback).toBeCalledTimes(1); // Only one generated block.
expect(mockUploadBlockExpiredCallback).not.toBeCalled();
});
it('retries the same block number times before giving up when error happens', async () => {
async function* generator(): AsyncGenerator<UploadingBlockControl> {
yield createUploadingBlockControl(1, mockUploadBlockFinishCallback, mockUploadBlockExpiredCallback);
}
const err = new Error('Some not-network error');
const mockUploadBlockCallback = jest.fn(() => {
throw err;
});
const promise = startUploadJobs(
pauser,
generator(),
mockProgressCallback,
mockNetworkErrorCallback,
mockUploadBlockCallback
);
await expect(promise).rejects.toBe(err);
expect(mockUploadBlockCallback).toBeCalledTimes(1 + MAX_RETRIES_BEFORE_FAIL); // First call + retries.
expect(mockUploadBlockFinishCallback).not.toBeCalled();
expect(mockUploadBlockExpiredCallback).not.toBeCalled();
});
it('automatically retries after network error once', async () => {
async function* generator(): AsyncGenerator<UploadingBlockControl> {
yield createUploadingBlockControl(1, mockUploadBlockFinishCallback, mockUploadBlockExpiredCallback);
}
const mockUploadBlockCallback = jest.fn(() => {
if (mockUploadBlockCallback.mock.calls.length === 1) {
throw new Error('network error');
}
return Promise.resolve();
});
mockNetworkErrorCallback.mockImplementation(() => {
expect(pauser.isPaused).toBeTruthy();
});
await startUploadJobs(
pauser,
generator(),
mockProgressCallback,
mockNetworkErrorCallback,
mockUploadBlockCallback
);
// First call + automatic retry.
expect(mockUploadBlockCallback).toBeCalledTimes(2);
expect(mockNetworkErrorCallback).toBeCalledTimes(0);
expect(mockUploadBlockFinishCallback).toBeCalledTimes(1); // Only one generated block.
expect(mockUploadBlockExpiredCallback).not.toBeCalled();
});
it('pauses and notifies about network error', async () => {
async function* generator(): AsyncGenerator<UploadingBlockControl> {
yield createUploadingBlockControl(1, mockUploadBlockFinishCallback, mockUploadBlockExpiredCallback);
}
const mockUploadBlockCallback = jest.fn(() => {
// Fail twice as it automatically retries after first failure.
if (mockUploadBlockCallback.mock.calls.length <= 2) {
throw new Error('network error');
}
return Promise.resolve();
});
mockNetworkErrorCallback.mockImplementation(() => {
expect(pauser.isPaused).toBeTruthy();
pauser.resume();
});
await startUploadJobs(
pauser,
generator(),
mockProgressCallback,
mockNetworkErrorCallback,
mockUploadBlockCallback
);
// First call + automatic retry + after resume.
expect(mockUploadBlockCallback).toBeCalledTimes(3);
expect(mockNetworkErrorCallback).toBeCalledTimes(1);
expect(mockNetworkErrorCallback).toBeCalledWith('network error');
expect(mockUploadBlockFinishCallback).toBeCalledTimes(1); // Only one generated block.
expect(mockUploadBlockExpiredCallback).not.toBeCalled();
});
it('calls retry when token expires', async () => {
async function* generator(): AsyncGenerator<UploadingBlockControl> {
yield createUploadingBlockControl(1, mockUploadBlockFinishCallback, mockUploadBlockExpiredCallback);
}
const err = new XHRError('Token expired', 2501, 404);
const mockUploadBlockCallback = jest.fn(() => {
throw err;
});
await startUploadJobs(
pauser,
generator(),
mockProgressCallback,
mockNetworkErrorCallback,
mockUploadBlockCallback
);
expect(mockUploadBlockCallback).toBeCalledTimes(1);
expect(mockUploadBlockFinishCallback).not.toBeCalled();
expect(mockUploadBlockExpiredCallback).toBeCalledTimes(1);
});
it('waits specified time when rate limited', async () => {
async function* generator(): AsyncGenerator<UploadingBlockControl> {
yield createUploadingBlockControl(1, mockUploadBlockFinishCallback, mockUploadBlockExpiredCallback);
}
const err = new XHRError('Too many requests', 0, 429, {
headers: new Headers({ 'retry-after': '1' }),
} as Response);
const mockUploadBlockCallback = jest.fn(() => {
// Fail only once.
if (mockUploadBlockCallback.mock.calls.length === 1) {
throw err;
}
return Promise.resolve();
});
await startUploadJobs(
pauser,
generator(),
mockProgressCallback,
mockNetworkErrorCallback,
mockUploadBlockCallback
);
expect(mockUploadBlockCallback).toBeCalledTimes(2);
expect(mockUploadBlockFinishCallback).toBeCalled();
expect(mockUploadBlockExpiredCallback).not.toBeCalled();
});
});
|
3,215 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_uploads/worker/verifier.test.ts | import { CryptoProxy } from '@proton/crypto';
import { generateSessionKey, releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../utils/test/crypto';
import { createVerifier } from './verifier';
jest.setTimeout(20000);
describe('verifier implementation', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should throw if the block cannot be decrypted', async () => {
const sessionKey = await generateSessionKey();
const verify = createVerifier({ verificationCode: new Uint8Array(Array(32)), verifierSessionKey: sessionKey });
const result = verify(new Uint8Array(Array(32)));
await expect(result).rejects.toThrow();
});
describe('verification token', () => {
[
{
name: 'should construct the verification token correctly',
encryptedData: new Uint8Array([
6, 28, 236, 157, 20, 85, 195, 133, 7, 99, 11, 145, 123, 207, 27, 252, 80, 191, 107, 114, 195, 229,
120, 115, 8, 200, 34, 214, 178, 149, 78, 147,
]),
verificationCode: new Uint8Array([
140, 211, 158, 220, 71, 191, 71, 163, 245, 33, 192, 146, 154, 221, 196, 250, 94, 23, 56, 28, 235,
121, 28, 103, 229, 119, 95, 39, 157, 119, 4, 231,
]),
verificationToken: new Uint8Array([
138, 207, 114, 65, 83, 234, 132, 38, 242, 66, 203, 3, 225, 18, 223, 6, 14, 168, 83, 110, 40, 156,
100, 20, 237, 191, 125, 241, 47, 226, 74, 116,
]),
},
{
name: 'should ignore extra bytes in the encrypted block when constructing the token',
encryptedData: new Uint8Array([
6, 28, 236, 157, 20, 85, 195, 133, 7, 99, 11, 145, 123, 207, 27, 252, 80, 191, 107, 114, 195, 229,
120, 115, 8, 200, 34, 214, 178, 149, 78, 147, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
]),
verificationCode: new Uint8Array([
140, 211, 158, 220, 71, 191, 71, 163, 245, 33, 192, 146, 154, 221, 196, 250, 94, 23, 56, 28, 235,
121, 28, 103, 229, 119, 95, 39, 157, 119, 4, 231,
]),
verificationToken: new Uint8Array([
138, 207, 114, 65, 83, 234, 132, 38, 242, 66, 203, 3, 225, 18, 223, 6, 14, 168, 83, 110, 40, 156,
100, 20, 237, 191, 125, 241, 47, 226, 74, 116,
]),
},
{
name: 'should pad the data with 0 if the encrypted block is shorter than the verification code',
encryptedData: new Uint8Array([6, 28, 236, 157]),
verificationCode: new Uint8Array([
140, 211, 158, 220, 71, 191, 71, 163, 245, 33, 192, 146, 154, 221, 196, 250, 94, 23, 56, 28, 235,
121, 28, 103, 229, 119, 95, 39, 157, 119, 4, 231,
]),
verificationToken: new Uint8Array([
138, 207, 114, 65, 71, 191, 71, 163, 245, 33, 192, 146, 154, 221, 196, 250, 94, 23, 56, 28, 235,
121, 28, 103, 229, 119, 95, 39, 157, 119, 4, 231,
]),
},
].forEach(({ name, encryptedData, verificationCode, verificationToken }) => {
it(name, async () => {
const sessionKey = await generateSessionKey();
const verify = createVerifier({
verificationCode,
verifierSessionKey: sessionKey,
});
const decryptSpy = jest
.spyOn(CryptoProxy, 'decryptMessage')
.mockImplementation((async () => Promise.resolve()) as any);
const result = verify(encryptedData);
await expect(result).resolves.toStrictEqual(verificationToken);
expect(decryptSpy).toHaveBeenCalled();
});
});
});
});
|
3,220 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_utils/useDebouncedFunction.test.tsx | import * as React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { CacheProvider } from '@proton/components';
import createCache from '@proton/shared/lib/helpers/cache';
import useDebouncedFunction from './useDebouncedFunction';
describe('useDebouncedFunction', () => {
let debouncedFunction: ReturnType<typeof useDebouncedFunction>;
const mockCallback = jest.fn();
beforeEach(() => {
jest.resetAllMocks();
mockCallback.mockImplementation(() => Promise.resolve({ test: 'test' }));
const cache = createCache();
const { result } = renderHook(() => useDebouncedFunction(), {
wrapper: ({ children }: { children?: React.ReactNode }) => (
<CacheProvider cache={cache}>{children}</CacheProvider>
),
});
debouncedFunction = result.current;
});
it('should initially call debounced function instantly', async () => {
await debouncedFunction(mockCallback, { test: 'test' });
expect(mockCallback).toHaveBeenCalledTimes(1);
});
it('should return initial call result if called while pending', async () => {
const call1 = debouncedFunction(mockCallback, { test: 'test' });
const call2 = debouncedFunction(mockCallback, { test: 'test' });
const result1 = await call1;
const result2 = await call2;
expect(mockCallback).toHaveBeenCalledTimes(1);
expect(result2).toBe(result1);
});
it('should return new call result if called after initial call is completed', async () => {
const call1 = debouncedFunction(mockCallback, { test: 'test' });
const result1 = await call1;
const call2 = debouncedFunction(mockCallback, { test: 'test' });
const result2 = await call2;
expect(mockCallback).toHaveBeenCalledTimes(2);
expect(result2).not.toBe(result1);
});
it('should abort only when all signals are aborted', async () => {
const ac1 = new AbortController();
const call1 = debouncedFunction(mockCallback, { test: 'test' }, ac1.signal);
const ac2 = new AbortController();
const call2 = debouncedFunction(mockCallback, { test: 'test' }, ac2.signal);
ac1.abort();
// Wait first for the call not aborted so the request finishes.
await expect(call2).resolves.toMatchObject({ test: 'test' });
await expect(call1).rejects.toThrowError('Aborted');
});
it('should abort when all signals are aborted', async () => {
const ac1 = new AbortController();
const call1 = debouncedFunction(mockCallback, { test: 'test' }, ac1.signal);
const ac2 = new AbortController();
const call2 = debouncedFunction(mockCallback, { test: 'test' }, ac2.signal);
ac1.abort();
ac2.abort();
await expect(call1).rejects.toThrowError('Aborted');
await expect(call2).rejects.toThrowError('Aborted');
});
it('should return original error', async () => {
const mock = jest.fn();
mock.mockImplementation(async () => Promise.reject(new Error('failed')));
const ac1 = new AbortController();
const call1 = debouncedFunction(mock, { test: 'test' }, ac1.signal);
const ac2 = new AbortController();
const call2 = debouncedFunction(mock, { test: 'test' }, ac2.signal);
await expect(call1).rejects.toThrowError('failed');
await expect(call2).rejects.toThrowError('failed');
});
it('should return original error when aborted', async () => {
const mock = jest.fn();
mock.mockImplementation(async () => Promise.reject(new Error('failed')));
const ac1 = new AbortController();
const call1 = debouncedFunction(mock, { test: 'test' }, ac1.signal);
ac1.abort();
await expect(call1).rejects.toThrowError('failed');
});
});
|
3,242 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_views | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_views/utils/objectId.test.ts | import { getArrayIdNoMatterTheOrder, getObjectId } from './objectId';
describe('objectsId', () => {
const object1 = { a: 1 };
const object2 = { a: 1 };
const object3 = { a: 1 };
const array12 = [object1, object2];
const array13 = [object1, object3];
const array21 = [object2, object1];
it('getObjectId should return different ID for different object', () => {
const id1 = getObjectId(object1);
const id2 = getObjectId(object2);
expect(id1).not.toBe(id2);
});
it('getObjectId should return the same ID for the same object', () => {
const id1 = getObjectId(object1);
const id2 = getObjectId(object1);
expect(id1).toBe(id2);
});
it('getArrayIdNoMatterTheOrder should return different ID for different array containing different elements', () => {
const id1 = getArrayIdNoMatterTheOrder(array12);
const id2 = getArrayIdNoMatterTheOrder(array13);
expect(id1).not.toBe(id2);
});
it('getArrayIdNoMatterTheOrder should return the same ID for different array containing the same elements no matter the order', () => {
const id1 = getArrayIdNoMatterTheOrder(array12);
const id2 = getArrayIdNoMatterTheOrder(array21);
expect(id1).toBe(id2);
});
});
|
3,251 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/store/_volumes/useVolumesState.test.tsx | import { RenderResult, renderHook } from '@testing-library/react-hooks';
import { useVolumesStateProvider } from './useVolumesState';
const VOLUME_ID_1 = 'volumeId-1';
const VOLUME_ID_2 = 'volumeId-2';
describe('useDriveEventManager', () => {
let hook: RenderResult<ReturnType<typeof useVolumesStateProvider>>;
const renderTestHook = () => {
const { result } = renderHook(() => useVolumesStateProvider());
return result;
};
beforeEach(() => {
hook = renderTestHook();
});
afterEach(() => {
hook.current.clear();
});
it('sets share ids by volumeId', async () => {
const shareIds = ['1', '2', '3'];
const idsInitial = hook.current.getVolumeShareIds(VOLUME_ID_1);
expect(idsInitial).toEqual([]);
hook.current.setVolumeShareIds(VOLUME_ID_1, shareIds);
hook.current.setVolumeShareIds(VOLUME_ID_2, ['2']);
expect(hook.current.getVolumeShareIds(VOLUME_ID_1)).toEqual(shareIds);
expect(hook.current.getVolumeShareIds(VOLUME_ID_2)).toEqual(['2']);
});
it('finds volume id using share id', async () => {
hook.current.setVolumeShareIds(VOLUME_ID_1, ['1']);
hook.current.setVolumeShareIds(VOLUME_ID_2, ['2', '3']);
expect(hook.current.findVolumeId('1')).toBe(VOLUME_ID_1);
expect(hook.current.findVolumeId('2')).toBe(VOLUME_ID_2);
expect(hook.current.findVolumeId('5')).toBe(undefined);
});
});
|
3,253 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/utils/appPlatforms.test.ts | import { fetchDesktopVersion } from '@proton/shared/lib/apps/desktopVersions';
import { DESKTOP_PLATFORMS } from '@proton/shared/lib/constants';
import { isMac, isWindows } from '@proton/shared/lib/helpers/browser';
import { appPlatforms, fetchDesktopDownloads } from './appPlatforms';
jest.mock('@proton/shared/lib/apps/desktopVersions');
const mockFetchDesktopVersion = jest.mocked(fetchDesktopVersion);
jest.mock('@proton/shared/lib/helpers/browser');
const mockIsWindows = jest.mocked(isWindows);
const mockIsMac = jest.mocked(isMac);
const originalConsoleWarn = console.warn;
const mockConsoleWarn = jest.fn();
describe('appPlatforms', () => {
beforeEach(() => {
jest.resetAllMocks();
// Some default values for mocks
mockIsWindows.mockReturnValue(false);
mockIsMac.mockReturnValue(false);
});
const checkOrder = async (order: DESKTOP_PLATFORMS[]) => {
await jest.isolateModulesAsync(async () => {
const { appPlatforms } = await import('./appPlatforms');
expect(appPlatforms.length === order.length);
appPlatforms.forEach(({ platform }, i) => {
expect(platform).toBe(order[i]);
});
});
};
it('should not change order if no platform is preferred', async () => {
await checkOrder([DESKTOP_PLATFORMS.WINDOWS, DESKTOP_PLATFORMS.MACOS]);
});
it('should order by preferred platform', async () => {
mockIsMac.mockReturnValue(true);
await checkOrder([DESKTOP_PLATFORMS.MACOS, DESKTOP_PLATFORMS.WINDOWS]);
});
});
describe('fetchDesktopDownloads', () => {
beforeEach(() => {
jest.resetAllMocks();
console.warn = mockConsoleWarn;
// Default values
mockFetchDesktopVersion.mockResolvedValue({ url: 'url', version: 'version' });
});
afterEach(() => {
console.warn = originalConsoleWarn;
});
it('should return a map of platforms to url', async () => {
const result = await fetchDesktopDownloads();
appPlatforms.forEach(({ platform }) => {
expect(result).toHaveProperty(platform);
});
});
it('should return empty object on failure', async () => {
mockFetchDesktopVersion.mockRejectedValue(new Error('oh no'));
const result = await fetchDesktopDownloads();
expect(result).toStrictEqual({});
expect(mockConsoleWarn).toHaveBeenCalledTimes(appPlatforms.length);
});
it('should not include failed calls', async () => {
mockFetchDesktopVersion.mockRejectedValueOnce(new Error('oh no'));
const result = await fetchDesktopDownloads();
appPlatforms.forEach(({ platform }, index) => {
if (index === 0) {
expect(result).not.toHaveProperty(platform);
} else {
expect(result).toHaveProperty(platform);
}
});
expect(mockConsoleWarn).toHaveBeenCalledTimes(appPlatforms.length - 1);
});
});
|
3,257 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/utils/formatters.test.ts | import { COUNT_PLACEHOLDER, formatAccessCount } from './formatters';
describe('Formatters', () => {
describe('formatAccessCount()', () => {
it('should return `...` if input value it undefined', () => {
expect(formatAccessCount(undefined)).toBe(COUNT_PLACEHOLDER);
});
it('should return the input unchanged if the input is a number', () => {
const input = 42;
expect(formatAccessCount(input)).toBe(42);
expect(formatAccessCount(input)).not.toBe(56);
});
});
});
|
3,260 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/utils/retryOnError.test.ts | import retryOnError from './retryOnError';
const errorMessage = 'STRI-I-I-I-I-I-ING';
describe('retryOnError', () => {
let throwingFunction: () => Promise<void>;
let throwingFunction2: () => Promise<void>;
beforeEach(() => {
throwingFunction = jest.fn().mockImplementation(() => {
throw new Error(errorMessage);
});
throwingFunction2 = jest.fn().mockImplementation(() => {
throw new Error(errorMessage);
});
});
it("runs main function once if there's no error", () => {
const runFunction = jest.fn();
void retryOnError({
fn: runFunction,
shouldRetryBasedOnError: () => true,
maxRetriesNumber: 1000,
})();
expect(runFunction).toBeCalledTimes(1);
});
it('retries run function n times', async () => {
const promise = retryOnError<unknown>({
fn: throwingFunction,
shouldRetryBasedOnError: () => true,
maxRetriesNumber: 1,
})();
await expect(promise).rejects.toThrow();
expect(throwingFunction).toBeCalledTimes(2);
expect(retryOnError).toThrow();
});
it('validates incoming error', async () => {
const promise = retryOnError<unknown>({
fn: throwingFunction,
shouldRetryBasedOnError: (error: unknown) => {
return (error as Error).message === errorMessage;
},
maxRetriesNumber: 1,
})();
await expect(promise).rejects.toThrow();
expect(throwingFunction).toBeCalledTimes(2);
const promise2 = retryOnError<unknown>({
fn: throwingFunction2,
shouldRetryBasedOnError: (error: unknown) => {
return (error as Error).message === 'another string';
},
maxRetriesNumber: 1,
})();
expect(throwingFunction2).toBeCalledTimes(1);
await expect(promise2).rejects.toThrow();
});
it('executes preparation function on retry', async () => {
const preparationFunction = jest.fn();
const promise = retryOnError<unknown>({
fn: throwingFunction,
shouldRetryBasedOnError: (error: unknown) => {
return (error as Error).message === errorMessage;
},
beforeRetryCallback: preparationFunction,
maxRetriesNumber: 1,
})();
expect(preparationFunction).toBeCalledTimes(1);
await expect(promise).rejects.toThrow();
});
it('returns value on successful retry attempt', async () => {
const returnValue = Symbol('returnValue');
let execCount = 0;
const runFunc = jest.fn().mockImplementation(() => {
if (execCount > 1) {
return Promise.resolve(returnValue);
}
execCount++;
throw new Error();
});
const result = await retryOnError<unknown>({
fn: runFunc,
shouldRetryBasedOnError: () => true,
maxRetriesNumber: 2,
})().catch(() => {});
expect(result).toBe(returnValue);
});
});
|
3,264 | 0 | petrpan-code/ProtonMail/WebClients/applications/drive/src/app | petrpan-code/ProtonMail/WebClients/applications/drive/src/app/utils/transfer.test.ts | import { ProgressBarStatus } from '../components/TransferManager/ProgressBar';
import { Transfer, TransferState, TransfersStats } from '../components/TransferManager/transfer';
import {
calculateProgress,
getProgressBarStatus,
isTransferActive,
isTransferCancelError,
isTransferCanceled,
isTransferDone,
isTransferError,
isTransferFailed,
isTransferFinalizing,
isTransferFinished,
isTransferInitializing,
isTransferPaused,
isTransferProgress,
isTransferRetry,
} from './transfer';
describe('trasfer utils', () => {
const allStatesList = [
TransferState.Canceled,
TransferState.Done,
TransferState.Error,
TransferState.Finalizing,
TransferState.Initializing,
TransferState.Paused,
TransferState.Pending,
TransferState.Progress,
];
describe('isTransferFinished', () => {
[TransferState.Error, TransferState.Canceled, TransferState.Done].forEach((state) => {
it(`should return true for transfer state ${state}`, () => {
expect(isTransferFinished({ state })).toBeTruthy();
});
});
allStatesList
.filter((state) => ![TransferState.Error, TransferState.Canceled, TransferState.Done].includes(state))
.forEach((state) => {
it(`should return flase for transfer state ${state}`, () => {
expect(isTransferFinished({ state })).toBeFalsy();
});
});
});
describe('isTransferActive', () => {
[TransferState.Pending, TransferState.Progress, TransferState.Initializing, TransferState.Finalizing].forEach(
(state) => {
it(`should return true for transfer state ${state}`, () => {
expect(isTransferActive({ state })).toBeTruthy();
});
}
);
allStatesList
.filter(
(state) =>
![
TransferState.Pending,
TransferState.Progress,
TransferState.Initializing,
TransferState.Finalizing,
].includes(state)
)
.forEach((state) => {
it(`should return flase for transfer state ${state}`, () => {
expect(isTransferActive({ state })).toBeFalsy();
});
});
});
describe('isTransferFailed', () => {
[TransferState.Canceled, TransferState.Error].forEach((state) => {
it(`should return true for transfer state ${state}`, () => {
expect(isTransferFailed({ state })).toBeTruthy();
});
});
allStatesList
.filter((state) => ![TransferState.Canceled, TransferState.Error].includes(state))
.forEach((state) => {
it(`should return flase for transfer state ${state}`, () => {
expect(isTransferFailed({ state })).toBeFalsy();
});
});
});
describe('isTransferDone', () => {
it(`should return true for transfer state ${TransferState.Done}`, () => {
expect(isTransferDone({ state: TransferState.Done })).toBeTruthy();
});
allStatesList
.filter((state) => state !== TransferState.Done)
.forEach((state) => {
it(`should return flase for transfer state ${state}`, () => {
expect(isTransferDone({ state })).toBeFalsy();
});
});
});
describe('isTransferError', () => {
it(`should return true for transfer state ${TransferState.Error}`, () => {
expect(isTransferError({ state: TransferState.Error })).toBeTruthy();
});
allStatesList
.filter((state) => state !== TransferState.Error)
.forEach((state) => {
it(`should return flase for transfer state ${state}`, () => {
expect(isTransferError({ state })).toBeFalsy();
});
});
});
describe('isTransferCanceled', () => {
it(`should return true for transfer state ${TransferState.Canceled}`, () => {
expect(isTransferCanceled({ state: TransferState.Canceled })).toBeTruthy();
});
allStatesList
.filter((state) => state !== TransferState.Canceled)
.forEach((state) => {
it(`should return flase for transfer state ${state}`, () => {
expect(isTransferCanceled({ state })).toBeFalsy();
});
});
});
describe('isTransferProgress', () => {
it(`should return true for transfer state ${TransferState.Progress}`, () => {
expect(isTransferProgress({ state: TransferState.Progress })).toBeTruthy();
});
allStatesList
.filter((state) => state !== TransferState.Progress)
.forEach((state) => {
it(`should return flase for transfer state ${state}`, () => {
expect(isTransferProgress({ state })).toBeFalsy();
});
});
});
describe('isTransferInitializing', () => {
it(`should return true for transfer state ${TransferState.Initializing}`, () => {
expect(isTransferInitializing({ state: TransferState.Initializing })).toBeTruthy();
});
allStatesList
.filter((state) => state !== TransferState.Initializing)
.forEach((state) => {
it(`should return flase for transfer state ${state}`, () => {
expect(isTransferInitializing({ state })).toBeFalsy();
});
});
});
describe('isTransferPaused', () => {
it(`should return true for transfer state ${TransferState.Paused}`, () => {
expect(isTransferPaused({ state: TransferState.Paused })).toBeTruthy();
});
allStatesList
.filter((state) => state !== TransferState.Paused)
.forEach((state) => {
it(`should return flase for transfer state ${state}`, () => {
expect(isTransferPaused({ state })).toBeFalsy();
});
});
});
describe('isTransferFinalizing', () => {
it(`should return true for transfer state ${TransferState.Finalizing}`, () => {
expect(isTransferFinalizing({ state: TransferState.Finalizing })).toBeTruthy();
});
allStatesList
.filter((state) => state !== TransferState.Finalizing)
.forEach((state) => {
it(`should return flase for transfer state ${state}`, () => {
expect(isTransferFinalizing({ state })).toBeFalsy();
});
});
});
describe('isTransferCancelError', () => {
['TransferCancel', 'AbortError'].forEach((name) => {
it(`should return true for error with name ${name}`, () => {
const error = {
name,
message: `${name} error accured.`,
};
expect(isTransferCancelError(error)).toBeTruthy();
});
});
['TypeError', 'SyntaxError'].forEach((name) => {
it(`should return false for error with name ${name}`, () => {
const error = {
name,
message: `${name} error accured.`,
};
expect(isTransferCancelError(error)).toBeFalsy();
});
});
});
describe('isTransferRetry', () => {
['TransferRetry'].forEach((name) => {
it(`should return true for error with name ${name}`, () => {
const error = {
name,
message: `${name} error accured.`,
};
expect(isTransferRetry(error)).toBeTruthy();
});
});
['TypeError', 'SyntaxError'].forEach((name) => {
it(`should return false for error with name ${name}`, () => {
const error = {
name,
message: `${name} error accured.`,
};
expect(isTransferRetry(error)).toBeFalsy();
});
});
});
describe('getProgressBarStatus', () => {
[
{ state: TransferState.Done, status: ProgressBarStatus.Success },
{ state: TransferState.Canceled, status: ProgressBarStatus.Disabled },
{ state: TransferState.Error, status: ProgressBarStatus.Error },
{ state: TransferState.Finalizing, status: ProgressBarStatus.Running },
{ state: TransferState.Initializing, status: ProgressBarStatus.Running },
{ state: TransferState.Paused, status: ProgressBarStatus.Running },
{ state: TransferState.Pending, status: ProgressBarStatus.Running },
{ state: TransferState.Progress, status: ProgressBarStatus.Running },
].forEach(({ state, status }) => {
it(`should return progress bar status ${status} for transfer state ${state}`, () => {
expect(getProgressBarStatus(state)).toEqual(status);
});
});
});
it(`calculateProgress should calculate progress of active trasfers`, () => {
const size1 = 734003200;
const size2 = 83404340;
const progress1 = 279297577;
const progress2 = 8340324;
const progress = Math.floor(100 * ((progress1 + progress2) / (size1 + size2 || 1)));
const stats: TransfersStats = {
'drive-transfers-5740': {
averageSpeed: 2588514,
progress: progress1,
},
'drive-transfers-7456': {
averageSpeed: 734032,
progress: progress2,
},
};
const transfers: Transfer[] = [
{
id: 'drive-transfers-5740',
meta: {
size: size1,
mimeType: 'application/octet-stream',
filename: 'Pregenerated File',
},
state: TransferState.Finalizing,
} as any,
{
id: 'drive-transfers-7456',
meta: {
size: size2,
mimeType: 'application/octet-stream',
filename: 'Pregenerated File 2',
},
state: TransferState.Progress,
} as any,
];
expect(calculateProgress(stats, transfers)).toEqual(progress);
});
});
|
3,342 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/attachment/AttachmentList.test.tsx | import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';
import { clearAll, createEmbeddedImage, createMessageImages, render } from '../../helpers/test/helper';
import AttachmentList, { AttachmentAction } from './AttachmentList';
const localID = 'localID';
const cid = 'cid';
const normalAttachment = { ID: 'ID1' } as Attachment;
const embeddedAttachment = { ID: 'ID2', Headers: { 'content-id': cid } } as Attachment;
const image = createEmbeddedImage(embeddedAttachment);
const messageImages = createMessageImages([image]);
const props = {
message: {
localID,
data: {} as Message,
messageImages,
},
primaryAction: AttachmentAction.Download,
secondaryAction: AttachmentAction.Remove,
collapsable: true,
onRemoveAttachment: jest.fn(),
onRemoveUpload: jest.fn(),
};
describe('AttachmentsList', () => {
afterEach(() => clearAll());
it('should show attachments count', async () => {
const messageImages = createMessageImages([]);
const attachments = [normalAttachment];
const { getByText, queryByText } = await render(
<AttachmentList {...props} message={{ ...props.message, messageImages }} attachments={attachments} />
);
getByText('file attached');
expect(queryByText('embedded image')).toBe(null);
});
it('should show embedded count', async () => {
const attachments = [embeddedAttachment];
const { getByText, queryByText } = await render(<AttachmentList {...props} attachments={attachments} />);
getByText('embedded image');
expect(queryByText('file attached')).toBe(null);
});
it('should show attachments count and embedded count', async () => {
const attachments = [normalAttachment, embeddedAttachment];
const { getByText } = await render(<AttachmentList {...props} attachments={attachments} />);
getByText('file attached,');
getByText('embedded image');
});
});
|
3,348 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/checklist/UsersOnboardingChecklist.test.tsx | import { fireEvent } from '@testing-library/react';
import { CHECKLIST_DISPLAY_TYPE } from '@proton/shared/lib/interfaces';
import {
ContextState,
useGetStartedChecklist,
} from 'proton-mail/containers/onboardingChecklist/provider/GetStartedChecklistProvider';
import { minimalCache, render } from 'proton-mail/helpers/test/helper';
import MailSidebar from '../sidebar/MailSidebar';
import UsersOnboardingChecklist from './UsersOnboardingChecklist';
jest.mock('../../containers/onboardingChecklist/provider/GetStartedChecklistProvider', () => ({
__esModule: true,
useGetStartedChecklist: jest.fn(),
default: ({ children }: { children: any }) => <>{children}</>,
}));
jest.mock('../../containers/onboardingChecklist/provider/GetStartedChecklistProvider');
const mockedReturn = useGetStartedChecklist as jest.MockedFunction<any>;
const labelID = 'labelID';
const props = {
labelID,
location: {} as Location,
onToggleExpand: jest.fn(),
};
describe('OnboardingChecklistWrapper', () => {
beforeEach(() => {
minimalCache();
});
it('Should reduce the checklist when pressing the "Maybe later" button', async () => {
const mockedChangeDisplay = jest.fn();
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.FULL,
items: new Set(),
changeChecklistDisplay: mockedChangeDisplay,
} as Partial<ContextState>);
const { getByText } = await render(<UsersOnboardingChecklist />, false);
const { container } = await render(<MailSidebar {...props} />, false);
const nav = container.querySelector('nav');
expect(nav?.childNodes.length).toEqual(2);
const laterButton = getByText('Maybe later');
fireEvent.click(laterButton);
expect(mockedChangeDisplay).toHaveBeenCalledWith(CHECKLIST_DISPLAY_TYPE.REDUCED);
});
it('Should hide maybe later when dismiss button', async () => {
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.FULL,
items: new Set(),
} as Partial<ContextState>);
const { queryByText } = await render(<UsersOnboardingChecklist hideDismissButton />, false);
const laterButton = queryByText('Maybe later');
expect(laterButton).toBeNull();
});
it('Should display the small text when smallVariant is enabled', async () => {
mockedReturn.mockReturnValue({
displayState: CHECKLIST_DISPLAY_TYPE.FULL,
items: new Set(),
} as Partial<ContextState>);
const { getByText } = await render(<UsersOnboardingChecklist smallVariant />, false);
getByText('Discover privacy features');
getByText('Auto-forward Gmail');
getByText('Update your logins');
getByText('Get the App');
});
});
|
3,351 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/checklist | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/checklist/modals/AccountsLoginModal.test.tsx | import { useUserSettings } from '@proton/components/hooks';
import { render } from 'proton-mail/helpers/test/render';
import AccountsLoginModal from './AccountsLoginModal';
import { getOnlineAccounts } from './OnlineAccounts';
jest.mock('@proton/components/hooks/useUserSettings');
const mockedUserSettings = useUserSettings as jest.MockedFunction<any>;
describe('AccountsLoginModal', () => {
it('Should render all services for US user', async () => {
mockedUserSettings.mockReturnValue([{ Locale: 'en_US' }]);
const { getAllByTestId } = await render(
<AccountsLoginModal open onClose={jest.fn} onExit={jest.fn} key="us" />
);
const links = getOnlineAccounts();
const allLinks = links.map((item) => item.services).flat();
expect(getAllByTestId('accounts-login-modal-service-item')?.length).toEqual(allLinks.length);
});
it('Should render part of services for non US users', async () => {
mockedUserSettings.mockReturnValue([{ Locale: 'fr_CH' }]);
const { getAllByTestId } = await render(
<AccountsLoginModal open onClose={jest.fn} onExit={jest.fn} key="non_us" />
);
const links = getOnlineAccounts();
const allLinks = links
.map((item) => item.services)
.flat()
.filter((item) => !item.usOnly);
expect(getAllByTestId('accounts-login-modal-service-item')?.length).toEqual(allLinks.length);
});
});
|
3,379 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/addresses/Addresses.test.tsx | import { MutableRefObject } from 'react';
import { fireEvent, getAllByRole, screen } from '@testing-library/react';
import { act, getByText } from '@testing-library/react';
import { pick } from '@proton/shared/lib/helpers/object';
import { Recipient } from '@proton/shared/lib/interfaces';
import { ContactEmail } from '@proton/shared/lib/interfaces/contacts';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { mergeMessages } from '../../../helpers/message/messages';
import { addApiMock, addToCache, clearAll, minimalCache, render } from '../../../helpers/test/helper';
import { MessageSendInfo } from '../../../hooks/useSendInfo';
import { composerActions } from '../../../logic/composers/composersSlice';
import { MessageState } from '../../../logic/messages/messagesTypes';
import { store } from '../../../logic/store';
import Addresses from './Addresses';
const email1 = '[email protected]';
const email2 = '[email protected]';
const email3 = '[email protected]';
const email1Name = 'email1Name';
const email2Name = 'email2Name';
const email3Name = 'email3Name';
const contact1ID = '1';
const contact2ID = '2';
const contact3ID = '3';
const recipient1: Recipient = { Address: email1, Name: email1Name, ContactID: contact1ID };
const recipient2: Recipient = { Address: email2, Name: email2Name, ContactID: contact2ID };
const recipient3: Recipient = { Address: email3, Name: email3Name, ContactID: contact3ID };
const contactEmails: ContactEmail[] = [
{
ID: contact1ID,
Email: email1,
Name: email1Name,
Type: [],
Defaults: 1,
Order: 1,
ContactID: contact1ID,
LabelIDs: [],
LastUsedTime: 1,
},
{
ID: contact2ID,
Email: email2,
Name: email2Name,
Type: [],
Defaults: 2,
Order: 2,
ContactID: contact2ID,
LabelIDs: [],
LastUsedTime: 2,
},
{
ID: contact3ID,
Email: email3,
Name: email3Name,
Type: [],
Defaults: 3,
Order: 3,
ContactID: contact3ID,
LabelIDs: [],
LastUsedTime: 3,
},
];
const message: MessageState = {
localID: 'localId',
data: {
Sender: { Address: '[email protected]' },
AddressID: 'AddressID',
ToList: [recipient1, recipient2],
CCList: [] as Recipient[],
BCCList: [] as Recipient[],
} as Message,
};
const messageSendInfo: MessageSendInfo = {
message,
mapSendInfo: {
[email1]: {
loading: false,
emailValidation: true,
},
[email2]: {
loading: false,
emailValidation: true,
},
},
setMapSendInfo: () => jest.fn(),
};
const DEFAULT_PROPS = {
message,
messageSendInfo,
disabled: false,
onChange: jest.fn(),
addressesBlurRef: {} as MutableRefObject<() => void>,
addressesFocusRef: {} as MutableRefObject<() => void>,
} as const;
const setup = async ({
messageProp,
minimalCache = true,
}: {
messageProp?: Partial<MessageState>;
minimalCache?: boolean;
} = {}) => {
const nextMessage = mergeMessages(DEFAULT_PROPS.message, messageProp || {});
store.dispatch(
composerActions.addComposer({
messageID: nextMessage.localID || '',
// @ts-expect-error
recipients: pick(nextMessage?.data, ['ToList', 'CCList', 'BCCList']),
senderEmailAddress: nextMessage.data?.Sender.Address,
})
);
const composerID = Object.keys(store.getState().composers.composers)[0];
const result = await render(
<Addresses {...DEFAULT_PROPS} message={nextMessage} composerID={composerID} />,
minimalCache
);
return { ...result, composerID };
};
describe('Addresses', () => {
const originalOffsetHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight');
const originalOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
beforeEach(clearAll);
// Used to render the Autosizer contact list
beforeAll(() => {
Object.defineProperty(HTMLElement.prototype, 'offsetHeight', { configurable: true, value: 50 });
Object.defineProperty(HTMLElement.prototype, 'offsetWidth', { configurable: true, value: 50 });
});
afterAll(() => {
if (originalOffsetHeight && originalOffsetWidth) {
Object.defineProperty(HTMLElement.prototype, 'offsetHeight', originalOffsetHeight);
Object.defineProperty(HTMLElement.prototype, 'offsetWidth', originalOffsetWidth);
}
clearAll();
});
it('should render Addresses', async () => {
await setup();
screen.getByText(email1Name);
screen.getByText(email2Name);
});
it('should add a contact from insert contact modal', async () => {
minimalCache();
addToCache('ContactEmails', contactEmails);
addApiMock('core/v4/keys/all', () => ({ Address: { Keys: [] } }));
const { rerender, composerID } = await setup({ minimalCache: false });
const toButton = screen.getByTestId('composer:to-button');
// Open the modal
fireEvent.click(toButton);
const modal = screen.getByTestId('modal:contactlist');
// Check if the modal is displayed with all contacts
getByText(modal, 'Insert contacts');
getByText(modal, contactEmails[0].Name);
getByText(modal, contactEmails[1].Name);
getByText(modal, contactEmails[2].Name);
// Expect contacts "email1" and "email2" to be checked by default
const checkedCheckboxes = getAllByRole(modal, 'checkbox', { checked: true, hidden: true });
expect(checkedCheckboxes.length).toEqual(2);
// Expect contact "email3" and "select all" checkboxes not to be checked
const notCheckedCheckboxes = getAllByRole(modal, 'checkbox', { checked: false, hidden: true });
expect(notCheckedCheckboxes.length).toEqual(2);
await act(async () => {
// Click on a non-checked checkbox (does not matter if this is the select all as long as there is only 3 contacts here)
fireEvent.click(notCheckedCheckboxes[0]);
});
// Check if all checkboxes are now checked
const checkedCheckboxesAfterClick = getAllByRole(modal, 'checkbox', { checked: true, hidden: true });
expect(checkedCheckboxesAfterClick.length).toEqual(4);
await act(async () => {
// Insert the third contact
const insertButton = getByText(modal, 'Insert 3 contacts');
fireEvent.click(insertButton);
});
// Expect to have all three contacts
const expectedChange = { data: { ToList: [recipient1, recipient2, recipient3] } };
expect(store.getState().composers.composers[composerID].recipients.ToList).toEqual([
recipient1,
recipient2,
recipient3,
]);
const updatedMessage = mergeMessages(message, expectedChange);
await rerender(<Addresses {...DEFAULT_PROPS} message={updatedMessage} composerID={composerID} />);
const updatedAddresses = screen.getAllByTestId('composer-addresses-item');
expect(updatedAddresses.length).toEqual(3);
});
it('Should display CC field on click', async () => {
await setup();
// cc and bcc fields shoud be hidden
expect(screen.queryByTestId('composer:to-cc')).toBe(null);
expect(screen.queryByTestId('composer:to-bcc')).toBe(null);
fireEvent.click(screen.getByTestId('composer:recipients:cc-button'));
// cc field visible now
await screen.findByTestId('composer:to-cc');
fireEvent.click(screen.getByTestId('composer:recipients:bcc-button'));
// bcc field visible now
await screen.findByTestId('composer:to-bcc');
});
it('Summary has BCC contact so click on CC should displays CC field and BCC field', async () => {
await setup({
messageProp: {
data: { BCCList: [recipient1] } as MessageState['data'],
},
});
// cc and bcc fields shoud be hidden
expect(screen.queryByTestId('composer:to-cc')).toBe(null);
expect(screen.queryByTestId('composer:to-bcc')).toBe(null);
fireEvent.click(screen.getByTestId('composer:recipients:cc-button'));
const ccField = await screen.findByTestId('composer:to-cc');
const bccField = await screen.findByTestId('composer:to-bcc');
expect(ccField).not.toBe(null);
expect(bccField).not.toBe(null);
});
it('Summary has CC contact so click on BCC should displays BCC field and CC field', async () => {
await setup({
messageProp: {
data: { CCList: [recipient1] } as MessageState['data'],
},
});
// cc and bcc fields shoud be hidden
expect(screen.queryByTestId('composer:to-cc')).toBe(null);
expect(screen.queryByTestId('composer:to-bcc')).toBe(null);
fireEvent.click(screen.getByTestId('composer:recipients:bcc-button'));
const ccField = await screen.findByTestId('composer:to-cc');
const bccField = await screen.findByTestId('composer:to-bcc');
expect(ccField).not.toBe(null);
expect(bccField).not.toBe(null);
});
});
|
3,383 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/addresses/AddressesEditor.test.tsx | import { MutableRefObject } from 'react';
import { fireEvent, screen } from '@testing-library/react';
import { getByText } from '@testing-library/react';
import { pick } from '@proton/shared/lib/helpers/object';
import { Recipient } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { addApiMock, clearAll, getDropdown, render, tick } from '../../../helpers/test/helper';
import { MessageSendInfo } from '../../../hooks/useSendInfo';
import { composerActions } from '../../../logic/composers/composersSlice';
import { MessageState } from '../../../logic/messages/messagesTypes';
import { store } from '../../../logic/store';
import AddressesEditor from './AddressesEditor';
const email1 = '[email protected]';
const email2 = '[email protected]';
const email3 = '[email protected]';
const email4 = '[email protected]';
const email1Name = 'email1Name';
const email2Name = 'email2Name';
const email3Name = 'email3Name';
const contact1ID = '1';
const contact2ID = '2';
const recipient1: Recipient = { Address: email1, Name: email1Name, ContactID: contact1ID };
const recipient2: Recipient = { Address: email2, Name: email2Name, ContactID: contact2ID };
const message: MessageState = {
localID: 'localId',
data: {
ToList: [recipient1, recipient2],
} as Message,
};
const messageSendInfo: MessageSendInfo = {
message,
mapSendInfo: {
[email1]: {
loading: false,
emailValidation: true,
},
[email2]: {
loading: false,
emailValidation: true,
},
},
setMapSendInfo: () => jest.fn(),
};
let ccExpanded = false;
let bccExpanded = false;
const props = {
message,
messageSendInfo,
onChange: jest.fn(),
expanded: false,
toggleExpanded: jest.fn(),
inputFocusRefs: {
to: {} as MutableRefObject<() => void>,
cc: {} as MutableRefObject<() => void>,
bcc: {} as MutableRefObject<() => void>,
},
handleContactModal: jest.fn(),
ccExpanded,
bccExpanded,
expandCC: () => {
ccExpanded = true;
},
expandBCC: () => {
bccExpanded = true;
},
};
const setupComposer = async () => {
store.dispatch(
composerActions.addComposer({
messageID: message.localID || '',
// @ts-expect-error
recipients: pick(message?.data, ['ToList', 'CCList', 'BCCList']),
senderEmailAddress: message.data?.Sender?.Address || '',
})
);
const composerID = Object.keys(store.getState().composers.composers)[0];
return composerID;
};
describe('AddressesEditor', () => {
beforeAll(() => {
ccExpanded = false;
bccExpanded = false;
});
beforeEach(clearAll);
afterAll(clearAll);
it('should render Addresses', async () => {
const composerID = await setupComposer();
const { getByText } = await render(<AddressesEditor {...props} composerID={composerID} />);
getByText(`${email1Name} <${email1}>`);
getByText(`${email2Name} <${email2}>`);
});
it('should delete an address', async () => {
const composerID = await setupComposer();
const { getByTestId, getAllByTestId } = await render(<AddressesEditor {...props} composerID={composerID} />);
const displayedAddresses = getAllByTestId('composer-addresses-item');
expect(displayedAddresses.length).toEqual(2);
const email2RemoveButton = getByTestId(`remove-address-button-${email2}`);
fireEvent.click(email2RemoveButton);
const remainingAddresses = getAllByTestId('composer-addresses-item');
expect(remainingAddresses.length).toEqual(1);
});
it.each`
input | expectedArray
${email3} | ${[{ Name: email3, Address: email3 }]}
${`${email3}, ${email4}`} | ${[{ Name: email3, Address: email3 }, { Name: email4, Address: email4 }]}
${`${email3} ${email4}`} | ${[{ Name: email3, Address: email3 }, { Name: email4, Address: email4 }]}
${`${email3Name} <${email3}>`} | ${[{ Name: email3Name, Address: email3 }]}
${`${email3Name} <${email3}>, ${email4}`} | ${[{ Name: email3Name, Address: email3 }, { Name: email4, Address: email4 }]}
${`${email3Name} <${email3}> ${email4}`} | ${[{ Name: email3Name, Address: email3 }]}
`(
'should add correct addresses with the input "$input"',
async ({ input, expectedArray }: { input: string; expectedArray: Recipient[] }) => {
addApiMock('core/v4/keys/all', () => ({ Address: { Keys: [] } }));
const composerID = await setupComposer();
const { getAllByTestId, getByTestId } = await render(
<AddressesEditor {...props} composerID={composerID} />
);
const displayedAddresses = getAllByTestId('composer-addresses-item');
expect(displayedAddresses.length).toEqual(2);
const addressesInput = getByTestId('composer:to');
fireEvent.change(addressesInput, { target: { value: input } });
fireEvent.keyDown(addressesInput, { key: 'Enter' });
const newAddresses = getAllByTestId('composer-addresses-item');
expect(newAddresses.length).toEqual(2 + expectedArray.length);
}
);
it('should edit an address on double click', async () => {
const composerID = await setupComposer();
const { getAllByTestId, getByText } = await render(<AddressesEditor {...props} composerID={composerID} />);
const displayedAddresses = getAllByTestId('composer-addresses-item-label');
const addressSpan = displayedAddresses[0];
expect(addressSpan.getAttribute('contenteditable')).toEqual('false');
fireEvent.dblClick(addressSpan);
expect(addressSpan.getAttribute('contenteditable')).toEqual('true');
fireEvent.change(addressSpan, {
target: { innerHTML: email3 },
});
fireEvent.keyDown(addressSpan, { key: 'Enter' });
getByText(email3);
expect(addressSpan.getAttribute('contenteditable')).toEqual('false');
});
it('should open option dropdown', async () => {
const composerID = await setupComposer();
const { getAllByTestId } = await render(<AddressesEditor {...props} composerID={composerID} />);
const displayedAddresses = getAllByTestId('composer-addresses-item-label');
fireEvent.contextMenu(displayedAddresses[0]);
const dropdown = await getDropdown();
getByText(dropdown, 'Copy address');
getByText(dropdown, 'Edit address');
getByText(dropdown, 'Create new contact');
getByText(dropdown, 'Remove');
});
it('should copy an address', async () => {
document.execCommand = jest.fn();
const composerID = await setupComposer();
const { getAllByTestId } = await render(<AddressesEditor {...props} composerID={composerID} />);
const displayedAddresses = getAllByTestId('composer-addresses-item-label');
fireEvent.contextMenu(displayedAddresses[0]);
const dropdown = await getDropdown();
const copyAddressButton = getByText(dropdown, 'Copy address');
fireEvent.click(copyAddressButton);
expect(document.execCommand).toHaveBeenCalledWith('copy');
});
it('should edit an address in option dropdown', async () => {
const composerID = await setupComposer();
const { getAllByTestId } = await render(<AddressesEditor {...props} composerID={composerID} />);
const displayedAddresses = getAllByTestId('composer-addresses-item-label');
const addressSpan = displayedAddresses[0];
fireEvent.contextMenu(addressSpan);
const dropdown = await getDropdown();
const editAddressButton = getByText(dropdown, 'Edit address');
fireEvent.click(editAddressButton);
expect(addressSpan.getAttribute('contenteditable')).toEqual('true');
fireEvent.change(addressSpan, {
target: { innerHTML: email3 },
});
fireEvent.keyDown(addressSpan, { key: 'Enter' });
screen.getByText(email3);
});
it('should open create modal when clicking on create contact', async () => {
addApiMock('contacts/v4/contacts', () => ({ Contacts: [] }));
const composerID = await setupComposer();
const { getAllByTestId } = await render(<AddressesEditor {...props} composerID={composerID} />);
const displayedAddresses = getAllByTestId('composer-addresses-item-label');
fireEvent.contextMenu(displayedAddresses[0]);
const dropdown = await getDropdown();
const createContactButton = getByText(dropdown, 'Create new contact');
fireEvent.click(createContactButton);
await tick();
getByText(document.body, 'Create contact');
});
it('should delete an address in option modal', async () => {
const composerID = await setupComposer();
const { getAllByTestId } = await render(<AddressesEditor {...props} composerID={composerID} />);
const displayedAddresses = getAllByTestId('composer-addresses-item-label');
expect(displayedAddresses.length).toEqual(2);
const addressSpan = displayedAddresses[0];
fireEvent.contextMenu(addressSpan);
const dropdown = await getDropdown();
const removeAddressButton = getByText(dropdown, 'Remove');
fireEvent.click(removeAddressButton);
const remainingAddresses = getAllByTestId('composer-addresses-item');
expect(remainingAddresses.length).toEqual(1);
});
it('should not focus CC BCC or Insert contacts buttons', async () => {
const composerID = await setupComposer();
const { getByTestId } = await render(<AddressesEditor {...props} composerID={composerID} />);
const ccButton = getByTestId('composer:recipients:cc-button');
const bccButton = getByTestId('composer:recipients:bcc-button');
const insertContactsButton = getByTestId('composer:to-button');
expect(ccButton.getAttribute('tabindex')).toEqual('-1');
expect(bccButton.getAttribute('tabindex')).toEqual('-1');
expect(insertContactsButton.getAttribute('tabindex')).toEqual('-1');
});
});
|
3,389 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/addresses/AddressesSummary.test.tsx | import { screen } from '@testing-library/react';
import { ContactGroup } from '@proton/shared/lib/interfaces/contacts';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import noop from '@proton/utils/noop';
import { getRecipientLabel } from '../../../helpers/message/messageRecipients';
import { clearAll, render } from '../../../helpers/test/helper';
import { refresh } from '../../../logic/contacts/contactsActions';
import { store } from '../../../logic/store';
import { RecipientType } from '../../../models/address';
import { prepareMessage } from '../tests/Composer.test.helpers';
import AddressesSummary from './AddressesSummary';
const message = {} as Message;
const props = {
message,
contacts: [],
contactGroups: [],
onFocus: noop,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
toggleExpanded: (_type: RecipientType) => noop,
disabled: false,
handleContactModal: jest.fn(),
};
const recipient = { Name: 'RecipientName', Address: 'Address' };
const recipientLabel = getRecipientLabel(recipient, {}) || '';
const recipientGroup = { Name: 'RecipientName', Address: 'Address', Group: 'GroupPath' };
const group = { Name: 'GroupName', Path: 'GroupPath' } as ContactGroup;
describe('AddressesSummary', () => {
beforeEach(clearAll);
beforeEach(() => {
store.dispatch(refresh({ contacts: [], contactGroups: [group] }));
});
beforeAll(clearAll);
it('should render a recipient', async () => {
const { composerID } = prepareMessage({
data: {
ToList: [recipient],
},
});
await render(<AddressesSummary {...props} composerID={composerID} />);
screen.getByText(recipientLabel);
});
it('should render a group', async () => {
const { composerID } = prepareMessage({
data: {
ToList: [recipientGroup],
},
});
await render(<AddressesSummary {...props} composerID={composerID} />);
screen.getByText(group.Name, { exact: false });
});
it('should render a recipient and a group', async () => {
const { composerID } = prepareMessage({
data: {
ToList: [recipient, recipientGroup],
},
});
await render(<AddressesSummary {...props} composerID={composerID} />);
screen.getByText(recipientLabel);
screen.getByText(group.Name, { exact: false });
});
});
|
3,421 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/tests/QuickReply.compose.test.tsx | import {
GeneratedKey,
clearAll,
generateKeys,
releaseCryptoProxy,
removeLineBreaks,
setFeatureFlags,
setupCryptoProxyForTesting,
} from '../../../../helpers/test/helper';
import { messageID } from '../../../message/tests/Message.test.helpers';
import { data, fromFields, recipients } from './QuickReply.test.data';
import { getStateMessageFromParentID, setupQuickReplyTests } from './QuickReply.test.helpers';
jest.setTimeout(20000);
describe('Quick reply - Compose', () => {
let meKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
meKeys = await generateKeys('me', fromFields.meAddress);
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(() => {
setFeatureFlags('QuickReply', true);
});
afterEach(() => {
clearAll();
});
it('should open a plaintext quick reply and be able to modify it', async () => {
// Setup test
const {
openQuickReply,
updateQuickReplyContent,
sendQuickReply,
getPlainTextEditor,
expectedDefaultPlainTextContent,
createCall,
sendCall,
} = await setupQuickReplyTests({ meKeys, isPlainText: true });
await openQuickReply();
const plainTextEditor = await getPlainTextEditor();
/**
* Initialisation check
*/
// Plaintext editor should contain only the signature by default in QR
// Because we hide the reply
expect(plainTextEditor?.value.trim()).toEqual(data.protonSignature);
// However, the state should contain the whole message (message + sig + blockquotes content)
const messageFromState = getStateMessageFromParentID(messageID);
expect(removeLineBreaks(messageFromState?.messageDocument?.plainText || '')).toEqual(
removeLineBreaks(expectedDefaultPlainTextContent)
);
// Sender and Recipients are correct
expect(messageFromState?.data?.Sender.Address).toEqual(fromFields.meAddress);
expect(messageFromState?.data?.ToList).toEqual([recipients.fromRecipient]);
// Auto-save has not been called yet
expect(createCall).not.toHaveBeenCalled();
/**
* Check after making a change in the editor
* After passing the whole composer logic, we still don't have the reply added to the content
*/
const newContent = 'Adding content';
const contentChange = `${newContent} ${data.protonSignature}`;
// Type something in the editor
await updateQuickReplyContent(contentChange);
// Content in the editor is the one expected
expect(removeLineBreaks(plainTextEditor?.value || '')).toEqual(removeLineBreaks(contentChange));
// Content in the state is the one expected
const messageFromStateAfterUpdate = getStateMessageFromParentID(messageID);
const expectedUpdatedContent = `${newContent} ${expectedDefaultPlainTextContent}`;
expect(removeLineBreaks(messageFromStateAfterUpdate?.messageDocument?.plainText || '')).toEqual(
removeLineBreaks(expectedUpdatedContent)
);
// Auto-save has been called
expect(createCall).toHaveBeenCalled();
/**
* Send the quick reply
*/
await sendQuickReply();
expect(sendCall).toHaveBeenCalled();
const sendRequest = (sendCall.mock.calls[0] as any[])[0];
expect(sendRequest.method).toBe('post');
});
it('should open an HTML quick reply and be able to modify it', async () => {
const referenceMessageContent = 'Reference message content';
const { openQuickReply, updateQuickReplyContent, getRoosterEditor, sendQuickReply, createCall, sendCall } =
await setupQuickReplyTests({
meKeys,
referenceMessageBody: `<div>${referenceMessageContent}<br><div>`,
});
await openQuickReply();
const roosterEditor = await getRoosterEditor();
const messageFromState = getStateMessageFromParentID(messageID);
/**
* Initialisation check
*/
// Editor should contain only the signature by default in QR
// Because we hide the reply
let protonSignature;
let protonBlockquotes;
if (roosterEditor) {
protonSignature = roosterEditor.innerHTML.includes('Sent with');
protonBlockquotes = roosterEditor.innerHTML.includes(referenceMessageContent);
}
// Editor
// Signature is found in the editor
expect(protonSignature).toBeTruthy();
// Blockquotes are not present in the editor
expect(protonBlockquotes).toBeFalsy();
// Redux state
// Signature is found in the state
const messageInnerHTML = messageFromState?.messageDocument?.document?.innerHTML || '';
expect(messageInnerHTML.includes('Sent with')).toBeTruthy();
// Blockquotes are present in the state
expect(messageInnerHTML.includes(referenceMessageContent)).toBeTruthy();
// Auto-save has not been called yet
expect(createCall).not.toHaveBeenCalled();
/**
* Check after making a change in the editor
* After passing the whole composer logic, we still don't have the reply added to the content
*/
const newContent = 'Adding content';
// Type something in the editor
await updateQuickReplyContent(newContent);
const messageFromStateAfterUpdate = getStateMessageFromParentID(messageID);
let protonContentAfterUpdate;
let protonSignatureAfterUpdate;
let protonBlockquotesAfterUpdate;
if (roosterEditor) {
protonContentAfterUpdate = roosterEditor.innerHTML.includes(newContent);
protonSignatureAfterUpdate = roosterEditor.innerHTML.includes('Sent with');
protonBlockquotesAfterUpdate = roosterEditor.innerHTML.includes(referenceMessageContent);
}
// Editor
// New content is found in the editor
expect(protonContentAfterUpdate).toBeTruthy();
// Signature is found in the editor
expect(protonSignatureAfterUpdate).toBeTruthy();
// Blockquotes are not present in the editor
expect(protonBlockquotesAfterUpdate).toBeFalsy();
// Redux state
const messageInnerHTMLAfterUpdate = messageFromStateAfterUpdate?.messageDocument?.document?.innerHTML || '';
// New content is found in the state
expect(messageInnerHTMLAfterUpdate.includes(newContent)).toBeTruthy();
// Signature is found in the state
expect(messageInnerHTMLAfterUpdate.includes('Sent with')).toBeTruthy();
// Blockquotes are present in the state
expect(messageInnerHTMLAfterUpdate.includes(referenceMessageContent)).toBeTruthy();
// Auto-save has been called
expect(createCall).toHaveBeenCalled();
/**
* Send the quick reply
*/
await sendQuickReply();
await expect(sendCall).toHaveBeenCalled();
const sendRequest = (sendCall.mock.calls[0] as any[])[0];
expect(sendRequest.method).toBe('post');
});
});
|
3,422 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/tests/QuickReply.replyType.test.tsx | import { MESSAGE_ACTIONS } from '../../../../constants';
import {
GeneratedKey,
clearAll,
generateKeys,
releaseCryptoProxy,
setFeatureFlags,
setupCryptoProxyForTesting,
} from '../../../../helpers/test/helper';
import { messageID } from '../../../message/tests/Message.test.helpers';
import { data, fromFields, recipients } from './QuickReply.test.data';
import { getStateMessageFromParentID, setupQuickReplyTests } from './QuickReply.test.helpers';
jest.setTimeout(20000);
describe('Quick reply - Reply type', function () {
beforeEach(() => {
setFeatureFlags('QuickReply', true);
});
afterEach(() => {
clearAll();
});
let meKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
meKeys = await generateKeys('me', fromFields.meAddress);
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should be possible to switch the quick reply type when user received a message', async () => {
// Setup test
const { openQuickReply, updateReplyType, getRecipientList, createCall, updateCall } =
await setupQuickReplyTests({
meKeys,
isPlainText: true,
});
await openQuickReply();
/**
* Initialisation check
*/
const messageFromState = getStateMessageFromParentID(messageID);
// List is the one expected on the UI
const expectedList = `${data.quickReplyRecipientsStart} ${fromFields.fromName}`;
const recipientList = await getRecipientList();
expect(recipientList).toEqual(expectedList);
// List is the one expected in the state
expect(messageFromState?.data?.ToList).toEqual([recipients.fromRecipient]);
expect(messageFromState?.data?.CCList).toEqual([]);
expect(messageFromState?.data?.BCCList).toEqual([]);
// Auto-save has not been called yet
expect(createCall).not.toHaveBeenCalled();
/**
* Switch to reply all
*/
await updateReplyType(MESSAGE_ACTIONS.REPLY_ALL, true);
const messageFromStateAfterUpdate1 = getStateMessageFromParentID(messageID);
const expectedListAfterUpdate1 = `${data.quickReplyRecipientsStart} ${fromFields.fromName}, ${fromFields.toName}, ${fromFields.ccName}`;
const recipientListAfterUpdate1 = await getRecipientList();
expect(recipientListAfterUpdate1).toEqual(expectedListAfterUpdate1);
// List is the one expected in the state
expect(messageFromStateAfterUpdate1?.data?.ToList).toEqual([recipients.fromRecipient]);
expect(messageFromStateAfterUpdate1?.data?.CCList).toEqual([recipients.toRecipient, recipients.ccRecipient]);
expect(messageFromStateAfterUpdate1?.data?.BCCList).toEqual([]);
// Auto-save has been called
expect(createCall).toHaveBeenCalled();
/**
* Switch back to reply
*/
await updateReplyType(MESSAGE_ACTIONS.REPLY);
const messageFromStateAfterUpdate2 = getStateMessageFromParentID(messageID);
expect(recipientList).toEqual(expectedList);
// List is the one expected in the state
expect(messageFromStateAfterUpdate2?.data?.ToList).toEqual([recipients.fromRecipient]);
expect(messageFromStateAfterUpdate2?.data?.CCList).toEqual([]);
expect(messageFromStateAfterUpdate2?.data?.BCCList).toEqual([]);
// Auto-save update has been called
expect(updateCall).toHaveBeenCalled();
});
it('should be possible to switch the quick reply type when user sent a message', async () => {
// Setup test
const { openQuickReply, updateReplyType, getRecipientList, createCall, updateCall } =
await setupQuickReplyTests({
meKeys,
isPlainText: true,
isSender: true,
});
await openQuickReply();
/**
* Initialisation check
*/
const messageFromState = getStateMessageFromParentID(messageID);
// List is the one expected on the UI
const expectedList = `${data.quickReplyRecipientsStart} ${fromFields.fromName}, ${fromFields.toName}`;
const recipientList = await getRecipientList();
expect(recipientList).toEqual(expectedList);
// List is the one expected in the state
expect(messageFromState?.data?.ToList).toEqual([recipients.fromRecipient, recipients.toRecipient]);
expect(messageFromState?.data?.CCList).toEqual([]);
expect(messageFromState?.data?.BCCList).toEqual([]);
// Auto-save has not been called yet
expect(createCall).not.toHaveBeenCalled();
/**
* Switch to reply all
*/
await updateReplyType(MESSAGE_ACTIONS.REPLY_ALL, true);
const messageFromStateAfterUpdate1 = getStateMessageFromParentID(messageID);
const expectedListAfterUpdate1 = `${data.quickReplyRecipientsStart} ${fromFields.fromName}, ${fromFields.toName}, ${fromFields.ccName}, ${fromFields.bccName}`;
const recipientListAfterUpdate1 = await getRecipientList();
expect(recipientListAfterUpdate1).toEqual(expectedListAfterUpdate1);
// List is the one expected in the state
expect(messageFromStateAfterUpdate1?.data?.ToList).toEqual([recipients.fromRecipient, recipients.toRecipient]);
expect(messageFromStateAfterUpdate1?.data?.CCList).toEqual([recipients.ccRecipient]);
expect(messageFromStateAfterUpdate1?.data?.BCCList).toEqual([recipients.bccRecipient]);
// Auto-save has been called
expect(createCall).toHaveBeenCalled();
/**
* Switch back to reply
*/
await updateReplyType(MESSAGE_ACTIONS.REPLY);
const messageFromStateAfterUpdate2 = getStateMessageFromParentID(messageID);
expect(recipientList).toEqual(expectedList);
// List is the one expected in the state
expect(messageFromStateAfterUpdate2?.data?.ToList).toEqual([recipients.fromRecipient, recipients.toRecipient]);
expect(messageFromState?.data?.CCList).toEqual([]);
expect(messageFromState?.data?.BCCList).toEqual([]);
// Auto-save update has been called
expect(updateCall).toHaveBeenCalled();
});
});
|
3,425 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.attachments.test.tsx | import { fireEvent, getByTitle, waitFor } from '@testing-library/react';
import { act } from '@testing-library/react';
import loudRejection from 'loud-rejection';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { Address, Key } from '@proton/shared/lib/interfaces';
import { arrayToBase64 } from '../../../helpers/base64';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
GeneratedKey,
addAddressToCache,
addApiKeys,
addApiMock,
addApiResolver,
addKeysToAddressKeysCache,
clearAll,
createAttachment,
createDocument,
decryptSessionKey,
generateKeys,
getDropdown,
minimalCache,
parseFormData,
render,
tick,
waitForNoNotification,
waitForNotification,
} from '../../../helpers/test/helper';
import { store } from '../../../logic/store';
import Composer from '../Composer';
import { ID, prepareMessage, props, toAddress } from './Composer.test.helpers';
loudRejection();
jest.setTimeout(20000);
describe('Composer attachments', () => {
let address1Keys: GeneratedKey;
let address2Keys: GeneratedKey;
const address1 = { ID: 'AddressID1', Email: '[email protected]', Keys: [{ ID: 'KeyID1' } as Key] } as Address;
const address2 = { ID: 'AddressID2', Email: '[email protected]', Keys: [{ ID: 'KeyID2' } as Key] } as Address;
const fileName = 'file.png';
const fileType = 'image/png';
const file = new File([], fileName, { type: fileType });
const attachmentData = { ID: 'AttachmentID', Name: fileName, MIMEType: fileType };
let updateSpy: jest.Mock;
let sendSpy: jest.Mock;
const setup = async (MIMEType = MIME_TYPES.PLAINTEXT) => {
const { attachment, sessionKey: generatedSessionKey } = await createAttachment(
attachmentData,
address1Keys.publicKeys
);
const { resolve } = addApiResolver('mail/v4/attachments');
updateSpy = jest.fn(({ data: { Message, AttachmentKeyPackets } }: any) => {
Message.Attachments.forEach((Attachment: any) => {
if (AttachmentKeyPackets?.[Attachment.ID]) {
Attachment.KeyPackets = AttachmentKeyPackets[Attachment.ID];
}
});
return Promise.resolve({ Message });
});
addApiMock(`mail/v4/messages/${ID}`, updateSpy, 'put');
sendSpy = jest.fn(() => Promise.resolve({ Sent: {} }));
addApiMock(`mail/v4/messages/${ID}`, sendSpy, 'post');
minimalCache();
const message = prepareMessage({
localID: ID,
data: { AddressID: address1.ID, MIMEType, Sender: { Address: address1.ID, Name: address1.Email } },
messageDocument: { plainText: 'test', document: createDocument('hello') },
});
addApiKeys(false, toAddress, []);
addAddressToCache(address1);
addAddressToCache(address2);
const composerID = Object.keys(store.getState().composers.composers)[0];
const result = await render(<Composer {...props} composerID={composerID} />, false);
props.onClose.mockImplementation(result.unmount);
const inputAttachment = result.getByTestId('composer-attachments-button') as HTMLInputElement;
fireEvent.change(inputAttachment, { target: { files: [file] } });
await tick();
return { ...result, resolve, message, attachment, generatedSessionKey, updateSpy, sendSpy };
};
const saveNow = async (container: HTMLElement) => {
fireEvent.keyDown(container, { key: 's', ctrlKey: true });
await tick();
};
const waitForAutoSave = async () => {
act(() => {
jest.advanceTimersByTime(3000);
});
await tick();
};
const switchAddress = async (getByTestId: (id: string) => HTMLElement) => {
const fromButton = getByTestId('composer:from') as HTMLButtonElement;
fireEvent.click(fromButton);
const fromDropdown = await getDropdown();
const email2Dropdown = getByTitle(fromDropdown, address2.Email);
fireEvent.click(email2Dropdown);
};
beforeAll(async () => {
await setupCryptoProxyForTesting();
address1Keys = await generateKeys('1', address1.Email);
address2Keys = await generateKeys('2', address2.Email);
});
afterAll(async () => {
clearAll();
await releaseCryptoProxy();
});
beforeEach(() => {
clearAll();
jest.useFakeTimers();
addKeysToAddressKeysCache(address1.ID, address1Keys);
addKeysToAddressKeysCache(address2.ID, address2Keys);
});
afterEach(() => {
jest.useRealTimers();
});
it('should not show embedded modal when plaintext mode', async () => {
const { queryAllByText, findByText, resolve, container } = await setup();
const embeddedModalMatch = queryAllByText('Insert image');
expect(embeddedModalMatch.length).toBe(0);
// Testing aria-label is simple as filename has an ellipse split in the middle
const attachmentName = container.querySelector(`[aria-label="${fileName}"]`);
expect(attachmentName).not.toBe(null);
resolve({ Attachment: { ID: 'AttachmentID' } });
await tick();
await waitForAutoSave();
// file without an "s" mean only one
await findByText('file attached');
});
it('should show embedded modal when html mode', async () => {
const { queryAllByText, getByTestId, findByText, resolve, container } = await setup(MIME_TYPES.DEFAULT);
const embeddedModalMatch = queryAllByText('Insert image');
expect(embeddedModalMatch.length).toBeGreaterThanOrEqual(1);
const attachmentButton = getByTestId('composer:insert-image-attachment');
fireEvent.click(attachmentButton);
await tick();
// Testing aria-label is simple as filename has an ellipse split in the middle
const attachmentName = container.querySelector(`[aria-label="${fileName}"]`);
expect(attachmentName).not.toBe(null);
resolve({ Attachment: { ID: 'AttachmentID' } });
await tick();
await waitForAutoSave();
// file without an "s" mean only one
await findByText('file attached');
});
it('should re-encrypt attachment key packets on sender address change', async () => {
const { getByTestId, findByText, resolve, attachment, generatedSessionKey, container, updateSpy } =
await setup();
resolve({ Attachment: attachment });
await tick();
await waitForAutoSave();
await switchAddress(getByTestId);
await findByText('file attached');
await saveNow(container);
expect(updateSpy).toHaveBeenCalled();
const requestData = (updateSpy.mock.calls[1] as any[])[0].data;
const keyPackets = requestData.AttachmentKeyPackets[attachment.ID as string];
expect(keyPackets).toBeDefined();
const decryptedSessionKey = await decryptSessionKey(keyPackets, address2Keys.privateKeys);
expect(generatedSessionKey).toEqual(decryptedSessionKey);
});
it('should re-encrypt attachment key packets on sender address change and send', async () => {
const { message, resolve, attachment, generatedSessionKey, updateSpy, sendSpy, ...renderResult } =
await setup();
await switchAddress(renderResult.getByTestId);
const sendButton = await renderResult.findByTestId('composer:send-button');
fireEvent.click(sendButton);
await tick();
await waitForNotification('Sending message...');
resolve({ Attachment: attachment });
await tick();
await waitFor(
() => {
expect(updateSpy).toBeCalled();
},
{ timeout: 20000 }
);
await tick();
await waitFor(
() => {
expect(sendSpy).toBeCalled();
},
{ timeout: 20000 }
);
await waitForNotification('Message sent');
await waitForNoNotification();
const requestData = (updateSpy.mock.calls[1] as any[])[0].data;
const keyPackets = requestData.AttachmentKeyPackets[attachment.ID as string];
expect(keyPackets).toBeDefined();
const sendRequest = (sendSpy.mock.calls[0] as any[])[0].data;
const sendData = parseFormData(sendRequest);
const attachmentKey = sendData.Packages['text/plain'].AttachmentKeys[attachment.ID as string].Key;
// Attachment session key sent is the one we generated
expect(attachmentKey).toBe(arrayToBase64(generatedSessionKey.data));
});
});
|
3,426 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.autosave.test.tsx | import { fireEvent, getByTestId, waitFor } from '@testing-library/react';
import { act } from '@testing-library/react';
import { ROOSTER_EDITOR_ID } from '@proton/components/components/editor/constants';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import noop from '@proton/utils/noop';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
GeneratedKey,
addApiKeys,
addApiMock,
addKeysToAddressKeysCache,
clearAll,
createDocument,
generateKeys,
} from '../../../helpers/test/helper';
import { store } from '../../../logic/store';
import { AddressID, ID, fromAddress, prepareMessage, renderComposer, toAddress } from './Composer.test.helpers';
jest.setTimeout(20000);
/**
* Those tests are slow, I'm sorry for that
* But I found no way of making jest fake timers works (at least with the composer)
*/
describe('Composer autosave', () => {
let fromKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
fromKeys = await generateKeys('me', fromAddress);
});
afterAll(async () => {
clearAll();
await releaseCryptoProxy();
});
beforeEach(() => {
clearAll();
jest.useFakeTimers();
addKeysToAddressKeysCache(AddressID, fromKeys);
addApiKeys(false, toAddress, []);
});
afterEach(() => {
jest.useRealTimers();
});
const asyncSpy = (resolved = true) => {
let resolve: (value: unknown) => void = noop;
let reject: (value: unknown) => void = noop;
const spy = jest.fn(() => {
if (resolved) {
return Promise.resolve({ Message: { ID } });
}
return new Promise((res, rej) => {
resolve = res;
reject = rej;
});
});
return { spy, resolve: (value: unknown) => resolve(value), reject: (value: unknown) => reject(value) };
};
const triggerRoosterInput = (container: HTMLElement) => {
const iframe = getByTestId(container, 'rooster-iframe') as HTMLIFrameElement;
const editor = iframe.contentDocument?.getElementById(ROOSTER_EDITOR_ID);
if (editor) {
fireEvent.input(editor, 'hello');
}
};
const setup = async (resolved = true) => {
prepareMessage({
data: { ID: undefined, MIMEType: MIME_TYPES.DEFAULT },
messageDocument: { document: createDocument('test') },
});
const composerID = Object.keys(store.getState().composers.composers)[0];
const renderResult = await renderComposer(composerID);
triggerRoosterInput(renderResult.container); // Initial dummy Squire input
const { spy: createSpy, resolve: createResolve } = asyncSpy(resolved);
const { spy: updateSpy, resolve: updateResolve } = asyncSpy(resolved);
const { spy: sendSpy, resolve: sendResolve } = asyncSpy(resolved);
addApiMock(`mail/v4/messages`, createSpy, 'post');
addApiMock(`mail/v4/messages/undefined`, updateSpy, 'put'); // Should be /ID
addApiMock(`mail/v4/messages/${ID}`, sendSpy, 'post'); // Should be /ID
return { ...renderResult, createSpy, updateSpy, sendSpy, createResolve, updateResolve, sendResolve };
};
const waitForSpy = (spy: jest.Mock<Promise<unknown>, []>) =>
waitFor(
() => {
expect(spy).toHaveBeenCalled();
},
{ timeout: 10000 }
);
it('should wait 2s before saving a change', async () => {
const { createSpy, container } = await setup();
await act(async () => {
triggerRoosterInput(container);
jest.advanceTimersByTime(1500);
expect(createSpy).not.toHaveBeenCalled();
jest.advanceTimersByTime(1500);
await waitForSpy(createSpy);
});
});
it('should wait 2s after the last change before saving a change', async () => {
const { createSpy, container } = await setup();
await act(async () => {
triggerRoosterInput(container);
jest.advanceTimersByTime(1500);
triggerRoosterInput(container);
jest.advanceTimersByTime(1500);
expect(createSpy).not.toHaveBeenCalled();
jest.advanceTimersByTime(1500);
await waitForSpy(createSpy);
});
});
it('should wait 2s after previous save resolved before saving a change', async () => {
const { createSpy, createResolve, updateSpy, container } = await setup(false);
await act(async () => {
triggerRoosterInput(container);
jest.advanceTimersByTime(1500);
expect(createSpy).not.toHaveBeenCalled();
jest.advanceTimersByTime(1500);
await waitForSpy(createSpy);
triggerRoosterInput(container);
jest.advanceTimersByTime(1500);
expect(updateSpy).not.toHaveBeenCalled();
jest.advanceTimersByTime(1500);
expect(updateSpy).not.toHaveBeenCalled();
createResolve({ Message: { ID } });
jest.advanceTimersByTime(1500);
expect(updateSpy).not.toHaveBeenCalled();
jest.advanceTimersByTime(1500);
await waitForSpy(updateSpy);
});
});
it('should wait previous save before sending', async () => {
jest.useFakeTimers();
const { createSpy, createResolve, sendSpy, container, ...renderResult } = await setup(false);
await act(async () => {
triggerRoosterInput(container);
jest.advanceTimersByTime(1500);
const sendButton = await renderResult.findByTestId('composer:send-button');
fireEvent.click(sendButton);
jest.advanceTimersByTime(1500);
await waitForSpy(createSpy);
expect(sendSpy).not.toHaveBeenCalled();
createResolve({ Message: { ID, Attachments: [] } });
await waitForSpy(sendSpy);
});
});
});
|
3,427 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.expiration.test.tsx | import { fireEvent } from '@testing-library/react';
import { act, getByTestId as getByTestIdDefault, getByText as getByTextDefault } from '@testing-library/react';
import { format } from 'date-fns';
import loudRejection from 'loud-rejection';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { addDays } from '@proton/shared/lib/date-fns-utc';
import { dateLocale } from '@proton/shared/lib/i18n';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
addApiKeys,
addKeysToAddressKeysCache,
clearAll,
generateKeys,
getDropdown,
render,
} from '../../../helpers/test/helper';
import { store } from '../../../logic/store';
import Composer from '../Composer';
import { AddressID, ID, fromAddress, prepareMessage, props, toAddress } from './Composer.test.helpers';
loudRejection();
describe('Composer expiration', () => {
beforeEach(() => {
clearAll();
});
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
clearAll();
await releaseCryptoProxy();
});
const setup = async () => {
const state = store.getState();
const composerID = Object.keys(state.composers.composers)[0];
const fromKeys = await generateKeys('me', fromAddress);
addKeysToAddressKeysCache(AddressID, fromKeys);
addApiKeys(false, toAddress, []);
const result = await render(<Composer {...props} composerID={composerID} />);
return result;
};
it('should open expiration modal with default values', async () => {
const expirationDate = addDays(new Date(), 7);
const datePlaceholder = format(expirationDate, 'PP', { locale: dateLocale });
prepareMessage({
localID: ID,
data: { MIMEType: 'text/plain' as MIME_TYPES },
messageDocument: { plainText: '' },
});
const { getByTestId, getByText } = await setup();
const moreOptionsButton = getByTestId('composer:more-options-button');
fireEvent.click(moreOptionsButton);
const dropdown = await getDropdown();
getByTextDefault(dropdown, 'Expiration time');
const expirationButton = getByTestIdDefault(dropdown, 'composer:expiration-button');
await act(async () => {
fireEvent.click(expirationButton);
});
getByText('Expiring message');
const dayInput = getByTestId('composer:expiration-days') as HTMLInputElement;
const hoursInput = getByTestId('composer:expiration-hours') as HTMLInputElement;
// Check if default expiration is in 7 days and at 9 o'clock
expect(dayInput.value).toEqual(datePlaceholder);
expect(hoursInput.value).toEqual('9:00 AM');
});
it('should display expiration banner and open expiration modal when clicking on edit', async () => {
const expirationDate = addDays(new Date(), 7);
const expirationTime = expirationDate.getTime() / 1000;
const datePlaceholder = format(expirationDate, 'PP', { locale: dateLocale });
prepareMessage({
localID: ID,
data: { MIMEType: 'text/plain' as MIME_TYPES, ExpirationTime: expirationTime },
messageDocument: { plainText: '' },
});
const { getByText, getByTestId } = await setup();
getByText(/This message will expire/);
const editButton = getByTestId('message:expiration-banner-edit-button');
await act(async () => {
fireEvent.click(editButton);
});
getByText('Expiring message');
const dayInput = getByTestId('composer:expiration-days') as HTMLInputElement;
const hoursInput = getByTestId('composer:expiration-hours') as HTMLInputElement;
// Check if default expiration is in 7 days and at 9 o'clock
expect(dayInput.value).toEqual(datePlaceholder);
expect(hoursInput.value).toEqual('9:00 AM');
});
});
|
3,428 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.hotkeys.test.tsx | import { fireEvent } from '@testing-library/react';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { SHORTCUTS } from '@proton/shared/lib/mail/mailSettings';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
GeneratedKey,
addApiKeys,
addApiMock,
addKeysToAddressKeysCache,
addToCache,
clearAll,
clearCache,
createDocument,
generateKeys,
minimalCache,
waitForNotification,
} from '../../../helpers/test/helper';
import { store } from '../../../logic/store';
import { AddressID, ID, fromAddress, prepareMessage, renderComposer, toAddress } from './Composer.test.helpers';
const orignalGetSelection = global.getSelection;
beforeAll(() => {
global.getSelection = jest.fn();
});
afterAll(() => {
global.getSelection = orignalGetSelection;
});
describe('Composer hotkeys', () => {
let fromKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
fromKeys = await generateKeys('me', fromAddress);
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(() => {
clearCache();
});
beforeEach(clearAll);
const setup = async (hasShortcutsEnabled = true) => {
minimalCache();
if (hasShortcutsEnabled) {
addToCache('MailSettings', { Shortcuts: SHORTCUTS.ENABLED });
} else {
addToCache('MailSettings', { Shortcuts: SHORTCUTS.DISABLED });
}
addKeysToAddressKeysCache(AddressID, fromKeys);
prepareMessage({
messageDocument: { document: createDocument('test') },
data: { MIMEType: MIME_TYPES.DEFAULT },
});
addApiKeys(false, toAddress, []);
const composerID = Object.keys(store.getState().composers.composers)[0];
const result = await renderComposer(composerID, false);
const iframe = result.container.querySelector('iframe') as HTMLIFrameElement;
return {
...result,
iframe,
esc: () => fireEvent.keyDown(iframe, { key: 'Escape' }),
ctrlEnter: () => fireEvent.keyDown(iframe, { key: 'Enter', ctrlKey: true }),
ctrlAltBackspace: () => fireEvent.keyDown(iframe, { key: 'Backspace', ctrlKey: true, altKey: true }),
ctrlS: () => fireEvent.keyDown(iframe, { key: 'S', ctrlKey: true }),
ctrlM: () => fireEvent.keyDown(iframe, { key: 'M', ctrlKey: true }),
ctrlShftM: () => fireEvent.keyDown(iframe, { key: 'M', ctrlKey: true, shiftKey: true }),
ctrlShftA: () => fireEvent.keyDown(iframe, { key: 'A', ctrlKey: true, shiftKey: true }),
ctrlShftE: () => fireEvent.keyDown(iframe, { key: 'E', ctrlKey: true, shiftKey: true }),
ctrlShftX: () => fireEvent.keyDown(iframe, { key: 'X', ctrlKey: true, shiftKey: true }),
};
};
it('shortcut should not work when app shortcuts settings are disabled', async () => {
const { container, esc } = await setup(false);
esc();
const composer = container.querySelector('.composer-container');
expect(composer).not.toBe(null);
});
it('should close composer on escape', async () => {
const { container, esc } = await setup();
esc();
const composer = container.querySelector('.composer-container');
expect(composer).toBe(null);
});
it('should send on meta + enter', async () => {
const { ctrlEnter } = await setup();
const sendSpy = jest.fn(() => Promise.resolve({ Sent: {} }));
addApiMock(`mail/v4/messages/${ID}`, sendSpy, 'post');
ctrlEnter();
await waitForNotification('Message sent');
expect(sendSpy).toHaveBeenCalled();
});
it('should delete on meta + alt + enter', async () => {
const deleteSpy = jest.fn(() => Promise.resolve({}));
addApiMock(`mail/v4/messages/delete`, deleteSpy, 'put');
const { ctrlAltBackspace } = await setup();
ctrlAltBackspace();
await waitForNotification('Draft discarded');
expect(deleteSpy).toHaveBeenCalled();
});
it('should save on meta + S', async () => {
const saveSpy = jest.fn(() => Promise.resolve({}));
addApiMock(`mail/v4/messages/${ID}`, saveSpy, 'put');
const { ctrlS } = await setup();
ctrlS();
await waitForNotification('Draft saved');
expect(saveSpy).toHaveBeenCalled();
});
it('should open attachment on meta + shift + A', async () => {
const { getByTestId, ctrlShftA } = await setup();
const attachmentsButton = getByTestId('composer:attachment-button');
const attachmentSpy = jest.fn();
attachmentsButton.addEventListener('click', attachmentSpy);
ctrlShftA();
expect(attachmentSpy).toHaveBeenCalled();
});
it('should open encryption modal on meta + shift + E', async () => {
const { findByText, ctrlShftE } = await setup();
ctrlShftE();
await findByText('Encrypt message');
});
it('should open encryption modal on meta + shift + X', async () => {
const { findByText, ctrlShftX } = await setup();
ctrlShftX();
await findByText('Expiring message');
});
});
|
3,429 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.outsideEncryption.test.tsx | import { fireEvent, getByTestId as getByTestIdDefault } from '@testing-library/react';
import { act } from '@testing-library/react';
import { addHours } from 'date-fns';
import loudRejection from 'loud-rejection';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
addApiKeys,
addApiMock,
addKeysToAddressKeysCache,
clearAll,
generateKeys,
getDropdown,
render,
setFeatureFlags,
tick,
} from '../../../helpers/test/helper';
import { store } from '../../../logic/store';
import Composer from '../Composer';
import { AddressID, ID, fromAddress, prepareMessage, props, toAddress } from './Composer.test.helpers';
loudRejection();
const password = 'password';
describe('Composer outside encryption', () => {
beforeEach(() => {
clearAll();
});
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
clearAll();
await releaseCryptoProxy();
});
const setup = async () => {
setFeatureFlags('EORedesign', true);
addApiMock(`mail/v4/messages/${ID}`, () => ({ Message: {} }), 'put');
const fromKeys = await generateKeys('me', fromAddress);
addKeysToAddressKeysCache(AddressID, fromKeys);
addApiKeys(false, toAddress, []);
const composerID = Object.keys(store.getState().composers.composers)[0];
const result = await render(<Composer {...props} composerID={composerID} />);
return result;
};
it('should set outside encryption and display the expiration banner', async () => {
prepareMessage({
localID: ID,
data: { MIMEType: 'text/plain' as MIME_TYPES },
messageDocument: { plainText: '' },
});
const { getByTestId, getByText, container } = await setup();
const expirationButton = getByTestId('composer:password-button');
fireEvent.click(expirationButton);
await tick();
// modal is displayed and we can set a password
getByText('Encrypt message');
const passwordInput = getByTestId('encryption-modal:password-input');
fireEvent.change(passwordInput, { target: { value: password } });
const setEncryptionButton = getByTestId('modal-footer:set-button');
fireEvent.click(setEncryptionButton);
// The expiration banner is displayed
getByText(/This message will expire/);
// Trigger manual save to avoid unhandledPromiseRejection
await act(async () => {
fireEvent.keyDown(container, { key: 'S', ctrlKey: true });
});
});
it('should set outside encryption with a default expiration time', async () => {
// Message will expire tomorrow
prepareMessage({
localID: ID,
data: { MIMEType: 'text/plain' as MIME_TYPES },
messageDocument: { plainText: '' },
draftFlags: {
expiresIn: addHours(new Date(), 25), // expires in 25 hours
},
});
const { getByTestId, getByText } = await setup();
const expirationButton = getByTestId('composer:password-button');
fireEvent.click(expirationButton);
await tick();
// Modal and expiration date are displayed
getByText('Edit encryption');
getByText('Your message will expire tomorrow.');
});
it('should be able to edit encryption', async () => {
prepareMessage({
localID: ID,
data: { MIMEType: 'text/plain' as MIME_TYPES },
messageDocument: { plainText: '' },
});
const { getByTestId, getByText, container } = await setup();
const expirationButton = getByTestId('composer:password-button');
fireEvent.click(expirationButton);
await tick();
// modal is displayed and we can set a password
getByText('Encrypt message');
const passwordInput = getByTestId('encryption-modal:password-input');
fireEvent.change(passwordInput, { target: { value: password } });
const setEncryptionButton = getByTestId('modal-footer:set-button');
fireEvent.click(setEncryptionButton);
// Trigger manual save to avoid unhandledPromiseRejection
await act(async () => {
fireEvent.keyDown(container, { key: 'S', ctrlKey: true });
});
// Edit encryption
// Open the encryption dropdown
const encryptionDropdownButton = getByTestId('composer:encryption-options-button');
fireEvent.click(encryptionDropdownButton);
const dropdown = await getDropdown();
// Click on edit button
const editEncryptionButton = getByTestIdDefault(dropdown, 'composer:edit-outside-encryption');
await act(async () => {
fireEvent.click(editEncryptionButton);
});
const passwordInputAfterUpdate = getByTestId('encryption-modal:password-input') as HTMLInputElement;
const passwordValue = passwordInputAfterUpdate.value;
expect(passwordValue).toEqual(password);
// Trigger manual save to avoid unhandledPromiseRejection
await act(async () => {
fireEvent.keyDown(container, { key: 'S', ctrlKey: true });
});
});
it('should be able to remove encryption', async () => {
prepareMessage({
localID: ID,
data: { MIMEType: 'text/plain' as MIME_TYPES },
messageDocument: { plainText: '' },
});
const { getByTestId, getByText, queryByText, container } = await setup();
const expirationButton = getByTestId('composer:password-button');
fireEvent.click(expirationButton);
await tick();
// modal is displayed and we can set a password
getByText('Encrypt message');
const passwordInput = getByTestId('encryption-modal:password-input');
fireEvent.change(passwordInput, { target: { value: password } });
const setEncryptionButton = getByTestId('modal-footer:set-button');
fireEvent.click(setEncryptionButton);
// Edit encryption
// Open the encryption dropdown
const encryptionDropdownButton = getByTestId('composer:encryption-options-button');
fireEvent.click(encryptionDropdownButton);
const dropdown = await getDropdown();
// Click on remove button
const editEncryptionButton = getByTestIdDefault(dropdown, 'composer:remove-outside-encryption');
await act(async () => {
fireEvent.click(editEncryptionButton);
});
expect(queryByText(/This message will self-destruct on/)).toBe(null);
// Trigger manual save to avoid unhandledPromiseRejection
await act(async () => {
fireEvent.keyDown(container, { key: 'S', ctrlKey: true });
});
});
});
|
3,430 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.plaintext.test.tsx | import { fireEvent } from '@testing-library/react';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { clearAll, createDocument, waitForSpyCall } from '../../../helpers/test/helper';
import { render } from '../../../helpers/test/render';
import * as useSaveDraft from '../../../hooks/message/useSaveDraft';
import { store } from '../../../logic/store';
import Composer from '../Composer';
import { ID, prepareMessage, props } from './Composer.test.helpers';
jest.setTimeout(20000);
// In this test, switching from plaintext to html will trigger autosave
// But encryption and save requests are not the point of this test so it's easier and faster to mock that logic
jest.mock('../../../hooks/message/useSaveDraft', () => {
const saveSpy = jest.fn(() => Promise.resolve());
return {
saveSpy,
useCreateDraft: () => () => Promise.resolve(),
useSaveDraft: () => saveSpy,
useDeleteDraft: () => () => Promise.resolve(),
};
});
const saveSpy = (useSaveDraft as any).saveSpy as jest.Mock;
const mockSetContent = jest.fn();
jest.mock('@proton/components/components/editor/rooster/helpers/getRoosterEditorActions', () => {
let content = '';
return function () {
return {
getContent: () => {
return content;
},
setContent: (nextContent: string) => {
content = nextContent;
mockSetContent(nextContent);
},
focus: () => {},
};
};
});
describe('Composer switch plaintext <-> html', () => {
beforeEach(clearAll);
afterAll(clearAll);
it('should switch from plaintext to html content without loosing content', async () => {
const content = 'content';
prepareMessage({
localID: ID,
data: {
MIMEType: 'text/plain' as MIME_TYPES,
ToList: [],
},
messageDocument: {
plainText: content,
},
});
const composerID = Object.keys(store.getState().composers.composers)[0];
const { findByTestId } = await render(<Composer {...props} composerID={composerID} />);
const moreOptionsButton = await findByTestId('composer:more-options-button');
fireEvent.click(moreOptionsButton);
const toHtmlButton = await findByTestId('editor-to-html');
fireEvent.click(toHtmlButton);
await findByTestId('rooster-iframe');
await waitForSpyCall(mockSetContent);
expect(mockSetContent).toHaveBeenCalledWith(
`<div style="font-family: Arial, sans-serif; font-size: 14px;">${content}</div>`
);
// Wait for auto save
await waitForSpyCall(saveSpy);
});
it('should switch from html to plaintext content without loosing content', async () => {
const content = `
<div>content line 1<br><div>
<div>content line 2<br><div>
`;
prepareMessage({
localID: ID,
data: {
MIMEType: 'text/html' as MIME_TYPES,
ToList: [],
},
messageDocument: {
document: createDocument(content),
},
});
const composerID = Object.keys(store.getState().composers.composers)[0];
const { findByTestId } = await render(<Composer {...props} composerID={composerID} />);
const moreOptionsButton = await findByTestId('composer:more-options-button');
fireEvent.click(moreOptionsButton);
const toHtmlButton = await findByTestId('editor-to-plaintext');
fireEvent.click(toHtmlButton);
const textarea = (await findByTestId('editor-textarea')) as HTMLTextAreaElement;
expect(textarea.value).toBe('content line 1\ncontent line 2');
// Wait for auto save
await waitForSpyCall(saveSpy);
});
});
|
3,431 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.reply.test.tsx | import { fireEvent } from '@testing-library/react';
import { act } from '@testing-library/react';
import loudRejection from 'loud-rejection';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { MailSettings } from '@proton/shared/lib/interfaces';
import {
GeneratedKey,
addApiKeys,
addKeysToAddressKeysCache,
generateKeys,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from '../../../helpers/test/crypto';
import {
addApiMock,
addToCache,
clearAll,
createDocument,
decryptMessage,
decryptSessionKey,
minimalCache,
} from '../../../helpers/test/helper';
import { store } from '../../../logic/store';
import { ID, clickSend, prepareMessage, renderComposer, send } from './Composer.test.helpers';
loudRejection();
jest.setTimeout(20000);
const bodyContent = 'body content';
const blockquoteContent = 'blockquoteContent';
const content = `
${bodyContent}
<blockquote class="protonmail_quote" type="cite">
${blockquoteContent}
</blockquote>
`;
describe('Composer reply and forward', () => {
const AddressID = 'AddressID';
const fromAddress = '[email protected]';
const toAddress = '[email protected]';
let fromKeys: GeneratedKey;
let toKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
fromKeys = await generateKeys('me', fromAddress);
toKeys = await generateKeys('someone', toAddress);
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(() => {
addKeysToAddressKeysCache(AddressID, fromKeys);
});
afterEach(() => {
clearAll();
jest.useRealTimers();
});
it('send content with blockquote collapsed', async () => {
const { composerID } = prepareMessage({
messageDocument: { document: createDocument(content) },
data: { MIMEType: MIME_TYPES.DEFAULT },
});
minimalCache();
addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings);
addApiKeys(true, toAddress, [toKeys]);
// Will use update only on the wrong path, but it allows to have a "nice failure"
const updateSpy = jest.fn(() => Promise.reject(new Error('Should not update here')));
addApiMock(`mail/v4/messages/${ID}`, updateSpy, 'put');
const sendRequest = await send(composerID, false);
const packages = sendRequest.data.Packages;
const pack = packages['text/html'];
const address = pack.Addresses[toAddress];
const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys);
const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey);
expect(decryptResult.data).toContain(bodyContent);
expect(decryptResult.data).toContain(blockquoteContent);
});
it('send content with blockquote expanded', async () => {
prepareMessage({
messageDocument: { document: createDocument(content) },
data: { MIMEType: MIME_TYPES.DEFAULT },
});
minimalCache();
addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings);
addApiKeys(true, toAddress, [toKeys]);
const composerID = Object.keys(store.getState().composers.composers)[0];
const renderResult = await renderComposer(composerID, false);
const iframe = (await renderResult.findByTestId('rooster-iframe')) as HTMLIFrameElement;
const button = iframe.contentWindow?.document.getElementById('ellipsis') as HTMLButtonElement;
await act(async () => {
fireEvent.click(button);
});
// Will use update only on the wrong path, but it allows to have a "nice failure"
const updateSpy = jest.fn(() => Promise.reject(new Error('Should not update here')));
addApiMock(`mail/v4/messages/${ID}`, updateSpy, 'put');
const sendRequest = await clickSend(renderResult);
const packages = sendRequest.data.Packages;
const pack = packages['text/html'];
const address = pack.Addresses[toAddress];
const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys);
const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey);
expect(decryptResult.data).toContain(bodyContent);
expect(decryptResult.data).toContain(blockquoteContent);
});
});
|
3,432 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.schedule.test.tsx | import {
act,
fireEvent,
getByTestId as getByTestIdDefault,
getByText as getByTextDefault,
screen,
waitFor,
} from '@testing-library/react';
import { format, getUnixTime } from 'date-fns';
import { enUS } from 'date-fns/locale';
import loudRejection from 'loud-rejection';
import { MAILBOX_LABEL_IDS, MIME_TYPES } from '@proton/shared/lib/constants';
import { addDays, addMinutes } from '@proton/shared/lib/date-fns-utc';
import { Recipient } from '@proton/shared/lib/interfaces';
import { VIEW_MODE } from '@proton/shared/lib/mail/mailSettings';
import { getMinScheduleTime } from '../../../helpers/schedule';
import { addApiMock, setFeatureFlags } from '../../../helpers/test/api';
import { addToCache, minimalCache } from '../../../helpers/test/cache';
import { addApiKeys, clearAll, getDropdown } from '../../../helpers/test/helper';
import { render } from '../../../helpers/test/render';
import Composer from '../Composer';
import { ID, prepareMessage, props } from './Composer.test.helpers';
loudRejection();
const user = { Name: 'User', Address: '[email protected]' };
const setupTest = ({
hasPaidMail,
scheduledTotalCount = 4,
featureFlagActive = true,
showSpotlight = false,
}: {
hasPaidMail: boolean;
scheduledTotalCount?: number;
featureFlagActive?: boolean;
showSpotlight?: boolean;
}) => {
minimalCache();
addToCache('User', {
Email: 'Email',
DisplayName: 'DisplayName',
Name: 'Name',
hasPaidMail,
UsedSpace: 10,
MaxSpace: 100,
});
addToCache('MailSettings', { ViewMode: VIEW_MODE.SINGLE });
addToCache('MessageCounts', [{ LabelID: MAILBOX_LABEL_IDS.SCHEDULED, Unread: 1, Total: scheduledTotalCount }]);
setFeatureFlags('ScheduledSendFreemium', featureFlagActive);
setFeatureFlags('SpotlightScheduledSend', showSpotlight);
addApiKeys(false, user.Address, []);
};
const setupMessage = (Subject = '', ToList: Recipient[] = [], scheduledAt?: number) => {
return prepareMessage({
localID: ID,
data: { MIMEType: 'text/plain' as MIME_TYPES, Subject, ToList },
messageDocument: { plainText: '' },
...(scheduledAt ? { draftFlags: { scheduledAt } } : {}),
});
};
describe('Composer scheduled messages', () => {
beforeEach(() => {
clearAll();
addApiMock('core/v4/features/SpotlightScheduledSend/value', jest.fn, 'put');
});
afterEach(() => {
jest.useRealTimers();
});
afterAll(() => {
clearAll();
});
it('Should see the schedule send when FF is active', async () => {
const { composerID } = setupMessage('Subject', [user as Recipient]);
setupTest({ hasPaidMail: false, featureFlagActive: true });
const { queryByTestId } = await render(<Composer {...props} composerID={composerID} />, false);
expect(queryByTestId('composer:send-button')).toBeTruthy();
expect(queryByTestId('composer:scheduled-send:open-dropdown')).toBeTruthy();
});
it('Should not see the schedule send when FF is not active', async () => {
const { composerID } = setupMessage('Subject', [user as Recipient]);
setupTest({ hasPaidMail: false, featureFlagActive: false });
const { queryByTestId } = await render(<Composer {...props} composerID={composerID} />, false);
expect(queryByTestId('composer:send-button')).toBeTruthy();
expect(queryByTestId('composer:scheduled-send:open-dropdown')).toBeNull();
});
describe('Dropdown', () => {
it('Should contain default fields', async () => {
// Sunday 1 2023
const fakeNow = new Date(2023, 0, 1, 10, 0, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const { composerID } = setupMessage('Subject', [user as Recipient]);
setupTest({ hasPaidMail: false, featureFlagActive: true });
await render(<Composer {...props} composerID={composerID} />, false);
const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown');
fireEvent.click(dropdownButton);
expect(screen.queryByTestId('composer:schedule-send:dropdown-title')).toBeTruthy();
expect(screen.queryByTestId('composer:schedule-send:tomorrow')).toBeTruthy();
expect(screen.queryByTestId('composer:schedule-send:next-monday')).toBeTruthy();
expect(screen.queryByTestId('composer:schedule-send:custom')).toBeTruthy();
// Scheduled At should not be there
expect(screen.queryByTestId('composer:schedule-send-as-scheduled')).toBeNull();
expect(screen.queryByTestId('composer:schedule-send:tomorrow')).toHaveTextContent('January 2nd at 8:00 AM');
expect(screen.queryByTestId('composer:schedule-send:next-monday')).toHaveTextContent(
'January 2nd at 8:00 AM'
);
});
it.each`
expected | date
${'Tomorrow'} | ${new Date(2023, 0, 1, 7, 59, 0)}
${'Tomorrow'} | ${new Date(2023, 0, 1, 8, 0, 0)}
${'Tomorrow'} | ${new Date(2023, 0, 1, 10, 0, 0)}
${'In the morning'} | ${new Date(2023, 0, 1, 0, 0, 1)}
${'In the morning'} | ${new Date(2023, 0, 1, 2, 0, 0)}
${'In the morning'} | ${new Date(2023, 0, 1, 7, 30, 0)}
`('Should display "$expected" on "$date"', async ({ expected, date }) => {
jest.useFakeTimers().setSystemTime(date.getTime());
const { composerID } = setupMessage('Subject', [user as Recipient]);
setupTest({ hasPaidMail: false, featureFlagActive: true });
await render(<Composer {...props} composerID={composerID} />, false);
const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown');
fireEvent.click(dropdownButton);
expect(screen.queryByTestId('composer:schedule-send:tomorrow')).toHaveTextContent(expected);
});
it('Should contain "as scheduled" field when editing', async () => {
// Sunday 1 2023
const fakeNow = new Date(2023, 0, 1, 10, 0, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const { composerID } = setupMessage(
'Subject',
[user as Recipient],
getUnixTime(new Date(2023, 0, 5, 10, 0, 0))
);
setupTest({ hasPaidMail: false, featureFlagActive: true });
await render(<Composer {...props} composerID={composerID} />, false);
const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown');
fireEvent.click(dropdownButton);
const asScheduledButton = screen.getByTestId('composer:schedule-send-as-scheduled');
expect(asScheduledButton).toHaveTextContent('January 5th at 10:00 AM');
});
});
describe('Spotlight', () => {
it('Should be displayed on composer opening', async () => {
const { composerID } = setupMessage('Subject', [user as Recipient]);
setupTest({ hasPaidMail: false, featureFlagActive: true, showSpotlight: true });
await render(<Composer {...props} composerID={composerID} />, false);
let spotlightTitle = screen.queryByTestId('composer:schedule-send:spotlight-title');
expect(spotlightTitle).toBeTruthy();
});
it('Should be closed when dropdown is clicked', async () => {
const { composerID } = setupMessage('Subject', [user as Recipient]);
setupTest({ hasPaidMail: false, featureFlagActive: true, showSpotlight: true });
await render(<Composer {...props} composerID={composerID} />, false);
let spotlightTitle = screen.queryByTestId('composer:schedule-send:spotlight-title');
expect(spotlightTitle).toBeTruthy();
const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown');
fireEvent.click(dropdownButton);
await waitFor(() => {
expect(screen.queryByTestId('composer:schedule-send:spotlight-title')).toBeNull();
});
});
});
describe('Upsell modal', () => {
it('Should be displayed to free users', async () => {
const { composerID } = setupMessage('Subject', [user as Recipient]);
setupTest({ hasPaidMail: false, featureFlagActive: true, showSpotlight: false });
await render(<Composer {...props} composerID={composerID} />, false);
const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown');
fireEvent.click(dropdownButton);
const customDropdownButton = screen.getByTestId('composer:schedule-send:custom');
fireEvent.click(customDropdownButton);
expect(screen.queryByTestId('composer:schedule-send:upsell-modal')).toBeTruthy();
});
it('Should be hidden for paid users', async () => {
const { composerID } = setupMessage('Subject', [user as Recipient]);
setupTest({ hasPaidMail: true, featureFlagActive: true, showSpotlight: false });
await render(<Composer {...props} composerID={composerID} />, false);
const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown');
fireEvent.click(dropdownButton);
const customDropdownButton = screen.getByTestId('composer:schedule-send:custom');
fireEvent.click(customDropdownButton);
expect(screen.queryByTestId('composer:schedule-send:upsell-modal')).toBeNull();
});
});
it('should show a modal when the user reached scheduled messages limit', async () => {
const { composerID } = setupMessage('Subject', [user as Recipient]);
setupTest({ hasPaidMail: true, scheduledTotalCount: 100 });
const { getByTestId, getByText } = await render(<Composer {...props} composerID={composerID} />, false);
const sendActions = getByTestId('composer:send-actions');
const dropdownButton = getByTestIdDefault(sendActions, 'composer:scheduled-send:open-dropdown');
fireEvent.click(dropdownButton);
const dropdown = await getDropdown();
const scheduledSendButton = getByTestIdDefault(dropdown, 'composer:schedule-send:custom');
fireEvent.click(scheduledSendButton);
getByText(
'Too many messages waiting to be sent. Please wait until another message has been sent to schedule this one.'
);
});
it('should show a modal when trying to schedule a message without a recipient', async () => {
const { composerID } = setupMessage();
setupTest({ hasPaidMail: true });
const { getByTestId } = await render(<Composer {...props} composerID={composerID} />, false);
const sendActions = getByTestId('composer:send-actions');
const dropdownButton = getByTestIdDefault(sendActions, 'composer:scheduled-send:open-dropdown');
fireEvent.click(dropdownButton);
const dropdown = await getDropdown();
const scheduledSendButton = getByTestIdDefault(dropdown, 'composer:schedule-send:custom');
fireEvent.click(scheduledSendButton);
const modal = getByTestId('composer:modal:norecipients');
getByTextDefault(modal, 'Recipient missing');
});
it('Should show a modal when trying to schedule a message with a recipient and without subject', async () => {
const { composerID } = setupMessage('', [user as Recipient]);
setupTest({ hasPaidMail: true });
await render(<Composer {...props} composerID={composerID} />, false);
const sendActions = screen.getByTestId('composer:send-actions');
const dropdownButton = getByTestIdDefault(sendActions, 'composer:scheduled-send:open-dropdown');
fireEvent.click(dropdownButton);
const dropdown = await getDropdown();
const scheduledSendButton = getByTestIdDefault(dropdown, 'composer:schedule-send:custom');
fireEvent.click(scheduledSendButton);
const modal = await screen.findByTestId('composer:modal:nosubject');
getByTextDefault(modal, 'Subject missing');
});
it('should open schedule send modal and change date', async () => {
const { composerID } = setupMessage('Subject', [user as Recipient]);
setupTest({ hasPaidMail: true });
const dateSpy = jest.spyOn(Date, 'now').mockImplementation(() => new Date().setHours(12).valueOf());
const { getByTestId } = await render(<Composer {...props} composerID={composerID} />, false);
const sendActions = getByTestId('composer:send-actions');
const dropdownButton = getByTestIdDefault(sendActions, 'composer:scheduled-send:open-dropdown');
fireEvent.click(dropdownButton);
const dropdown = await getDropdown();
const scheduledSendButton = getByTestIdDefault(dropdown, 'composer:schedule-send:custom');
await act(async () => {
fireEvent.click(scheduledSendButton);
});
getByTestId('composer:schedule-send:custom-modal:title');
const dateInput = getByTestId('composer:schedule-date-input') as HTMLInputElement;
const timeInput = getByTestId('composer:schedule-time-input') as HTMLInputElement;
// Check if default date is Tomorrow, 8:00 AM
expect(dateInput.value).toEqual('Tomorrow');
expect(timeInput.value).toEqual('8:00 AM');
// format today date to change the input
const todayDate = format(new Date(Date.now()), 'PP', { locale: enUS });
// set date input to today
fireEvent.change(dateInput, { target: { value: todayDate } });
fireEvent.keyDown(dateInput, { key: 'Enter' });
// When choosing today with a time before the current time, the time should be set to the next available time
const nextAvailableTime = getMinScheduleTime(new Date()) ?? new Date();
const nextAvailableTimeFormatted = format(nextAvailableTime, 'p', { locale: enUS });
expect(dateInput.value).toEqual('Today');
expect(timeInput.value).toEqual(nextAvailableTimeFormatted);
const laterDate = format(addDays(new Date(Date.now()), 5), 'PP', { locale: enUS });
// set date input to 5 days later
fireEvent.change(dateInput, { target: { value: laterDate } });
fireEvent.keyDown(dateInput, { key: 'Enter' });
expect(dateInput.value).toEqual(laterDate);
expect(timeInput.value).toEqual(nextAvailableTimeFormatted);
dateSpy.mockRestore();
});
it('should disable schedule send button display if date is not valid', async () => {
const { composerID } = setupMessage('Subject', [user as Recipient]);
setupTest({ hasPaidMail: true });
const dateSpy = jest.spyOn(Date, 'now').mockImplementation(() => new Date().setHours(12).valueOf());
const { getByTestId } = await render(<Composer {...props} composerID={composerID} />, false);
const sendActions = getByTestId('composer:send-actions');
const dropdownButton = getByTestIdDefault(sendActions, 'composer:scheduled-send:open-dropdown');
fireEvent.click(dropdownButton);
const dropdown = await getDropdown();
const scheduledSendButton = getByTestIdDefault(dropdown, 'composer:schedule-send:custom');
await act(async () => {
fireEvent.click(scheduledSendButton);
});
const dateInput = getByTestId('composer:schedule-date-input') as HTMLInputElement;
const timeInput = getByTestId('composer:schedule-time-input') as HTMLInputElement;
const button = getByTestId('modal-footer:set-button') as HTMLButtonElement;
// set date input to the past
const previousDate = format(addDays(new Date(), -5), 'PP', { locale: enUS });
fireEvent.change(dateInput, { target: { value: previousDate } });
fireEvent.keyDown(dateInput, { key: 'Enter' });
expect(dateInput.value).toEqual(previousDate);
expect(timeInput.value).toEqual('8:00 AM');
expect(button.disabled).toBeTruthy();
// set date input too far in the future
const laterDate = format(addDays(new Date(), 91), 'PP', { locale: enUS });
fireEvent.change(dateInput, { target: { value: laterDate } });
fireEvent.keyDown(dateInput, { key: 'Enter' });
expect(dateInput.value).toEqual(laterDate);
expect(timeInput.value).toEqual('8:00 AM');
expect(button.disabled).toBeTruthy();
// set date input to today, and time in the past
const todayDate = format(Date.now(), 'PP', { locale: enUS });
const todayTime = format(addMinutes(new Date(Date.now()), -5), 'p', { locale: enUS });
fireEvent.change(dateInput, { target: { value: todayDate } });
fireEvent.keyDown(dateInput, { key: 'Enter' });
fireEvent.change(timeInput, { target: { value: todayTime } });
fireEvent.keyDown(timeInput, { key: 'Enter' });
expect(dateInput.value).toEqual('Today');
expect(timeInput.value).toEqual(todayTime);
expect(button.disabled).toBeTruthy();
dateSpy.mockRestore();
});
});
|
3,433 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.sending.test.tsx | import { fireEvent, getByTestId } from '@testing-library/react';
import loudRejection from 'loud-rejection';
import { ROOSTER_EDITOR_ID } from '@proton/components/components/editor/constants';
import { WorkerDecryptionResult } from '@proton/crypto/lib';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { SIGN } from '@proton/shared/lib/mail/mailSettings';
import { arrayToBase64 } from '../../../helpers/base64';
import { addApiContact } from '../../../helpers/test/contact';
import {
GeneratedKey,
addApiKeys,
addKeysToAddressKeysCache,
addKeysToUserKeysCache,
generateKeys,
releaseCryptoProxy,
setupCryptoProxyForTesting,
} from '../../../helpers/test/crypto';
import {
addApiMock,
addToCache,
clearAll,
createAttachment,
createDocument,
createEmbeddedImage,
createMessageImages,
decryptMessage,
decryptMessageMultipart,
decryptSessionKey,
minimalCache,
readSessionKey,
} from '../../../helpers/test/helper';
import { addAttachment } from '../../../logic/attachments/attachmentsActions';
import { store } from '../../../logic/store';
import { ID, clickSend, prepareMessage, renderComposer, send } from './Composer.test.helpers';
loudRejection();
jest.setTimeout(20000);
describe('Composer sending', () => {
const AddressID = 'AddressID';
const fromAddress = '[email protected]';
const toAddress = '[email protected]';
let fromKeys: GeneratedKey;
let secondFromKeys: GeneratedKey;
let toKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
fromKeys = await generateKeys('me', fromAddress);
secondFromKeys = await generateKeys('secondme', fromAddress);
toKeys = await generateKeys('someone', toAddress);
});
afterAll(async () => {
clearAll();
await releaseCryptoProxy();
});
beforeEach(() => {
clearAll();
addKeysToAddressKeysCache(AddressID, fromKeys);
});
describe('send plaintext', () => {
it('text/plain clear', async () => {
const { composerID, message } = prepareMessage({
localID: ID,
messageDocument: { plainText: 'test' },
data: { MIMEType: MIME_TYPES.PLAINTEXT },
});
addKeysToAddressKeysCache(message.data.AddressID, fromKeys);
const sendRequest = await send(composerID);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['text/plain'];
expect(pack).toBeDefined();
const sessionKey = readSessionKey(pack.BodyKey);
const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(message.messageDocument?.plainText);
});
it('text/plain self', async () => {
const { composerID, message } = prepareMessage({
messageDocument: { plainText: 'test' },
data: { MIMEType: MIME_TYPES.PLAINTEXT, ToList: [{ Name: '', Address: fromAddress }] },
});
minimalCache();
addToCache('Addresses', [
{
ID: message.data.AddressID,
Email: fromAddress,
Receive: 1,
HasKeys: true,
Keys: [
{
Primary: 1,
PrivateKey: fromKeys.privateKeyArmored,
PublicKey: fromKeys.publicKeyArmored,
},
],
},
]);
const sendRequest = await send(composerID, false);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['text/plain'];
const address = pack.Addresses[fromAddress];
const sessionKey = await decryptSessionKey(address.BodyKeyPacket, fromKeys.privateKeys);
expect(sessionKey).toBeDefined();
const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(message.messageDocument?.plainText);
});
it('text/plain pgp internal', async () => {
const { composerID, message } = prepareMessage({
messageDocument: { plainText: 'test' },
data: { MIMEType: MIME_TYPES.PLAINTEXT },
});
addApiKeys(true, toAddress, [toKeys]);
const sendRequest = await send(composerID);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['text/plain'];
const address = pack.Addresses[toAddress];
const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys);
expect(sessionKey).toBeDefined();
const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(message.messageDocument?.plainText);
});
it('multipart/mixed pgp external', async () => {
const { composerID, message } = prepareMessage({
messageDocument: { plainText: 'test' },
data: { MIMEType: MIME_TYPES.PLAINTEXT },
});
addApiKeys(false, toAddress, [toKeys]);
const sendRequest = await send(composerID);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['multipart/mixed'];
const address = pack.Addresses[toAddress];
const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys);
expect(sessionKey).toBeDefined();
const decryptResult = await decryptMessageMultipart(pack, toKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(message.messageDocument?.plainText);
expect(decryptResult.mimeType).toBe(message.data.MIMEType);
});
it('downgrade to plaintext due to contact setting', async () => {
const content = 'test';
const { composerID } = prepareMessage({
messageDocument: { document: createDocument(content) },
data: { MIMEType: MIME_TYPES.DEFAULT },
});
minimalCache();
addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings);
addKeysToUserKeysCache(fromKeys);
addApiContact({ contactID: 'ContactID', email: toAddress, mimeType: MIME_TYPES.PLAINTEXT }, fromKeys);
const sendRequest = await send(composerID, false);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['text/plain'];
expect(pack).toBeDefined();
const sessionKey = readSessionKey(pack.BodyKey);
const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(content);
});
it.skip('downgrade to plaintext and sign', async () => {
const content = 'test';
const { composerID } = prepareMessage({
messageDocument: { document: createDocument(content) },
data: { MIMEType: MIME_TYPES.DEFAULT },
});
minimalCache();
addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT, Sign: SIGN.ENABLED } as MailSettings);
addApiContact({ contactID: 'ContactID', email: toAddress, mimeType: MIME_TYPES.PLAINTEXT }, fromKeys);
const sendRequest = await send(composerID, false);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['text/plain'];
expect(pack).toBeDefined();
const sessionKey = readSessionKey(pack.BodyKey);
const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(content);
});
});
describe('send html', () => {
it('text/html clear', async () => {
const content = 'test';
const { composerID } = prepareMessage({
messageDocument: { document: createDocument(content) },
data: { MIMEType: MIME_TYPES.DEFAULT },
});
minimalCache();
addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings);
const sendRequest = await send(composerID, false);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['text/html'];
expect(pack).toBeDefined();
const sessionKey = readSessionKey(pack.BodyKey);
const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(content);
});
it('text/html pgp internal', async () => {
const content = 'test';
const { composerID } = prepareMessage({
messageDocument: { document: createDocument(content) },
data: { MIMEType: MIME_TYPES.DEFAULT },
});
minimalCache();
addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings);
addApiKeys(true, toAddress, [toKeys]);
const sendRequest = await send(composerID, false);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['text/html'];
const address = pack.Addresses[toAddress];
const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys);
expect(sessionKey).toBeDefined();
const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(content);
});
it('no downgrade even for default plaintext', async () => {
const content = 'test';
const { composerID } = prepareMessage({
messageDocument: { document: createDocument(content) },
data: { MIMEType: MIME_TYPES.DEFAULT },
});
minimalCache();
addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.PLAINTEXT } as MailSettings);
addApiKeys(true, toAddress, [toKeys]);
const sendRequest = await send(composerID, false);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['text/html'];
const address = pack.Addresses[toAddress];
const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys);
expect(sessionKey).toBeDefined();
const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(content);
});
it('multipart/mixed pgp external', async () => {
const content = 'test';
const document = window.document.createElement('div');
document.innerHTML = content;
const { composerID, message } = prepareMessage({
messageDocument: { document },
data: { MIMEType: MIME_TYPES.DEFAULT },
});
minimalCache();
addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings);
addApiKeys(false, toAddress, [toKeys]);
const sendRequest = await send(composerID, false);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['multipart/mixed'];
const address = pack.Addresses[toAddress];
const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys);
expect(sessionKey).toBeDefined();
const decryptResult = await decryptMessageMultipart(pack, toKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(content);
expect(decryptResult.mimeType).toBe(message.data.MIMEType);
});
});
describe('attachments', () => {
it('text/html with attachment', async () => {
const content = 'test';
const { attachment, sessionKey: generatedSessionKey } = await createAttachment(
{
ID: 'AttachmentID',
Name: 'image.png',
MIMEType: 'image/png',
},
fromKeys.publicKeys
);
const { composerID } = prepareMessage({
messageDocument: { document: createDocument(content) },
data: { MIMEType: MIME_TYPES.DEFAULT, Attachments: [attachment] },
});
minimalCache();
addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings);
addApiKeys(true, toAddress, [toKeys]);
const sendRequest = await send(composerID, false);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['text/html'];
const address = pack.Addresses[toAddress];
const AttachmentKeyPackets = address.AttachmentKeyPackets[attachment.ID as string];
const sessionKey = await decryptSessionKey(AttachmentKeyPackets, toKeys.privateKeys);
expect(arrayToBase64(sessionKey.data)).toBe(arrayToBase64(generatedSessionKey.data));
});
it('multipart/mixed with attachment', async () => {
const content = 'test';
const { attachment } = await createAttachment(
{
ID: 'AttachmentID',
Name: 'image.png',
MIMEType: 'image/png',
data: new Uint8Array(),
},
fromKeys.publicKeys
);
const { message, composerID } = prepareMessage({
messageDocument: { document: createDocument(content) },
data: {
MIMEType: MIME_TYPES.DEFAULT,
Attachments: [attachment],
},
});
addApiKeys(false, toAddress, [toKeys]);
store.dispatch(
addAttachment({
ID: attachment.ID as string,
attachment: { data: attachment.data } as WorkerDecryptionResult<Uint8Array>,
})
);
const sendRequest = await send(composerID);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['multipart/mixed'];
const address = pack.Addresses[toAddress];
const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys);
expect(sessionKey).toBeDefined();
const decryptResult = await decryptMessageMultipart(pack, toKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(content);
expect(decryptResult.mimeType).toBe(message.data.MIMEType);
expect(decryptResult.attachments.length).toBe(1);
expect(decryptResult.attachments[0].fileName).toBe(attachment.Name);
expect(decryptResult.attachments[0].contentType).toBe(attachment.MIMEType);
});
it('embedded image', async () => {
const cid = 'cid';
const imageUrl = 'https://localhost/some-generated-id';
const { attachment } = await createAttachment(
{
ID: 'AttachmentID',
Name: 'embedded.png',
MIMEType: 'image/png',
Headers: { 'content-id': cid },
},
fromKeys.publicKeys
);
const image = createEmbeddedImage(attachment);
const messageImages = createMessageImages([image]);
const content = `<img src="${imageUrl}" data-embedded-img="cid:${cid}">`;
const document = window.document.createElement('div');
document.innerHTML = content;
const { composerID } = prepareMessage({
messageDocument: { document },
messageImages,
data: { MIMEType: MIME_TYPES.DEFAULT, Attachments: [attachment] },
});
minimalCache();
addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings);
addApiKeys(true, toAddress, [toKeys]);
const sendRequest = await send(composerID, false);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['text/html'];
const address = pack.Addresses[toAddress];
const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys);
expect(sessionKey).toBeDefined();
const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(`<img src="cid:${cid}">`);
});
});
it('should not encrypt message with multiple keys', async () => {
const { message, composerID } = prepareMessage({
messageDocument: { plainText: 'test' },
data: { MIMEType: MIME_TYPES.PLAINTEXT },
});
addKeysToAddressKeysCache(message.data.AddressID, secondFromKeys);
addApiKeys(true, toAddress, [toKeys]);
const sendRequest = await send(composerID);
expect(sendRequest.data.ExpirationTime).toBeUndefined();
expect(sendRequest.data.ExpiresIn).toBeUndefined();
const packages = sendRequest.data.Packages;
const pack = packages['text/plain'];
const address = pack.Addresses[toAddress];
const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys);
const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey);
// Having 2 signatures here would meen we used both private keys to encrypt
// It's not "wrong", it works with OpenPGP and API accept it
// But other clients (Android, iOS, Bridge) don't support it so it's critical to use only one key
expect(decryptResult.signatures.length).toBe(1);
});
it('should ensure rooster content before sending', async () => {
const triggerEditorInput = (container: HTMLElement, content: string) => {
const iframe = getByTestId(container, 'rooster-iframe') as HTMLIFrameElement;
const editor = iframe.contentDocument?.getElementById(ROOSTER_EDITOR_ID);
if (editor) {
editor.innerHTML = content;
fireEvent.input(editor);
}
};
const content = 'test';
const editorContent = 'editor-test';
const { composerID } = prepareMessage({
messageDocument: { document: createDocument(content) },
data: { MIMEType: MIME_TYPES.DEFAULT },
});
minimalCache();
addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings);
addApiKeys(false, toAddress, []);
const renderResult = await renderComposer(composerID, false);
triggerEditorInput(renderResult.container, editorContent);
addApiMock(`mail/v4/messages/${ID}`, ({ data: { Message } }) => ({ Message }), 'put');
const sendRequest = await clickSend(renderResult);
const packages = sendRequest.data.Packages;
const pack = packages['text/html'];
const sessionKey = readSessionKey(pack.BodyKey);
const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey);
expect(decryptResult.data).toBe(editorContent);
});
});
|
3,435 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.verifySender.test.tsx | import { getByText as getByTextDefault } from '@testing-library/react';
import loudRejection from 'loud-rejection';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { Address, Recipient } from '@proton/shared/lib/interfaces';
import { addToCache, minimalCache } from '../../../helpers/test/cache';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
GeneratedKey,
addApiKeys,
addApiMock,
addKeysToAddressKeysCache,
clearAll,
generateKeys,
render,
} from '../../../helpers/test/helper';
import { messageID } from '../../message/tests/Message.test.helpers';
import Composer from '../Composer';
import { ID, prepareMessage, props, saveNow, toAddress } from './Composer.test.helpers';
loudRejection();
const name1 = 'Address 1';
const name2 = 'Address 2';
const address1 = '[email protected]';
const address2 = '[email protected]';
const addressID1 = 'AddressID1';
const addressID2 = 'AddressID2';
const addresses: Address[] = [
{
DisplayName: name1,
Email: address1,
ID: addressID1,
Send: 1,
Receive: 1,
Status: 1,
Order: 1,
} as Address,
{
DisplayName: name2,
Email: address2,
ID: addressID2,
Send: 0,
Receive: 0,
Status: 0,
Order: 2,
} as Address,
];
const user = {
Email: address1,
DisplayName: name1,
Name: name1,
hasPaidMail: true,
UsedSpace: 10,
MaxSpace: 100,
};
describe('Composer verify sender', () => {
let fromKeys: GeneratedKey;
beforeAll(async () => {
await setupCryptoProxyForTesting();
fromKeys = await generateKeys('me', address1);
});
afterAll(async () => {
clearAll();
await releaseCryptoProxy();
});
beforeEach(() => {
clearAll();
addKeysToAddressKeysCache(addressID1, fromKeys);
});
const setup = (sender: Recipient) => {
minimalCache();
addToCache('Addresses', addresses);
addToCache('User', user);
addApiKeys(false, toAddress, []);
addApiKeys(false, sender.Address, []);
const { composerID } = prepareMessage({
localID: ID,
data: {
ID: messageID,
MIMEType: MIME_TYPES.PLAINTEXT,
Sender: sender,
Flags: 12,
},
draftFlags: { isSentDraft: false, openDraftFromUndo: false },
messageDocument: { plainText: '' },
});
return composerID;
};
it('should display the sender address if the address is valid', async () => {
const sender = { Name: name1, Address: address1 } as Recipient;
const composerID = setup(sender);
const { findByTestId } = await render(<Composer {...props} composerID={composerID} />, false);
const fromField = await findByTestId('composer:from');
getByTextDefault(fromField, address1);
});
it('should display a modal and switch to default address when address is disabled', async () => {
addApiMock(`mail/v4/messages/${messageID}`, () => ({}));
const sender = { Name: name2, Address: address2 } as Recipient;
const composerID = setup(sender);
const { findByTestId, getByText, container } = await render(
<Composer {...props} composerID={composerID} />,
false
);
await saveNow(container);
// Sender is invalid, so we should see a modal
getByText('Sender changed');
// Then, the from field must have been replaced by the default address
const fromField = await findByTestId('composer:from');
getByTextDefault(fromField, address1);
});
it("should display a modal and switch to default address when address does not exist in user's addresses", async () => {
addApiMock(`mail/v4/messages/${messageID}`, () => ({}));
const sender = { Name: 'Address 3', Address: '[email protected]' } as Recipient;
const composerID = setup(sender);
const { findByTestId, container, getByText } = await render(
<Composer {...props} composerID={composerID} />,
false
);
await saveNow(container);
// Sender is invalid, so we should see a modal
getByText('Sender changed');
// Then, the from field must have been replaced by the default address
const fromField = await findByTestId('composer:from');
getByTextDefault(fromField, address1);
});
});
|
3,438 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/conversation/ConversationView.test.tsx | import { fireEvent, waitFor } from '@testing-library/react';
import { act } from '@testing-library/react';
import { wait } from '@proton/shared/lib/helpers/promise';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import range from '@proton/utils/range';
import { addApiKeys, addApiMock, assertFocus, clearAll, mockConsole, render, tick } from '../../helpers/test/helper';
import {
initialize as initializeConversation,
updateConversation,
} from '../../logic/conversations/conversationsActions';
import { ConversationState } from '../../logic/conversations/conversationsTypes';
import * as messageDraftActions from '../../logic/messages/draft/messagesDraftActions';
import { initialize as initializeMessage } from '../../logic/messages/read/messagesReadActions';
import { store } from '../../logic/store';
import { Conversation } from '../../models/conversation';
import { Breakpoints } from '../../models/utils';
import ConversationView from './ConversationView';
jest.setTimeout(20000);
describe('ConversationView', () => {
const props = {
hidden: false,
labelID: 'labelID',
conversationID: 'conversationID',
mailSettings: {} as MailSettings,
onBack: jest.fn(),
onCompose: jest.fn(),
breakpoints: {} as Breakpoints,
onMessageReady: jest.fn(),
columnLayout: true,
isComposerOpened: false,
containerRef: { current: null },
elementIDs: ['conversationID'],
loadingElements: false,
conversationMode: true,
};
const conversation = {
ID: props.conversationID,
Subject: 'conversation subject',
} as Conversation;
const message = {
ID: 'messageID',
Subject: 'message subject',
Sender: {},
Attachments: [] as any,
} as Message;
const conversationState = {
Conversation: conversation,
Messages: [message],
loadRetry: 0,
errors: {},
} as ConversationState;
const setup = async () => {
const result = await render(<ConversationView {...props} />);
const rerender = (newProps: Partial<typeof props> = {}) =>
result.rerender(<ConversationView {...props} {...newProps} />);
const messageElements = result.container.querySelectorAll<HTMLElement>(
'[data-shortcut-target="message-container"]'
);
const message = messageElements[0];
return {
...result,
rerender,
messageElements,
left: () => fireEvent.keyDown(message, { key: 'ArrowLeft' }),
down: () => fireEvent.keyDown(messageElements[0], { key: 'ArrowDown' }),
ctrlDown: () => fireEvent.keyDown(messageElements[0], { key: 'ArrowDown', ctrlKey: true }),
up: () => fireEvent.keyDown(messageElements[0], { key: 'ArrowUp' }),
ctrlUp: () => fireEvent.keyDown(messageElements[0], { key: 'ArrowUp', ctrlKey: true }),
enter: () => fireEvent.keyDown(messageElements[0], { key: 'Enter' }),
};
};
beforeEach(clearAll);
afterEach(() => {
jest.useRealTimers();
});
describe('Store / State management', () => {
it('should return store value', async () => {
store.dispatch(initializeConversation(conversationState));
store.dispatch(initializeMessage({ localID: message.ID, data: message }));
const { getByText } = await setup();
getByText(conversation.Subject as string);
});
it('should update value if store is updated', async () => {
store.dispatch(initializeConversation(conversationState));
store.dispatch(initializeMessage({ localID: message.ID, data: message }));
const { getByText, rerender } = await setup();
getByText(conversation.Subject as string);
const newSubject = 'other subject';
store.dispatch(
updateConversation({
ID: conversation.ID,
updates: { Conversation: { Subject: newSubject, ID: conversation.ID } },
})
);
await rerender();
getByText(newSubject);
});
it('should launch api request when needed', async () => {
const response = { Conversation: conversation, Messages: [message] };
addApiMock(`mail/v4/conversations/${conversation.ID}`, () => response);
const { getByText } = await setup();
getByText(conversation.Subject as string);
});
it('should change conversation when id change', async () => {
const conversation2 = { ID: 'conversationID2', Subject: 'other conversation subject' } as Conversation;
const conversationState2 = {
Conversation: conversation2,
Messages: [message],
loadRetry: 0,
errors: {},
} as ConversationState;
store.dispatch(initializeConversation(conversationState));
store.dispatch(initializeConversation(conversationState2));
const { getByText, rerender } = await setup();
getByText(conversation.Subject as string);
await rerender({ conversationID: conversation2.ID });
getByText(conversation2.Subject as string);
});
it('should reorder by date when old conversation draft is sent', async () => {
const conversationID = 'conversationID';
const makeMessage = (title: string, time: number): Message =>
({
ID: title,
Subject: title,
Time: time,
Sender: { Name: title, Address: `${title.replaceAll(' ', '')}@test.fr` },
Attachments: [] as any,
Flags: {},
ConversationID: conversationID,
} as Message);
const conversationState = {
Conversation: { ID: conversationID, Subject: 'a subject' },
Messages: [
makeMessage('test-message 1', new Date('2020-01-01').getTime()),
makeMessage('test-message 2', new Date('2020-01-02').getTime()),
makeMessage('test-message 3', new Date('2020-01-03').getTime()),
],
loadRetry: 0,
errors: {},
};
store.dispatch(initializeConversation(conversationState as ConversationState));
conversationState.Messages.forEach((message) => {
store.dispatch(initializeMessage({ localID: message.ID, data: message }));
});
const { getAllByText } = await setup();
const elements = getAllByText('test-message', { exact: false });
expect(elements[0].textContent).toContain('test-message 1');
expect(elements[1].textContent).toContain('test-message 2');
expect(elements[2].textContent).toContain('test-message 3');
// Consider message 2 is a draft and user sends it later
store.dispatch(messageDraftActions.sent(makeMessage('test-message 2', new Date('2020-01-04').getTime())));
// Wait for react to reflect store update
await wait(50);
// List order should change after draft is sent because of the date change
const elementsReordered = getAllByText('test-message ', { exact: false });
expect(elementsReordered[0].textContent).toContain('test-message 1');
expect(elementsReordered[1].textContent).toContain('test-message 3');
expect(elementsReordered[2].textContent).toContain('test-message 2');
});
});
describe('Auto reload', () => {
const waitForSpyCalls = (spy: jest.Mock, count: number) =>
waitFor(
() => {
expect(spy).toBeCalledTimes(count);
},
{ timeout: 20000 }
);
it('should reload a conversation if first request failed', async () => {
jest.useFakeTimers();
mockConsole();
const response = { Conversation: conversation, Messages: [message] };
const getSpy = jest.fn(() => {
if (getSpy.mock.calls.length === 1) {
const error = new Error();
error.name = 'NetworkError';
throw error;
}
return response;
});
addApiMock(`mail/v4/conversations/${conversation.ID}`, getSpy);
const { getByTestId, getByText, rerender } = await setup();
const header = getByTestId('conversation-header') as HTMLHeadingElement;
expect(header.getAttribute('class')).toContain('is-loading');
jest.advanceTimersByTime(5000);
await waitForSpyCalls(getSpy, 2);
await rerender();
expect(header.getAttribute('class')).not.toContain('is-loading');
getByText(conversation.Subject as string);
expect(getSpy).toHaveBeenCalledTimes(2);
jest.runAllTimers();
});
it('should show error banner after 4 attemps', async () => {
jest.useFakeTimers();
mockConsole();
const getSpy = jest.fn(() => {
const error = new Error();
error.name = 'NetworkError';
throw error;
});
addApiMock(`mail/v4/conversations/${conversation.ID}`, getSpy);
const { getByText } = await setup();
await act(async () => {
jest.advanceTimersByTime(5000);
await waitForSpyCalls(getSpy, 2);
jest.advanceTimersByTime(5000);
await waitForSpyCalls(getSpy, 3);
jest.advanceTimersByTime(5000);
await waitForSpyCalls(getSpy, 4);
});
getByText('Network error', { exact: false });
getByText('Try again');
expect(getSpy).toHaveBeenCalledTimes(4);
jest.runAllTimers();
});
it('should retry when using the Try again button', async () => {
const conversationState = {
Conversation: { ID: conversation.ID },
Messages: [],
loadRetry: 4,
errors: { network: [new Error()] },
} as ConversationState;
store.dispatch(initializeConversation(conversationState));
const response = { Conversation: conversation, Messages: [message] };
addApiMock(`mail/v4/conversations/${conversation.ID}`, () => response);
const { getByText, rerender } = await setup();
const tryAgain = getByText('Try again');
fireEvent.click(tryAgain);
await rerender();
getByText(conversation.Subject as string);
});
});
describe('Hotkeys', () => {
it('should focus item container on left', async () => {
store.dispatch(initializeConversation(conversationState));
const TestComponent = (props: any) => {
return (
<>
<div data-shortcut-target="item-container" tabIndex={-1}>
item container test
</div>
<ConversationView {...props} />
</>
);
};
const { container } = await render(<TestComponent {...props} />);
const itemContainer = container.querySelector('[data-shortcut-target="item-container"]');
const firstMessage = container.querySelector('[data-shortcut-target="message-container"]') as HTMLElement;
fireEvent.keyDown(firstMessage, { key: 'ArrowLeft' });
assertFocus(itemContainer);
});
it('should navigate through messages with up and down', async () => {
const messages = range(0, 10).map(
(i) =>
({
ID: `messageID${i}`,
Subject: `message subject ${i}`,
} as Message)
);
const conversationState = {
Conversation: conversation,
Messages: messages,
loadRetry: 0,
errors: {},
} as ConversationState;
store.dispatch(initializeConversation(conversationState));
const { messageElements, down, ctrlDown, up, ctrlUp } = await setup();
const isFocused = (element: HTMLElement) => element.dataset.hasfocus === 'true';
down();
expect(isFocused(messageElements[0])).toBe(true);
down();
expect(isFocused(messageElements[1])).toBe(true);
down();
expect(isFocused(messageElements[2])).toBe(true);
up();
expect(isFocused(messageElements[1])).toBe(true);
up();
expect(isFocused(messageElements[0])).toBe(true);
ctrlDown();
expect(isFocused(messageElements[9])).toBe(true);
ctrlUp();
expect(isFocused(messageElements[0])).toBe(true);
});
it('should open a message on enter', async () => {
const senderEmail = '[email protected]';
addApiKeys(false, senderEmail, []);
store.dispatch(initializeConversation(conversationState));
const messageMock = jest.fn(() => ({
Message: { ID: message.ID, Attachments: [], Sender: { Name: '', Address: senderEmail } },
}));
addApiMock(`mail/v4/messages/${message.ID}`, messageMock);
const { down, enter } = await setup();
down();
enter();
await tick();
expect(messageMock).toHaveBeenCalled();
});
});
});
|
3,450 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown/tests/CustomFilterDropdown.test.tsx | import { fireEvent } from '@testing-library/react';
import { act } from '@testing-library/react';
import { ConditionType } from '@proton/components/containers/filters/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { render, tick } from '../../../helpers/test/render';
import CustomFilterDropdown from '../CustomFilterDropdown';
const subject = 'Message subject';
const sender = '[email protected]';
const me = '[email protected]';
const message = {
Subject: subject,
Sender: { Address: sender },
ToList: [{ Address: me }],
} as Message;
const props = {
message: message,
onClose: jest.fn(),
onLock: jest.fn(),
};
describe('CustomFilterDropdown', () => {
it('should create a filter based on all options', async () => {
const { getByTestId } = await render(<CustomFilterDropdown {...props} />);
const subjectCheckbox = getByTestId(`custom-filter-checkbox:${ConditionType.SUBJECT}`) as HTMLInputElement;
const recipientCheckbox = getByTestId(`custom-filter-checkbox:${ConditionType.RECIPIENT}`) as HTMLInputElement;
const senderCheckbox = getByTestId(`custom-filter-checkbox:${ConditionType.SENDER}`) as HTMLInputElement;
const attachmentCheckbox = getByTestId(
`custom-filter-checkbox:${ConditionType.ATTACHMENTS}`
) as HTMLInputElement;
// By default all options are not checked
expect(subjectCheckbox.checked).toBeFalsy();
expect(recipientCheckbox.checked).toBeFalsy();
expect(senderCheckbox.checked).toBeFalsy();
expect(attachmentCheckbox.checked).toBeFalsy();
// Then we want to check them all (need to do it separately otherwise it fails)
await act(async () => {
fireEvent.click(subjectCheckbox);
await tick();
});
expect(subjectCheckbox.checked).toBeTruthy();
await act(async () => {
fireEvent.click(recipientCheckbox);
await tick();
});
expect(recipientCheckbox.checked).toBeTruthy();
await act(async () => {
fireEvent.click(senderCheckbox);
await tick();
});
expect(senderCheckbox.checked).toBeTruthy();
await act(async () => {
fireEvent.click(attachmentCheckbox);
await tick();
});
expect(attachmentCheckbox.checked).toBeTruthy();
// Open the filter modal
const applyButton = getByTestId('filter-dropdown:next-button');
fireEvent.click(applyButton);
/* TODO enable this part of the test when Sieve will be part of the monorepo
For now, we are forced to mock the library which is causing issue when we want to check prefilled condition from the modal
// Add a name to the filter so that we can pass to next step
const filterNameInput = screen.getByTestId('filter-modal:name-input');
await act(async () => {
fireEvent.change(filterNameInput, {target: {value: newFilterName}});
// input has a debounce, so we need to wait for the onChange
await wait(300);
});
const modalNextButton = screen.getByTestId('filter-modal:next-button');
fireEvent.click(modalNextButton);
// Check that conditions
const conditions = screen.queryAllByTestId(/filter-modal:condition-/)
expect(conditions.length).toEqual(4)
// Check that option 1 is Subject with the expected value
// Check that option 2 is Recipient with the expected value
// Check that option 2 is Sender with the expected value
// Check that option 2 is Attachments with the expected value
*/
});
});
|
3,451 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown/tests/LabelDropdown.test.tsx | import { fireEvent } from '@testing-library/react';
import { act, getByTestId as getByTestIdDefault, screen } from '@testing-library/react';
import { ACCENT_COLORS } from '@proton/shared/lib/colors';
import { LABEL_TYPE, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { wait } from '@proton/shared/lib/helpers/promise';
import { Label } from '@proton/shared/lib/interfaces';
import { addApiMock } from '../../../helpers/test/api';
import { addToCache, minimalCache } from '../../../helpers/test/cache';
import { render } from '../../../helpers/test/render';
import { MessageState } from '../../../logic/messages/messagesTypes';
import { initialize } from '../../../logic/messages/read/messagesReadActions';
import { store } from '../../../logic/store';
import { Breakpoints } from '../../../models/utils';
import { messageID } from '../../message/tests/Message.test.helpers';
import LabelDropdown from '../LabelDropdown';
const label1Name = 'Label1';
const label1ID = 'label-1-id';
const label2Name = 'Label2';
const label2ID = 'label-2-id';
const search = 'This label does not exists';
const props = {
selectedIDs: [messageID],
labelID: MAILBOX_LABEL_IDS.INBOX,
onClose: jest.fn(),
onLock: jest.fn(),
breakpoints: {} as Breakpoints,
};
const getMessage = (labelIDs: string[] = []) => {
return {
localID: messageID,
data: {
Sender: { Address: '[email protected]' },
ConversationID: 'conversationID',
LabelIDs: [MAILBOX_LABEL_IDS.INBOX, ...labelIDs],
},
} as MessageState;
};
describe('LabelDropdown', () => {
const setup = async (labelIDs: string[] = []) => {
minimalCache();
addToCache('Labels', [
{
ID: label1ID,
Name: label1Name,
Color: ACCENT_COLORS[0],
Type: LABEL_TYPE.MESSAGE_LABEL,
Path: label1Name,
} as Label,
{
ID: label2ID,
Name: label2Name,
Color: ACCENT_COLORS[1],
Type: LABEL_TYPE.MESSAGE_LABEL,
Path: label2Name,
} as Label,
]);
const message = getMessage(labelIDs);
store.dispatch(initialize(message));
const result = await render(<LabelDropdown {...props} />, false);
return result;
};
it("should display user's labels in the dropdown", async () => {
const { findAllByTestId, getByText } = await setup();
const labels = (await findAllByTestId(/label-dropdown:label-checkbox-/)) as HTMLInputElement[];
expect(labels.length).toBe(2);
// Checkboxes are present and unchecked
expect(labels[0].checked).toBe(false);
expect(labels[1].checked).toBe(false);
getByText(label1Name);
getByText(label2Name);
});
it('should label a message', async () => {
const apiMock = jest.fn(() => ({ UndoToken: 1000 }));
addApiMock(`mail/v4/messages/label`, apiMock);
const { getByTestId } = await setup();
const checkbox1 = getByTestId(`label-dropdown:label-checkbox-${label1Name}`) as HTMLInputElement;
// Check the first label
expect(checkbox1.checked).toBe(false);
await act(async () => {
fireEvent.click(checkbox1);
});
expect(checkbox1.checked).toBe(true);
// Apply the label
const applyButton = getByTestId('label-dropdown:apply');
await act(async () => {
fireEvent.click(applyButton);
});
// label call has been made
expect(apiMock).toHaveBeenCalled();
});
it('should unlabel a message', async () => {
const apiMock = jest.fn(() => ({ UndoToken: 1000 }));
addApiMock(`mail/v4/messages/unlabel`, apiMock);
const { getByTestId } = await setup([label1ID]);
const checkbox1 = getByTestId(`label-dropdown:label-checkbox-${label1Name}`) as HTMLInputElement;
// Check the first label
expect(checkbox1.checked).toBeTruthy();
await act(async () => {
fireEvent.click(checkbox1);
});
expect(checkbox1.checked).toBeFalsy();
// Apply the unlabel
const applyButton = getByTestId('label-dropdown:apply');
await act(async () => {
fireEvent.click(applyButton);
});
// label call has been made
expect(apiMock).toHaveBeenCalled();
});
it('should add the "also archive" option', async () => {
const apiMock = jest.fn(() => ({ UndoToken: 1000 }));
addApiMock(`mail/v4/messages/label`, apiMock);
const { getByTestId } = await setup();
const checkbox1 = getByTestId(`label-dropdown:label-checkbox-${label1Name}`) as HTMLInputElement;
// Check the first label
expect(checkbox1.checked).toBe(false);
await act(async () => {
fireEvent.click(checkbox1);
});
expect(checkbox1.checked).toBe(true);
// Check the also archive option
const alsoArchiveCheckbox = getByTestId('label-dropdown:also-archive') as HTMLInputElement;
await act(async () => {
fireEvent.click(alsoArchiveCheckbox);
});
// Apply the label
const applyButton = getByTestId('label-dropdown:apply');
await act(async () => {
fireEvent.click(applyButton);
});
// label calls have been made
// Call 1 => Apply label
// Call 2 => Apply archive
expect(apiMock).toHaveBeenCalledTimes(2);
expect((apiMock.mock.calls[0] as any[])[0]?.data?.LabelID).toEqual(label1ID);
expect((apiMock.mock.calls[1] as any[])[0]?.data?.LabelID).toEqual(MAILBOX_LABEL_IDS.ARCHIVE);
});
it('should add the "always label sender\'s email" option', async () => {
const labelApiMock = jest.fn(() => ({ UndoToken: 1000 }));
addApiMock(`mail/v4/messages/label`, labelApiMock);
const filterApiMock = jest.fn(() => ({ Filter: {} }));
addApiMock('mail/v4/filters', filterApiMock);
const { getByTestId } = await setup();
const checkbox1 = getByTestId(`label-dropdown:label-checkbox-${label1Name}`) as HTMLInputElement;
// Check the first label
expect(checkbox1.checked).toBe(false);
await act(async () => {
fireEvent.click(checkbox1);
});
expect(checkbox1.checked).toBe(true);
// Check the "always label sender's email" checkbox
const alwaysLabelCheckbox = getByTestId('label-dropdown:always-move') as HTMLInputElement;
await act(async () => {
fireEvent.click(alwaysLabelCheckbox);
});
// Apply the label
const applyButton = getByTestId('label-dropdown:apply');
await act(async () => {
fireEvent.click(applyButton);
});
expect(labelApiMock).toHaveBeenCalled();
expect(filterApiMock).toHaveBeenCalled();
});
it('should create a label from the button', async () => {
const { getByTestId, queryAllByTestId } = await setup();
// Search for a label which does not exist
const searchInput = getByTestId('label-dropdown:search-input');
await act(async () => {
fireEvent.change(searchInput, { target: { value: search } });
// input has a debounce, so we need to wait for the onChange
await wait(300);
});
// No more option are displayed
const labels = queryAllByTestId(/label-dropdown:label-checkbox-/) as HTMLInputElement[];
expect(labels.length).toBe(0);
// Click on the create label button
const createLabelButton = getByTestId('label-dropdown:add-label');
fireEvent.click(createLabelButton);
// Get the modal content
const createLabelModal = screen.getByRole('dialog', { hidden: true });
const labelModalNameInput = getByTestIdDefault(createLabelModal, 'label/folder-modal:name') as HTMLInputElement;
// Input is filled with the previous search content
expect(labelModalNameInput.value).toEqual(search);
});
it('should create a label from the option', async () => {
const { getByTestId, queryAllByTestId } = await setup();
// Search for a label which does not exist
const searchInput = getByTestId('label-dropdown:search-input');
await act(async () => {
fireEvent.change(searchInput, { target: { value: search } });
// input has a debounce, so we need to wait for the onChange
await wait(300);
});
// No more option are displayed
const labels = queryAllByTestId(/label-dropdown:label-checkbox-/) as HTMLInputElement[];
expect(labels.length).toBe(0);
// Click on the create label option
const createLabelOption = getByTestId('label-dropdown:create-label-option');
fireEvent.click(createLabelOption);
// Get the modal content
const createLabelModal = screen.getByRole('dialog', { hidden: true });
const labelModalNameInput = getByTestIdDefault(createLabelModal, 'label/folder-modal:name') as HTMLInputElement;
// Input is filled with the previous search content
expect(labelModalNameInput.value).toEqual(search);
});
});
|
3,452 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown/tests/MoveDropdownd.test.tsx | import { act, fireEvent, getByTestId as getByTestIdDefault, screen } from '@testing-library/react';
import { ACCENT_COLORS } from '@proton/shared/lib/colors';
import { LABEL_TYPE, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { wait } from '@proton/shared/lib/helpers/promise';
import { Label } from '@proton/shared/lib/interfaces';
import { addApiMock } from '../../../helpers/test/api';
import { addToCache, minimalCache } from '../../../helpers/test/cache';
import { render } from '../../../helpers/test/render';
import { MessageState } from '../../../logic/messages/messagesTypes';
import { initialize } from '../../../logic/messages/read/messagesReadActions';
import { store } from '../../../logic/store';
import { Breakpoints } from '../../../models/utils';
import { messageID } from '../../message/tests/Message.test.helpers';
import MoveDropdown from '../MoveDropdown';
const folder1Name = 'Folder1';
const folder1ID = 'folder-1-id';
const folder2Name = 'Folder2';
const folder2ID = 'folder-2-id';
const search = 'This label does not exists';
const props = {
selectedIDs: [messageID],
labelID: MAILBOX_LABEL_IDS.INBOX,
onClose: jest.fn(),
onLock: jest.fn(),
breakpoints: {} as Breakpoints,
};
const getMessage = (labelIDs: string[] = []) => {
return {
localID: messageID,
data: {
Sender: { Address: '[email protected]' },
ConversationID: 'conversationID',
LabelIDs: [MAILBOX_LABEL_IDS.INBOX, ...labelIDs],
},
} as MessageState;
};
describe('MoveDropdown', () => {
const setup = async (labelIDs: string[] = []) => {
minimalCache();
addToCache('Labels', [
{
ID: folder1ID,
Name: folder1Name,
Color: ACCENT_COLORS[0],
Type: LABEL_TYPE.MESSAGE_FOLDER,
Path: folder1Name,
} as Label,
{
ID: folder2ID,
Name: folder2Name,
Color: ACCENT_COLORS[1],
Type: LABEL_TYPE.MESSAGE_FOLDER,
Path: folder2Name,
} as Label,
]);
const message = getMessage(labelIDs);
store.dispatch(initialize(message));
const result = await render(<MoveDropdown {...props} />, false);
return result;
};
it("should display user's folders in the dropdowm", async () => {
const { findAllByTestId, getAllByText } = await setup();
const folders = (await findAllByTestId(/label-dropdown:folder-radio-/)) as HTMLInputElement[];
// Should contain default folders (Inbox, Archive, Spam, Trash) + custom folders
expect(folders.length).toBe(6);
expect(folders[0].checked).toBe(false);
expect(folders[1].checked).toBe(false);
getAllByText(folder1Name);
getAllByText(folder2Name);
});
it('should move to a folder', async () => {
const apiMock = jest.fn(() => ({ UndoToken: 1000 }));
addApiMock(`mail/v4/messages/label`, apiMock);
const { getByTestId } = await setup();
const radio1 = getByTestId(`label-dropdown:folder-radio-${folder1Name}`) as HTMLInputElement;
// Check the first radio
expect(radio1.checked).toBe(false);
await act(async () => {
fireEvent.click(radio1);
});
expect(radio1.checked).toBe(true);
// Apply the label
const applyButton = getByTestId('move-dropdown:apply');
await act(async () => {
fireEvent.click(applyButton);
});
// label call has been made
expect(apiMock).toHaveBeenCalled();
});
it('should create a folder from the button', async () => {
const { getByTestId, queryAllByTestId } = await setup();
// Search for a label which does not exist
const searchInput = getByTestId('folder-dropdown:search-folder');
await act(async () => {
fireEvent.change(searchInput, { target: { value: search } });
// input has a debounce, so we need to wait for the onChange
await wait(300);
});
// No more option are displayed
const labels = queryAllByTestId(/label-dropdown:folder-radio-/) as HTMLInputElement[];
expect(labels.length).toBe(0);
// Click on the create label button
const createLabelButton = getByTestId('folder-dropdown:add-folder');
fireEvent.click(createLabelButton);
// Get the modal content
const createLabelModal = screen.getByRole('dialog', { hidden: true });
const labelModalNameInput = getByTestIdDefault(createLabelModal, 'label/folder-modal:name') as HTMLInputElement;
// Input is filled with the previous search content
expect(labelModalNameInput.value).toEqual(search);
});
it('should create a folder from the option', async () => {
const { getByTestId, queryAllByTestId } = await setup();
// Search for a label which does not exist
const searchInput = getByTestId('folder-dropdown:search-folder');
await act(async () => {
fireEvent.change(searchInput, { target: { value: search } });
// input has a debounce, so we need to wait for the onChange
await wait(300);
});
// No more option are displayed
const labels = queryAllByTestId(/label-dropdown:folder-radio-/) as HTMLInputElement[];
expect(labels.length).toBe(0);
// Click on the create label option
const createLabelOption = getByTestId('folder-dropdown:create-folder-option');
fireEvent.click(createLabelOption);
// Get the modal content
const createLabelModal = screen.getByRole('dialog', { hidden: true });
const labelModalNameInput = getByTestIdDefault(createLabelModal, 'label/folder-modal:name') as HTMLInputElement;
// Input is filled with the previous search content
expect(labelModalNameInput.value).toEqual(search);
});
});
|
3,453 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/EORedirect.test.tsx | import { EOGetHistory, EORender } from '../../helpers/test/eo/EORender';
import { EOClearAll } from '../../helpers/test/eo/helpers';
import { MessageState } from '../../logic/messages/messagesTypes';
import EORedirect from './EORedirect';
describe('Encrypted Outside Redirection', () => {
afterEach(EOClearAll);
const getProps = (id?: string) => {
return {
id: id ? id : undefined,
isStoreInitialized: true,
messageState: {} as MessageState,
setSessionStorage: jest.fn(),
};
};
it('should redirect to Unlock page from /message if no id', async () => {
const props = getProps();
await EORender(<EORedirect {...props} />, '/eo/message/:id');
// Redirects to /eo
const history = EOGetHistory();
expect(history.location.pathname).toBe(`/eo`);
});
it('should redirect to Unlock page from /reply if no id', async () => {
const props = getProps();
await EORender(<EORedirect {...props} />, '/eo/reply/:id');
// Redirects to /eo
const history = EOGetHistory();
expect(history.location.pathname).toBe(`/eo`);
});
it('should redirect to Unlock page from /message if invalid id', async () => {
const props = getProps('invalidID');
await EORender(<EORedirect {...props} />, '/eo/message/:id');
// Redirects to /eo
const history = EOGetHistory();
expect(history.location.pathname).toBe(`/eo`);
});
it('should redirect to Unlock page from /reply if invalid id', async () => {
const props = getProps('invalidID');
await EORender(<EORedirect {...props} />, '/eo/reply/:id');
// Redirects to /eo
const history = EOGetHistory();
expect(history.location.pathname).toBe(`/eo`);
});
});
|
3,455 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/EOExpirationTime.test.tsx | import { add, addHours, addMinutes, addSeconds, getUnixTime } from 'date-fns';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { clearAll, render, tick } from '../../../helpers/test/helper';
import EOExpirationTime from './EOExpirationTime';
describe('EOExpirationTime', () => {
const date = new Date(2023, 0, 1, 10, 0, 1);
const seconds = 50;
beforeAll(() => {
jest.useFakeTimers();
});
beforeEach(() => {
jest.clearAllTimers();
jest.setSystemTime(date);
});
afterAll(() => {
jest.useRealTimers();
});
afterEach(() => {
jest.clearAllMocks();
clearAll();
});
const setup = async (ExpirationTime: number) => {
const result = await render(
<EOExpirationTime message={{ localID: 'localID', data: { ExpirationTime } as Message }} />
);
const rerender = async (ExpirationTime: number) => {
await result.rerender(
<EOExpirationTime message={{ localID: 'localID', data: { ExpirationTime } as Message }} />
);
return result.queryByTestId('expiration-banner');
};
return { banner: result.queryByTestId('expiration-banner'), rerender };
};
it('should display expiration banner as button and expected content', async () => {
// Set expiration time to two days
const daysInSeconds = getUnixTime(
add(date, {
hours: 23,
minutes: 59,
seconds: 59,
})
);
const result = await setup(daysInSeconds);
let { banner } = result;
// The message will expire in 1 day 23h 59min 59s, so we display "Expires in less than 24 hours"
expect(banner?.textContent).toBe('Expires in less than 24 hours');
// The message will expire in 0 day 3h 59min 59s, so we display "Expires in less than 4 hours"
const hoursInSeconds1 = getUnixTime(addHours(date, 4));
banner = await result.rerender(hoursInSeconds1);
await tick();
expect(banner?.textContent).toBe('Expires in less than 4 hours');
// The message will expire in 0 day 1h 59min 59s, so we display "Expires in less than 2 hour"
const hoursInSeconds2 = getUnixTime(addHours(date, 2));
banner = await result.rerender(hoursInSeconds2);
await tick();
expect(banner?.textContent).toBe('Expires in less than 2 hours');
// The message will expire in 0 day 0h 1min 59s, so we display "Expires in 2 minutes"
const minutesInSeconds = getUnixTime(addMinutes(date, 2));
banner = await result.rerender(minutesInSeconds);
await tick();
expect(banner?.textContent).toBe('Expires in 2 minutes');
// The message will expire in 0 day 0h 0min Xs, so we display "Expires in less than X seconds"
banner = await result.rerender(getUnixTime(addSeconds(date, seconds)));
const value = Number(/\d+/.exec(banner?.textContent || '')?.[0]);
await tick();
expect(value).toBeLessThanOrEqual(seconds);
});
});
|
3,464 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/tests/ViewEOMessage.attachments.test.tsx | import { fireEvent, waitFor, within } from '@testing-library/react';
import humanSize from '@proton/shared/lib/helpers/humanSize';
import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import { assertIcon } from '../../../../helpers/test/assertion';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto';
import { EOClearAll } from '../../../../helpers/test/eo/helpers';
import { tick } from '../../../../helpers/test/render';
import { setup } from './ViewEOMessage.test.helpers';
describe('Encrypted Outside message attachments', () => {
const cid = 'cid';
const attachment1 = {
ID: 'id1',
Name: 'attachment-name-unknown',
Size: 100,
Headers: { 'content-id': cid },
nameSplitStart: 'attachment-name-unkn',
nameSplitEnd: 'own',
};
const attachment2 = {
ID: 'id2',
Name: 'attachment-name-pdf.pdf',
Size: 200,
MIMEType: 'application/pdf',
nameSplitStart: 'attachment-name-p',
nameSplitEnd: 'df.pdf',
};
const attachment3 = {
ID: 'id3',
Name: 'attachment-name-png.png',
Size: 300,
MIMEType: 'image/png',
// Allow to skip actual download of the file content
Preview: {
data: [],
filename: 'preview',
signatures: [],
verified: VERIFICATION_STATUS.NOT_SIGNED,
},
nameSplitStart: 'attachment-name-p',
nameSplitEnd: 'ng.png',
Headers: { 'content-id': 'cid-embedded', 'content-disposition': 'inline' },
};
const Attachments = [attachment1, attachment2, attachment3];
const NumAttachments = Attachments.length;
const icons = ['md-unknown', 'md-pdf', 'md-image'];
const totalSize = Attachments.map((attachment) => attachment.Size).reduce((acc, size) => acc + size, 0);
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(EOClearAll);
it('should show EO attachments with their correct icon', async () => {
const { getAllByTestId } = await setup({ attachments: Attachments, numAttachments: NumAttachments });
const items = await waitFor(() => getAllByTestId('attachment-item'));
expect(items.length).toBe(NumAttachments);
for (let i = 0; i < NumAttachments; i++) {
const { getByText, getByTestId } = within(items[i]);
getByText(Attachments[i].nameSplitStart);
getByText(Attachments[i].nameSplitEnd);
const attachmentSizeText = getByTestId('attachment-item:size').textContent;
expect(attachmentSizeText).toEqual(humanSize(Attachments[i].Size));
assertIcon(items[i].querySelector('svg'), icons[i], undefined, 'mime');
}
});
it('should show global size and counters', async () => {
const body = '<div><img src="cid:cid-embedded"/></div>';
const { getByTestId } = await setup({ attachments: Attachments, numAttachments: NumAttachments, body: body });
const header = await waitFor(() => getByTestId('attachment-list:header'));
expect(header.textContent).toMatch(String(totalSize));
expect(header.textContent).toMatch(/2\s*files/);
expect(header.textContent).toMatch(/1\s*embedded/);
});
it('should open preview when clicking', async () => {
window.URL.createObjectURL = jest.fn();
const { getAllByTestId } = await setup({ attachments: Attachments, numAttachments: NumAttachments });
const items = await waitFor(() => getAllByTestId('attachment-item'));
const itemButton = items[2].querySelectorAll('button')[1];
fireEvent.click(itemButton);
await tick();
const preview = document.querySelector('.file-preview');
expect(preview).toBeDefined();
expect(preview?.textContent).toMatch(new RegExp(attachment3.Name));
expect(preview?.textContent).toMatch(/3of3/);
});
});
|
3,465 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/tests/ViewEOMessage.banners.test.tsx | import { screen, waitFor } from '@testing-library/react';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto';
import { EOClearAll } from '../../../../helpers/test/eo/helpers';
import { setup } from './ViewEOMessage.test.helpers';
describe('Encrypted Outside message banners', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(EOClearAll);
it('should show EO expiration banner', async () => {
const ExpirationTime = new Date().getTime() / 1000 + 1000;
await setup({ expirationTime: ExpirationTime });
const banner = await waitFor(() => screen.findByTestId('expiration-banner'));
expect(banner.textContent).toMatch(/Expires in/);
});
});
|
3,466 | 0 | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message | petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/tests/ViewEOMessage.encryption.test.tsx | import { findByText, waitFor } from '@testing-library/react';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto';
import { EOBody, EOClearAll, EOSubject } from '../../../../helpers/test/eo/helpers';
import { getIframeRootDiv } from '../../../message/tests/Message.test.helpers';
import { setup } from './ViewEOMessage.test.helpers';
describe('Encrypted Outside message view encryption', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
afterEach(EOClearAll);
it('should decrypt and render a EO message', async () => {
const { getByText, container } = await setup();
await waitFor(() => getByText(EOSubject));
const iframeContent = await getIframeRootDiv(container);
await findByText(iframeContent, EOBody);
});
});
|
Subsets and Splits