Fixed file structure of test utils

pull/1184/head
Mikunj 5 years ago
parent fe7aaa0aaa
commit cbc3518f04

@ -1,6 +1,6 @@
import { expect } from 'chai';
import * as sinon from 'sinon';
import { TestUtils, timeout } from '../../test-utils';
import { TestUtils } from '../../test-utils';
import { PairingAuthorisation } from '../../../../js/modules/data';
import { MultiDeviceProtocol } from '../../../session/protocols';
import { PubKey } from '../../../session/types';
@ -183,7 +183,7 @@ describe('MultiDeviceProtocol', () => {
it('should not fetch if the refresh delay has not been met', async () => {
await MultiDeviceProtocol.fetchPairingAuthorisationsIfNeeded(device);
await timeout(100);
await TestUtils.timeout(100);
await MultiDeviceProtocol.fetchPairingAuthorisationsIfNeeded(device);
expect(fetchPairingAuthorisationStub.callCount).to.equal(
1,
@ -202,21 +202,21 @@ describe('MultiDeviceProtocol', () => {
it('should fetch again if something went wrong while fetching', async () => {
fetchPairingAuthorisationStub.throws(new Error('42'));
await MultiDeviceProtocol.fetchPairingAuthorisationsIfNeeded(device);
await timeout(100);
await TestUtils.timeout(100);
await MultiDeviceProtocol.fetchPairingAuthorisationsIfNeeded(device);
expect(fetchPairingAuthorisationStub.callCount).to.equal(2);
});
it('should fetch only once if called rapidly', async () => {
fetchPairingAuthorisationStub.callsFake(async () => {
await timeout(200);
await TestUtils.timeout(200);
return [];
});
void MultiDeviceProtocol.fetchPairingAuthorisationsIfNeeded(device);
await timeout(10);
await TestUtils.timeout(10);
void MultiDeviceProtocol.fetchPairingAuthorisationsIfNeeded(device);
await timeout(200);
await TestUtils.timeout(200);
expect(fetchPairingAuthorisationStub.callCount).to.equal(1);
});

@ -1,7 +1,7 @@
import { expect } from 'chai';
import { SessionProtocol } from '../../../session/protocols';
import * as sinon from 'sinon';
import { Stubs, TestUtils, timeout } from '../../test-utils';
import { Stubs, TestUtils } from '../../test-utils';
import { UserUtil } from '../../../util';
import { SessionRequestMessage } from '../../../session/messages/outgoing';
import { TextEncoder } from 'util';
@ -219,7 +219,7 @@ describe('SessionProtocol', () => {
expect(SessionProtocol.getProcessedSessionsTimestamp())
.to.have.property('deviceid')
.to.be.approximately(Date.now(), 5);
await timeout(5);
await TestUtils.timeout(5);
const oldTimestamp = SessionProtocol.getProcessedSessionsTimestamp()
.deviceid;
await SessionProtocol.onSessionRequestProcessed(pubkey);
@ -291,7 +291,7 @@ describe('SessionProtocol', () => {
it('protocol: shouldProcessSessionRequest returns false if there is a more recent sent but a less recent processed', async () => {
await SessionProtocol.sendSessionRequest(resetMessage, pubkey); // adds a Date.now() entry
await timeout(100);
await TestUtils.timeout(100);
await SessionProtocol.onSessionRequestProcessed(pubkey); // adds a Date.now() entry 100ms after
expect(
@ -304,7 +304,7 @@ describe('SessionProtocol', () => {
it('protocol: shouldProcessSessionRequest returns false if there is a more recent processed but a less recent sent', async () => {
await SessionProtocol.onSessionRequestProcessed(pubkey); // adds a Date.now() entry
await timeout(100);
await TestUtils.timeout(100);
await SessionProtocol.sendSessionRequest(resetMessage, pubkey); // adds a Date.now() entry 100ms after
expect(

@ -1,7 +1,7 @@
import chai from 'chai';
import { v4 as uuid } from 'uuid';
import { JobQueue } from '../../../session/utils/JobQueue';
import { timeout } from '../../test-utils';
import { TestUtils } from '../../test-utils';
// tslint:disable-next-line: no-require-imports no-var-requires
const chaiAsPromised = require('chai-as-promised');
@ -16,7 +16,7 @@ describe('JobQueue', () => {
const id = 'jobId';
assert.isFalse(queue.has(id));
const promise = queue.addWithId(id, async () => timeout(100));
const promise = queue.addWithId(id, async () => TestUtils.timeout(100));
assert.isTrue(queue.has(id));
await promise;
assert.isFalse(queue.has(id));
@ -33,7 +33,7 @@ describe('JobQueue', () => {
const queue = new JobQueue();
const mapper = async ([value, ms]: Array<number>): Promise<number> =>
queue.addWithId(uuid(), async () => {
await timeout(ms);
await TestUtils.timeout(ms);
return value;
});
@ -55,12 +55,12 @@ describe('JobQueue', () => {
it('should return the result of the job', async () => {
const queue = new JobQueue();
const success = queue.addWithId(uuid(), async () => {
await timeout(100);
await TestUtils.timeout(100);
return 'success';
});
const failure = queue.addWithId(uuid(), async () => {
await timeout(100);
await TestUtils.timeout(100);
throw new Error('failed');
});
@ -72,7 +72,7 @@ describe('JobQueue', () => {
const queue = new JobQueue();
const first = queue.addWithId(uuid(), () => 'first');
const second = queue.addWithId(uuid(), async () => {
await timeout(100);
await TestUtils.timeout(100);
return 'second';
});
@ -89,7 +89,7 @@ describe('JobQueue', () => {
const queue = new JobQueue();
const id = uuid();
const job = async () => {
await timeout(100);
await TestUtils.timeout(100);
return 'job1';
};
@ -104,13 +104,15 @@ describe('JobQueue', () => {
const queue = new JobQueue();
const id = uuid();
const successfullJob = queue.addWithId(id, async () => timeout(100));
const successfullJob = queue.addWithId(id, async () =>
TestUtils.timeout(100)
);
assert.isTrue(queue.has(id));
await successfullJob;
assert.isFalse(queue.has(id));
const failJob = queue.addWithId(id, async () => {
await timeout(100);
await TestUtils.timeout(100);
throw new Error('failed');
});
assert.isTrue(queue.has(id));

@ -1,5 +1,4 @@
import * as TestUtils from './testUtils';
import * as TestUtils from './utils';
import * as Stubs from './stubs';
export * from './timeout';
export { TestUtils, Stubs };

@ -1,126 +0,0 @@
import * as sinon from 'sinon';
import * as crypto from 'crypto';
import * as window from '../../window';
import * as DataShape from '../../../js/modules/data';
import { v4 as uuid } from 'uuid';
import { PubKey } from '../../../ts/session/types';
import {
ChatMessage,
ClosedGroupChatMessage,
OpenGroupMessage,
} from '../../session/messages/outgoing';
import { OpenGroup } from '../../session/types/OpenGroup';
const globalAny: any = global;
const sandbox = sinon.createSandbox();
// We have to do this in a weird way because Data uses module.exports
// which doesn't play well with sinon or ImportMock
// tslint:disable-next-line: no-require-imports no-var-requires
const Data = require('../../../js/modules/data');
type DataFunction = typeof DataShape;
/**
* Stub a function inside Data.
*
* Note: This uses a custom sandbox.
* Please call `restoreStubs()` or `stub.restore()` to restore original functionality.
*/
export function stubData<K extends keyof DataFunction>(fn: K): sinon.SinonStub {
return sandbox.stub(Data, fn);
}
type WindowValue<K extends keyof Window> = Partial<Window[K]> | undefined;
/**
* Stub a window object.
*
* Note: This uses a custom sandbox.
* Please call `restoreStubs()` or `stub.restore()` to restore original functionality.
*/
export function stubWindow<K extends keyof Window>(
fn: K,
value: WindowValue<K>
) {
// tslint:disable-next-line: no-typeof-undefined
if (typeof globalAny.window === 'undefined') {
globalAny.window = {};
}
const set = (newValue: WindowValue<K>) => {
globalAny.window[fn] = newValue;
};
const get = () => {
return globalAny.window[fn] as WindowValue<K>;
};
globalAny.window[fn] = value;
return {
get,
set,
};
}
export function restoreStubs() {
globalAny.window = undefined;
sandbox.restore();
}
export function generateFakePubKey(): PubKey {
// Generates a mock pubkey for testing
const numBytes = PubKey.PUBKEY_LEN / 2 - 1;
const hexBuffer = crypto.randomBytes(numBytes).toString('hex');
const pubkeyString = `05${hexBuffer}`;
return new PubKey(pubkeyString);
}
export function generateFakePubKeys(amount: number): Array<PubKey> {
const numPubKeys = amount > 0 ? Math.floor(amount) : 0;
// tslint:disable-next-line: no-unnecessary-callback-wrapper
return new Array(numPubKeys).fill(0).map(() => generateFakePubKey());
}
export function generateChatMessage(): ChatMessage {
return new ChatMessage({
body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
identifier: uuid(),
timestamp: Date.now(),
attachments: undefined,
quote: undefined,
expireTimer: undefined,
lokiProfile: undefined,
preview: undefined,
});
}
export function generateOpenGroupMessage(): OpenGroupMessage {
const group = new OpenGroup({
server: 'chat.example.server',
channel: 0,
conversationId: '0',
});
return new OpenGroupMessage({
timestamp: Date.now(),
group,
attachments: undefined,
preview: undefined,
body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
quote: undefined,
});
}
export function generateClosedGroupMessage(
groupId?: string
): ClosedGroupChatMessage {
return new ClosedGroupChatMessage({
identifier: uuid(),
groupId: groupId ?? generateFakePubKey().key,
chatMessage: generateChatMessage(),
});
}

@ -0,0 +1,4 @@
export * from './timeout';
export * from './stubbing';
export * from './pubkey';
export * from './message';

@ -0,0 +1,48 @@
import {
ChatMessage,
ClosedGroupChatMessage,
OpenGroupMessage,
} from '../../../session/messages/outgoing';
import { v4 as uuid } from 'uuid';
import { OpenGroup } from '../../../session/types';
import { generateFakePubKey } from './pubkey';
export function generateChatMessage(): ChatMessage {
return new ChatMessage({
body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
identifier: uuid(),
timestamp: Date.now(),
attachments: undefined,
quote: undefined,
expireTimer: undefined,
lokiProfile: undefined,
preview: undefined,
});
}
export function generateOpenGroupMessage(): OpenGroupMessage {
const group = new OpenGroup({
server: 'chat.example.server',
channel: 0,
conversationId: '0',
});
return new OpenGroupMessage({
timestamp: Date.now(),
group,
attachments: undefined,
preview: undefined,
body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
quote: undefined,
});
}
export function generateClosedGroupMessage(
groupId?: string
): ClosedGroupChatMessage {
return new ClosedGroupChatMessage({
identifier: uuid(),
groupId: groupId ?? generateFakePubKey().key,
chatMessage: generateChatMessage(),
});
}

@ -0,0 +1,18 @@
import * as crypto from 'crypto';
import { PubKey } from '../../../session/types';
export function generateFakePubKey(): PubKey {
// Generates a mock pubkey for testing
const numBytes = PubKey.PUBKEY_LEN / 2 - 1;
const hexBuffer = crypto.randomBytes(numBytes).toString('hex');
const pubkeyString = `05${hexBuffer}`;
return new PubKey(pubkeyString);
}
export function generateFakePubKeys(amount: number): Array<PubKey> {
const numPubKeys = amount > 0 ? Math.floor(amount) : 0;
// tslint:disable-next-line: no-unnecessary-callback-wrapper
return new Array(numPubKeys).fill(0).map(() => generateFakePubKey());
}

@ -0,0 +1,60 @@
import * as sinon from 'sinon';
import * as crypto from 'crypto';
import * as DataShape from '../../../../js/modules/data';
const globalAny: any = global;
const sandbox = sinon.createSandbox();
// We have to do this in a weird way because Data uses module.exports
// which doesn't play well with sinon or ImportMock
// tslint:disable-next-line: no-require-imports no-var-requires
const Data = require('../../../../js/modules/data');
type DataFunction = typeof DataShape;
/**
* Stub a function inside Data.
*
* Note: This uses a custom sandbox.
* Please call `restoreStubs()` or `stub.restore()` to restore original functionality.
*/
export function stubData<K extends keyof DataFunction>(fn: K): sinon.SinonStub {
return sandbox.stub(Data, fn);
}
type WindowValue<K extends keyof Window> = Partial<Window[K]> | undefined;
/**
* Stub a window object.
*
* Note: This uses a custom sandbox.
* Please call `restoreStubs()` or `stub.restore()` to restore original functionality.
*/
export function stubWindow<K extends keyof Window>(
fn: K,
value: WindowValue<K>
) {
// tslint:disable-next-line: no-typeof-undefined
if (typeof globalAny.window === 'undefined') {
globalAny.window = {};
}
const set = (newValue: WindowValue<K>) => {
globalAny.window[fn] = newValue;
};
const get = () => {
return globalAny.window[fn] as WindowValue<K>;
};
globalAny.window[fn] = value;
return {
get,
set,
};
}
export function restoreStubs() {
globalAny.window = undefined;
sandbox.restore();
}
Loading…
Cancel
Save