do not use a custom sandbox for testing

instead use the one from Sinon as it is exposed for a good reason
pull/2242/head
Audric Ackermann 4 years ago
parent e11775a2e0
commit b76797d264
No known key found for this signature in database
GPG Key ID: 999F434D76324AD4

@ -1,6 +1,6 @@
import chai, { expect } from 'chai'; import chai, { expect } from 'chai';
import * as crypto from 'crypto'; import * as crypto from 'crypto';
import * as sinon from 'sinon'; import Sinon, * as sinon from 'sinon';
import { concatUInt8Array, getSodiumRenderer, MessageEncrypter } from '../../../../session/crypto'; import { concatUInt8Array, getSodiumRenderer, MessageEncrypter } from '../../../../session/crypto';
import { EncryptionType } from '../../../../session/types/EncryptionType'; import { EncryptionType } from '../../../../session/types/EncryptionType';
import { TestUtils } from '../../../test-utils'; import { TestUtils } from '../../../test-utils';
@ -17,7 +17,6 @@ chai.use(chaiBytes);
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
describe('MessageEncrypter', () => { describe('MessageEncrypter', () => {
const sandbox = sinon.createSandbox();
const ourNumber = '0123456789abcdef'; const ourNumber = '0123456789abcdef';
const ourUserEd25516Keypair = { const ourUserEd25516Keypair = {
pubKey: '37e1631b002de498caf7c5c1712718bde7f257c6dadeed0c21abf5e939e6c309', pubKey: '37e1631b002de498caf7c5c1712718bde7f257c6dadeed0c21abf5e939e6c309',
@ -98,13 +97,12 @@ describe('MessageEncrypter', () => {
}; };
beforeEach(() => { beforeEach(() => {
sandbox.stub(UserUtils, 'getOurPubKeyStrFromCache').returns(ourNumber); Sinon.stub(UserUtils, 'getOurPubKeyStrFromCache').returns(ourNumber);
sandbox.stub(UserUtils, 'getUserED25519KeyPair').resolves(ourUserEd25516Keypair); Sinon.stub(UserUtils, 'getUserED25519KeyPair').resolves(ourUserEd25516Keypair);
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
TestUtils.restoreStubs();
}); });
describe('EncryptionType', () => { describe('EncryptionType', () => {
@ -153,16 +151,12 @@ describe('MessageEncrypter', () => {
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
describe('Session Protocol', () => { describe('Session Protocol', () => {
let sandboxSessionProtocol: sinon.SinonSandbox;
beforeEach(() => { beforeEach(() => {
sandboxSessionProtocol = sinon.createSandbox(); Sinon.stub(UserUtils, 'getIdentityKeyPair').resolves(ourIdentityKeypair);
sandboxSessionProtocol.stub(UserUtils, 'getIdentityKeyPair').resolves(ourIdentityKeypair);
}); });
afterEach(() => { afterEach(() => {
sandboxSessionProtocol.restore(); Sinon.restore();
}); });
it('should pass the padded message body to encrypt', async () => { it('should pass the padded message body to encrypt', async () => {
@ -180,7 +174,7 @@ describe('MessageEncrypter', () => {
const keypair = await UserUtils.getUserED25519KeyPair(); const keypair = await UserUtils.getUserED25519KeyPair();
const recipient = TestUtils.generateFakePubKey(); const recipient = TestUtils.generateFakePubKey();
const sodium = await getSodiumRenderer(); const sodium = await getSodiumRenderer();
const cryptoSignDetachedSpy = sandboxSessionProtocol.spy(sodium, 'crypto_sign_detached'); const cryptoSignDetachedSpy = Sinon.spy(sodium, 'crypto_sign_detached');
const plainText = '123456'; const plainText = '123456';
const plainTextBytes = new Uint8Array(StringUtils.encode(plainText, 'utf8')); const plainTextBytes = new Uint8Array(StringUtils.encode(plainText, 'utf8'));
const userED25519PubKeyBytes = new Uint8Array( const userED25519PubKeyBytes = new Uint8Array(

@ -1,7 +1,7 @@
// tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression // tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression
import chai from 'chai'; import chai from 'chai';
import * as sinon from 'sinon'; import Sinon, * as sinon from 'sinon';
import _ from 'lodash'; import _ from 'lodash';
import { describe } from 'mocha'; import { describe } from 'mocha';
@ -34,8 +34,6 @@ const fakeSnodePool: Array<Data.Snode> = [
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
describe('GuardNodes', () => { describe('GuardNodes', () => {
// Initialize new stubbed cache
const sandbox = sinon.createSandbox();
let getSnodePoolFromDBOrFetchFromSeed: sinon.SinonStub; let getSnodePoolFromDBOrFetchFromSeed: sinon.SinonStub;
let fetchFromSeedWithRetriesAndWriteToDb: sinon.SinonStub; let fetchFromSeedWithRetriesAndWriteToDb: sinon.SinonStub;
describe('selectGuardNodes', () => { describe('selectGuardNodes', () => {
@ -51,22 +49,23 @@ describe('GuardNodes', () => {
}); });
afterEach(() => { afterEach(() => {
TestUtils.restoreStubs(); Sinon.restore();
sandbox.restore();
}); });
it('does not fetch from seed if we got 12 or more snodes in the db', async () => { it('does not fetch from seed if we got 12 or more snodes in the db', async () => {
sandbox.stub(Data, 'getSnodePoolFromDb').resolves(fakeSnodePool); Sinon.stub(Data, 'getSnodePoolFromDb').resolves(fakeSnodePool);
getSnodePoolFromDBOrFetchFromSeed = sandbox getSnodePoolFromDBOrFetchFromSeed = Sinon.stub(
.stub(SnodePool, 'getSnodePoolFromDBOrFetchFromSeed') SnodePool,
.callThrough(); 'getSnodePoolFromDBOrFetchFromSeed'
fetchFromSeedWithRetriesAndWriteToDb = sandbox ).callThrough();
.stub(SnodePool, 'TEST_fetchFromSeedWithRetriesAndWriteToDb') fetchFromSeedWithRetriesAndWriteToDb = Sinon.stub(
.resolves(); SnodePool,
const testGuardNode = sandbox.stub(OnionPaths, 'TEST_testGuardNode').resolves(true); 'TEST_fetchFromSeedWithRetriesAndWriteToDb'
).resolves();
sandbox.stub(Data, 'updateGuardNodes').resolves(); const testGuardNode = Sinon.stub(OnionPaths, 'TEST_testGuardNode').resolves(true);
Sinon.stub(Data, 'updateGuardNodes').resolves();
// run the command // run the command
const fetchedGuardNodes = await OnionPaths.selectGuardNodes(); const fetchedGuardNodes = await OnionPaths.selectGuardNodes();
@ -89,17 +88,19 @@ describe('GuardNodes', () => {
}); });
it('throws an error if we got enough snodes in the db but none test passes', async () => { it('throws an error if we got enough snodes in the db but none test passes', async () => {
sandbox.stub(Data, 'getSnodePoolFromDb').resolves(fakeSnodePool); Sinon.stub(Data, 'getSnodePoolFromDb').resolves(fakeSnodePool);
getSnodePoolFromDBOrFetchFromSeed = sandbox getSnodePoolFromDBOrFetchFromSeed = Sinon.stub(
.stub(SnodePool, 'getSnodePoolFromDBOrFetchFromSeed') SnodePool,
.callThrough(); 'getSnodePoolFromDBOrFetchFromSeed'
fetchFromSeedWithRetriesAndWriteToDb = sandbox ).callThrough();
.stub(SnodePool, 'TEST_fetchFromSeedWithRetriesAndWriteToDb') fetchFromSeedWithRetriesAndWriteToDb = Sinon.stub(
.resolves(); SnodePool,
const testGuardNode = sandbox.stub(OnionPaths, 'TEST_testGuardNode').resolves(false); 'TEST_fetchFromSeedWithRetriesAndWriteToDb'
).resolves();
sandbox.stub(Data, 'updateGuardNodes').resolves(); const testGuardNode = Sinon.stub(OnionPaths, 'TEST_testGuardNode').resolves(false);
Sinon.stub(Data, 'updateGuardNodes').resolves();
// run the command // run the command
let throwedError: string | undefined; let throwedError: string | undefined;
try { try {
@ -125,17 +126,19 @@ describe('GuardNodes', () => {
it('throws an error if we have to fetch from seed, fetch from seed enough snode but we still fail', async () => { it('throws an error if we have to fetch from seed, fetch from seed enough snode but we still fail', async () => {
const invalidSndodePool = fakeSnodePool.slice(0, 11); const invalidSndodePool = fakeSnodePool.slice(0, 11);
sandbox.stub(Data, 'getSnodePoolFromDb').resolves(invalidSndodePool); Sinon.stub(Data, 'getSnodePoolFromDb').resolves(invalidSndodePool);
TestUtils.stubWindow('getSeedNodeList', () => [{ url: 'whatever' }]); TestUtils.stubWindow('getSeedNodeList', () => [{ url: 'whatever' }]);
getSnodePoolFromDBOrFetchFromSeed = sandbox getSnodePoolFromDBOrFetchFromSeed = Sinon.stub(
.stub(SnodePool, 'getSnodePoolFromDBOrFetchFromSeed') SnodePool,
.callThrough(); 'getSnodePoolFromDBOrFetchFromSeed'
fetchFromSeedWithRetriesAndWriteToDb = sandbox ).callThrough();
.stub(SeedNodeAPI, 'fetchSnodePoolFromSeedNodeWithRetries') fetchFromSeedWithRetriesAndWriteToDb = Sinon.stub(
.resolves(fakeSnodePool); SeedNodeAPI,
'fetchSnodePoolFromSeedNodeWithRetries'
).resolves(fakeSnodePool);
sandbox.stub(Data, 'updateGuardNodes').resolves(); Sinon.stub(Data, 'updateGuardNodes').resolves();
// run the command // run the command
let throwedError: string | undefined; let throwedError: string | undefined;
try { try {
@ -149,18 +152,20 @@ describe('GuardNodes', () => {
it('returns valid guardnode if we have to fetch from seed, fetch from seed enough snodes but guard node tests passes', async () => { it('returns valid guardnode if we have to fetch from seed, fetch from seed enough snodes but guard node tests passes', async () => {
const invalidSndodePool = fakeSnodePool.slice(0, 11); const invalidSndodePool = fakeSnodePool.slice(0, 11);
sandbox.stub(Data, 'getSnodePoolFromDb').resolves(invalidSndodePool); Sinon.stub(Data, 'getSnodePoolFromDb').resolves(invalidSndodePool);
TestUtils.stubWindow('getSeedNodeList', () => [{ url: 'whatever' }]); TestUtils.stubWindow('getSeedNodeList', () => [{ url: 'whatever' }]);
const testGuardNode = sandbox.stub(OnionPaths, 'TEST_testGuardNode').resolves(true); const testGuardNode = Sinon.stub(OnionPaths, 'TEST_testGuardNode').resolves(true);
getSnodePoolFromDBOrFetchFromSeed = sandbox getSnodePoolFromDBOrFetchFromSeed = Sinon.stub(
.stub(SnodePool, 'getSnodePoolFromDBOrFetchFromSeed') SnodePool,
.callThrough(); 'getSnodePoolFromDBOrFetchFromSeed'
fetchFromSeedWithRetriesAndWriteToDb = sandbox ).callThrough();
.stub(SeedNodeAPI, 'fetchSnodePoolFromSeedNodeWithRetries') fetchFromSeedWithRetriesAndWriteToDb = Sinon.stub(
.resolves(fakeSnodePool); SeedNodeAPI,
'fetchSnodePoolFromSeedNodeWithRetries'
sandbox.stub(Data, 'updateGuardNodes').resolves(); ).resolves(fakeSnodePool);
Sinon.stub(Data, 'updateGuardNodes').resolves();
// run the command // run the command
const guardNodes = await OnionPaths.selectGuardNodes(); const guardNodes = await OnionPaths.selectGuardNodes();
@ -170,17 +175,19 @@ describe('GuardNodes', () => {
it('throws if we have to fetch from seed, fetch from seed but not have enough fetched snodes', async () => { it('throws if we have to fetch from seed, fetch from seed but not have enough fetched snodes', async () => {
const invalidSndodePool = fakeSnodePool.slice(0, 11); const invalidSndodePool = fakeSnodePool.slice(0, 11);
sandbox.stub(Data, 'getSnodePoolFromDb').resolves(invalidSndodePool); Sinon.stub(Data, 'getSnodePoolFromDb').resolves(invalidSndodePool);
TestUtils.stubWindow('getSeedNodeList', () => [{ url: 'whatever' }]); TestUtils.stubWindow('getSeedNodeList', () => [{ url: 'whatever' }]);
getSnodePoolFromDBOrFetchFromSeed = sandbox getSnodePoolFromDBOrFetchFromSeed = Sinon.stub(
.stub(SnodePool, 'getSnodePoolFromDBOrFetchFromSeed') SnodePool,
.callThrough(); 'getSnodePoolFromDBOrFetchFromSeed'
fetchFromSeedWithRetriesAndWriteToDb = sandbox ).callThrough();
.stub(SeedNodeAPI, 'fetchSnodePoolFromSeedNodeWithRetries') fetchFromSeedWithRetriesAndWriteToDb = Sinon.stub(
.resolves(invalidSndodePool); SeedNodeAPI,
'fetchSnodePoolFromSeedNodeWithRetries'
).resolves(invalidSndodePool);
sandbox.stub(Data, 'updateGuardNodes').resolves(); Sinon.stub(Data, 'updateGuardNodes').resolves();
// run the command // run the command
let throwedError: string | undefined; let throwedError: string | undefined;
try { try {

@ -1,7 +1,7 @@
// tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression // tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression
import chai from 'chai'; import chai from 'chai';
import * as sinon from 'sinon'; import Sinon, * as sinon from 'sinon';
import { describe } from 'mocha'; import { describe } from 'mocha';
import { TestUtils } from '../../../test-utils'; import { TestUtils } from '../../../test-utils';
@ -45,7 +45,6 @@ const getFakeResponseOnDestination = (statusCode?: number, body?: string) => {
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
describe('OnionPathsErrors', () => { describe('OnionPathsErrors', () => {
// Initialize new stubbed cache // Initialize new stubbed cache
const sandbox = sinon.createSandbox();
let updateSwarmSpy: sinon.SinonStub; let updateSwarmSpy: sinon.SinonStub;
let dropSnodeFromSwarmIfNeededSpy: sinon.SinonSpy; let dropSnodeFromSwarmIfNeededSpy: sinon.SinonSpy;
let dropSnodeFromSnodePool: sinon.SinonSpy; let dropSnodeFromSnodePool: sinon.SinonSpy;
@ -84,30 +83,29 @@ describe('OnionPathsErrors', () => {
associatedWith = TestUtils.generateFakePubKey().key; associatedWith = TestUtils.generateFakePubKey().key;
fakeSwarmForAssociatedWith = otherNodesPubkeys.slice(0, 6); fakeSwarmForAssociatedWith = otherNodesPubkeys.slice(0, 6);
// Stubs // Stubs
sandbox.stub(OnionPaths, 'selectGuardNodes').resolves(guardNodesArray); Sinon.stub(OnionPaths, 'selectGuardNodes').resolves(guardNodesArray);
sandbox.stub(SNodeAPI.SNodeAPI, 'TEST_getSnodePoolFromSnode').resolves(guardNodesArray); Sinon.stub(SNodeAPI.SNodeAPI, 'TEST_getSnodePoolFromSnode').resolves(guardNodesArray);
TestUtils.stubData('getGuardNodes').resolves([ TestUtils.stubData('getGuardNodes').resolves([
guardPubkeys[0], guardPubkeys[0],
guardPubkeys[1], guardPubkeys[1],
guardPubkeys[2], guardPubkeys[2],
]); ]);
TestUtils.stubWindow('getSeedNodeList', () => ['seednode1']); TestUtils.stubWindow('getSeedNodeList', () => ['seednode1']);
sandbox.stub(SeedNodeAPI, 'fetchSnodePoolFromSeedNodeWithRetries').resolves(fakeSnodePool); Sinon.stub(SeedNodeAPI, 'fetchSnodePoolFromSeedNodeWithRetries').resolves(fakeSnodePool);
sandbox.stub(Data, 'getSwarmNodesForPubkey').resolves(fakeSwarmForAssociatedWith); Sinon.stub(Data, 'getSwarmNodesForPubkey').resolves(fakeSwarmForAssociatedWith);
updateGuardNodesStub = sandbox.stub(Data, 'updateGuardNodes').resolves(); updateGuardNodesStub = Sinon.stub(Data, 'updateGuardNodes').resolves();
// those are still doing what they do, but we spy on their executation // those are still doing what they do, but we spy on their executation
updateSwarmSpy = sandbox.stub(Data, 'updateSwarmNodesForPubkey').resolves(); updateSwarmSpy = Sinon.stub(Data, 'updateSwarmNodesForPubkey').resolves();
sandbox Sinon.stub(DataItem, 'getItemById')
.stub(DataItem, 'getItemById')
.withArgs(Data.SNODE_POOL_ITEM_ID) .withArgs(Data.SNODE_POOL_ITEM_ID)
.resolves({ id: Data.SNODE_POOL_ITEM_ID, value: '' }); .resolves({ id: Data.SNODE_POOL_ITEM_ID, value: '' });
sandbox.stub(DataItem, 'createOrUpdateItem').resolves(); Sinon.stub(DataItem, 'createOrUpdateItem').resolves();
dropSnodeFromSnodePool = sandbox.spy(SNodeAPI.SnodePool, 'dropSnodeFromSnodePool'); dropSnodeFromSnodePool = Sinon.spy(SNodeAPI.SnodePool, 'dropSnodeFromSnodePool');
dropSnodeFromSwarmIfNeededSpy = sandbox.spy(SNodeAPI.SnodePool, 'dropSnodeFromSwarmIfNeeded'); dropSnodeFromSwarmIfNeededSpy = Sinon.spy(SNodeAPI.SnodePool, 'dropSnodeFromSwarmIfNeeded');
dropSnodeFromPathSpy = sandbox.spy(OnionPaths, 'dropSnodeFromPath'); dropSnodeFromPathSpy = Sinon.spy(OnionPaths, 'dropSnodeFromPath');
incrementBadPathCountOrDropSpy = sandbox.spy(OnionPaths, 'incrementBadPathCountOrDrop'); incrementBadPathCountOrDropSpy = Sinon.spy(OnionPaths, 'incrementBadPathCountOrDrop');
incrementBadSnodeCountOrDropSpy = sandbox.spy(SNodeAPI.Onions, 'incrementBadSnodeCountOrDrop'); incrementBadSnodeCountOrDropSpy = Sinon.spy(SNodeAPI.Onions, 'incrementBadSnodeCountOrDrop');
OnionPaths.clearTestOnionPath(); OnionPaths.clearTestOnionPath();
@ -116,16 +114,16 @@ describe('OnionPathsErrors', () => {
await OnionPaths.getOnionPath({}); await OnionPaths.getOnionPath({});
oldOnionPaths = OnionPaths.TEST_getTestOnionPath(); oldOnionPaths = OnionPaths.TEST_getTestOnionPath();
sandbox Sinon.stub(
.stub(SNodeAPI.Onions, 'decodeOnionResult') SNodeAPI.Onions,
.callsFake((_symkey: ArrayBuffer, plaintext: string) => 'decodeOnionResult'
Promise.resolve({ plaintext, ciphertextBuffer: new Uint8Array() }) ).callsFake((_symkey: ArrayBuffer, plaintext: string) =>
); Promise.resolve({ plaintext, ciphertextBuffer: new Uint8Array() })
);
}); });
afterEach(() => { afterEach(() => {
TestUtils.restoreStubs(); Sinon.restore();
sandbox.restore();
}); });
describe('processOnionResponse', () => { describe('processOnionResponse', () => {

@ -1,7 +1,7 @@
// tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression // tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression
import chai from 'chai'; import chai from 'chai';
import * as sinon from 'sinon'; import Sinon from 'sinon';
import _ from 'lodash'; import _ from 'lodash';
import { describe } from 'mocha'; import { describe } from 'mocha';
@ -42,7 +42,6 @@ const fakeGuardNodesFromDB: Array<Data.GuardNode> = fakeGuardNodesEd25519.map(ed
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
describe('OnionPaths', () => { describe('OnionPaths', () => {
// Initialize new stubbed cache // Initialize new stubbed cache
const sandbox = sinon.createSandbox();
let oldOnionPaths: Array<Array<Snode>>; let oldOnionPaths: Array<Array<Snode>>;
describe('dropSnodeFromPath', () => { describe('dropSnodeFromPath', () => {
@ -50,9 +49,9 @@ describe('OnionPaths', () => {
// Utils Stubs // Utils Stubs
OnionPaths.clearTestOnionPath(); OnionPaths.clearTestOnionPath();
sandbox.stub(OnionPaths, 'selectGuardNodes').resolves(fakeGuardNodes); Sinon.stub(OnionPaths, 'selectGuardNodes').resolves(fakeGuardNodes);
sandbox.stub(SNodeAPI.SNodeAPI, 'TEST_getSnodePoolFromSnode').resolves(fakeGuardNodes); Sinon.stub(SNodeAPI.SNodeAPI, 'TEST_getSnodePoolFromSnode').resolves(fakeGuardNodes);
sandbox.stub(Data, 'getSnodePoolFromDb').resolves(fakeSnodePool); Sinon.stub(Data, 'getSnodePoolFromDb').resolves(fakeSnodePool);
TestUtils.stubData('getGuardNodes').resolves(fakeGuardNodesFromDB); TestUtils.stubData('getGuardNodes').resolves(fakeGuardNodesFromDB);
TestUtils.stubData('createOrUpdateItem').resolves(); TestUtils.stubData('createOrUpdateItem').resolves();
@ -61,7 +60,7 @@ describe('OnionPaths', () => {
TestUtils.stubWindowLog(); TestUtils.stubWindowLog();
sandbox.stub(SeedNodeAPI, 'fetchSnodePoolFromSeedNodeWithRetries').resolves(fakeSnodePool); Sinon.stub(SeedNodeAPI, 'fetchSnodePoolFromSeedNodeWithRetries').resolves(fakeSnodePool);
SNodeAPI.Onions.resetSnodeFailureCount(); SNodeAPI.Onions.resetSnodeFailureCount();
OnionPaths.resetPathFailureCount(); OnionPaths.resetPathFailureCount();
// get a copy of what old ones look like // get a copy of what old ones look like
@ -75,8 +74,7 @@ describe('OnionPaths', () => {
}); });
afterEach(() => { afterEach(() => {
TestUtils.restoreStubs(); Sinon.restore();
sandbox.restore();
}); });
describe('with valid snode pool', () => { describe('with valid snode pool', () => {
it('rebuilds after removing last snode on path', async () => { it('rebuilds after removing last snode on path', async () => {

@ -1,7 +1,7 @@
// tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression // tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression
import chai from 'chai'; import chai from 'chai';
import * as sinon from 'sinon'; import Sinon from 'sinon';
import _ from 'lodash'; import _ from 'lodash';
import { describe } from 'mocha'; import { describe } from 'mocha';
@ -44,7 +44,6 @@ const fakeSnodePoolFromSeedNode: Array<SnodeFromSeed> = fakeSnodePool.map(m => {
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
describe('SeedNodeAPI', () => { describe('SeedNodeAPI', () => {
// Initialize new stubbed cache // Initialize new stubbed cache
const sandbox = sinon.createSandbox();
describe('getSnodeListFromSeednode', () => { describe('getSnodeListFromSeednode', () => {
beforeEach(() => { beforeEach(() => {
@ -59,19 +58,20 @@ describe('SeedNodeAPI', () => {
}); });
afterEach(() => { afterEach(() => {
TestUtils.restoreStubs(); Sinon.restore();
sandbox.restore();
}); });
it('if the cached snode pool has less than 12 snodes, trigger a fetch from the seed nodes with retries', async () => { it('if the cached snode pool has less than 12 snodes, trigger a fetch from the seed nodes with retries', async () => {
const TEST_fetchSnodePoolFromSeedNodeRetryable = sandbox const TEST_fetchSnodePoolFromSeedNodeRetryable = Sinon.stub(
.stub(SeedNodeAPI, 'TEST_fetchSnodePoolFromSeedNodeRetryable') SeedNodeAPI,
'TEST_fetchSnodePoolFromSeedNodeRetryable'
)
.onFirstCall() .onFirstCall()
.throws() .throws()
.onSecondCall() .onSecondCall()
.resolves(fakeSnodePoolFromSeedNode); .resolves(fakeSnodePoolFromSeedNode);
sandbox.stub(SeedNodeAPI, 'getMinTimeout').returns(20); Sinon.stub(SeedNodeAPI, 'getMinTimeout').returns(20);
// run the command // run the command
const fetched = await SeedNodeAPI.fetchSnodePoolFromSeedNodeWithRetries([ const fetched = await SeedNodeAPI.fetchSnodePoolFromSeedNodeWithRetries([

@ -1,7 +1,7 @@
// tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression // tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression
import chai from 'chai'; import chai from 'chai';
import * as sinon from 'sinon'; import Sinon, * as sinon from 'sinon';
import _ from 'lodash'; import _ from 'lodash';
import { describe } from 'mocha'; import { describe } from 'mocha';
@ -33,9 +33,6 @@ const fakeSnodePool: Array<Data.Snode> = [
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
describe('OnionPaths', () => { describe('OnionPaths', () => {
// Initialize new stubbed cache
const sandbox = sinon.createSandbox();
describe('getSnodePoolFromDBOrFetchFromSeed', () => { describe('getSnodePoolFromDBOrFetchFromSeed', () => {
let getSnodePoolFromDb: sinon.SinonStub; let getSnodePoolFromDb: sinon.SinonStub;
let fetchFromSeedWithRetriesAndWriteToDb: sinon.SinonStub; let fetchFromSeedWithRetriesAndWriteToDb: sinon.SinonStub;
@ -54,12 +51,11 @@ describe('OnionPaths', () => {
}); });
afterEach(() => { afterEach(() => {
TestUtils.restoreStubs(); Sinon.restore();
sandbox.restore();
}); });
it('if the cached snode pool has at least 12 snodes, just return it without fetching from seed', async () => { it('if the cached snode pool has at least 12 snodes, just return it without fetching from seed', async () => {
getSnodePoolFromDb = sandbox.stub(Data, 'getSnodePoolFromDb').resolves(fakeSnodePool); getSnodePoolFromDb = Sinon.stub(Data, 'getSnodePoolFromDb').resolves(fakeSnodePool);
fetchFromSeedWithRetriesAndWriteToDb = sandbox.stub( fetchFromSeedWithRetriesAndWriteToDb = Sinon.stub(
SnodePool, SnodePool,
'TEST_fetchFromSeedWithRetriesAndWriteToDb' 'TEST_fetchFromSeedWithRetriesAndWriteToDb'
); );
@ -74,15 +70,17 @@ describe('OnionPaths', () => {
it('if the cached snode pool 12 or less snodes, trigger a fetch from the seed nodes', async () => { it('if the cached snode pool 12 or less snodes, trigger a fetch from the seed nodes', async () => {
const length12 = fakeSnodePool.slice(0, 12); const length12 = fakeSnodePool.slice(0, 12);
expect(length12.length).to.eq(12); expect(length12.length).to.eq(12);
getSnodePoolFromDb = sandbox.stub(Data, 'getSnodePoolFromDb').resolves(length12); getSnodePoolFromDb = Sinon.stub(Data, 'getSnodePoolFromDb').resolves(length12);
sandbox.stub(Data, 'updateSnodePoolOnDb').resolves(); Sinon.stub(Data, 'updateSnodePoolOnDb').resolves();
fetchFromSeedWithRetriesAndWriteToDb = sandbox fetchFromSeedWithRetriesAndWriteToDb = Sinon.stub(
.stub(SnodePool, 'TEST_fetchFromSeedWithRetriesAndWriteToDb') SnodePool,
.callThrough(); 'TEST_fetchFromSeedWithRetriesAndWriteToDb'
fetchSnodePoolFromSeedNodeWithRetries = sandbox ).callThrough();
.stub(SeedNodeAPI, 'fetchSnodePoolFromSeedNodeWithRetries') fetchSnodePoolFromSeedNodeWithRetries = Sinon.stub(
.resolves(fakeSnodePool); SeedNodeAPI,
'fetchSnodePoolFromSeedNodeWithRetries'
).resolves(fakeSnodePool);
// run the command // run the command
const fetched = await SnodePool.getSnodePoolFromDBOrFetchFromSeed(); const fetched = await SnodePool.getSnodePoolFromDBOrFetchFromSeed();

@ -2,6 +2,7 @@
import chai from 'chai'; import chai from 'chai';
import { describe } from 'mocha'; import { describe } from 'mocha';
import Sinon from 'sinon';
import { filterDuplicatesFromDbAndIncoming } from '../../../../../session/apis/open_group_api/opengroupV2/SogsFilterDuplicate'; import { filterDuplicatesFromDbAndIncoming } from '../../../../../session/apis/open_group_api/opengroupV2/SogsFilterDuplicate';
import { TestUtils } from '../../../../test-utils'; import { TestUtils } from '../../../../test-utils';
@ -16,7 +17,7 @@ describe('filterDuplicatesFromDbAndIncoming', () => {
}); });
afterEach(() => { afterEach(() => {
TestUtils.restoreStubs(); Sinon.restore();
}); });
it('no duplicates', async () => { it('no duplicates', async () => {

@ -9,8 +9,6 @@ chai.use(chaiAsPromised as any);
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
describe('ClosedGroupUpdates', () => { describe('ClosedGroupUpdates', () => {
//FIXME AUDRIC TODO //FIXME AUDRIC TODO
// Initialize new stubbed cache
// const sandbox = sinon.createSandbox();
// const ourDevice = TestUtils.generateFakePubKey(); // const ourDevice = TestUtils.generateFakePubKey();
// const ourNumber = ourDevice.key; // const ourNumber = ourDevice.key;
// const groupId = TestUtils.generateFakePubKey().key; // const groupId = TestUtils.generateFakePubKey().key;
@ -22,7 +20,6 @@ describe('ClosedGroupUpdates', () => {
// sandbox.stub(UserUtils, 'getCurrentDevicePubKey').resolves(ourNumber); // sandbox.stub(UserUtils, 'getCurrentDevicePubKey').resolves(ourNumber);
// }); // });
// afterEach(() => { // afterEach(() => {
// TestUtils.restoreStubs();
// sandbox.restore(); // sandbox.restore();
// }); // });
// describe('handleClosedGroupControlMessage', () => { // describe('handleClosedGroupControlMessage', () => {

@ -7,7 +7,7 @@ import { ConfigurationMessage } from '../../../../session/messages/outgoing/cont
import { UserUtils } from '../../../../session/utils'; import { UserUtils } from '../../../../session/utils';
import { TestUtils } from '../../../test-utils'; import { TestUtils } from '../../../test-utils';
import Sinon, * as sinon from 'sinon'; import Sinon from 'sinon';
import * as cache from '../../../../receiver/cache'; import * as cache from '../../../../receiver/cache';
import * as data from '../../../../../ts/data/data'; import * as data from '../../../../../ts/data/data';
import { EnvelopePlus } from '../../../../receiver/types'; import { EnvelopePlus } from '../../../../receiver/types';
@ -20,7 +20,6 @@ chai.should();
const { expect } = chai; const { expect } = chai;
describe('ConfigurationMessage_receiving', () => { describe('ConfigurationMessage_receiving', () => {
const sandbox = sinon.createSandbox();
let createOrUpdateStub: Sinon.SinonStub<any>; let createOrUpdateStub: Sinon.SinonStub<any>;
let getItemByIdStub: Sinon.SinonStub<any>; let getItemByIdStub: Sinon.SinonStub<any>;
let sender: string; let sender: string;
@ -29,7 +28,7 @@ describe('ConfigurationMessage_receiving', () => {
let config: ConfigurationMessage; let config: ConfigurationMessage;
beforeEach(() => { beforeEach(() => {
sandbox.stub(cache, 'removeFromCache').resolves(); Sinon.stub(cache, 'removeFromCache').resolves();
sender = TestUtils.generateFakePubKey().key; sender = TestUtils.generateFakePubKey().key;
config = new ConfigurationMessage({ config = new ConfigurationMessage({
activeOpenGroups: [], activeOpenGroups: [],
@ -42,17 +41,16 @@ describe('ConfigurationMessage_receiving', () => {
}); });
afterEach(() => { afterEach(() => {
TestUtils.restoreStubs(); Sinon.restore();
sandbox.restore();
}); });
it('should not be processed if we do not have a pubkey', async () => { it('should not be processed if we do not have a pubkey', async () => {
sandbox.stub(UserUtils, 'getOurPubKeyStrFromCache').resolves(undefined); Sinon.stub(UserUtils, 'getOurPubKeyStrFromCache').resolves(undefined);
envelope = TestUtils.generateEnvelopePlus(sender); envelope = TestUtils.generateEnvelopePlus(sender);
const proto = config.contentProto(); const proto = config.contentProto();
createOrUpdateStub = sandbox.stub(data, 'createOrUpdateItem').resolves(); createOrUpdateStub = Sinon.stub(data, 'createOrUpdateItem').resolves();
getItemByIdStub = sandbox.stub(data, 'getItemById').resolves(); getItemByIdStub = Sinon.stub(data, 'getItemById').resolves();
await handleConfigurationMessage( await handleConfigurationMessage(
envelope, envelope,
proto.configurationMessage as SignalService.ConfigurationMessage proto.configurationMessage as SignalService.ConfigurationMessage
@ -65,7 +63,7 @@ describe('ConfigurationMessage_receiving', () => {
const ourNumber = TestUtils.generateFakePubKey().key; const ourNumber = TestUtils.generateFakePubKey().key;
beforeEach(() => { beforeEach(() => {
sandbox.stub(UserUtils, 'getOurPubKeyStrFromCache').resolves(ourNumber); Sinon.stub(UserUtils, 'getOurPubKeyStrFromCache').resolves(ourNumber);
}); });
it('should not be processed if the message is not coming from our number', async () => { it('should not be processed if the message is not coming from our number', async () => {
@ -73,8 +71,8 @@ describe('ConfigurationMessage_receiving', () => {
// sender !== ourNumber // sender !== ourNumber
envelope = TestUtils.generateEnvelopePlus(sender); envelope = TestUtils.generateEnvelopePlus(sender);
createOrUpdateStub = sandbox.stub(data, 'createOrUpdateItem').resolves(); createOrUpdateStub = Sinon.stub(data, 'createOrUpdateItem').resolves();
getItemByIdStub = sandbox.stub(data, 'getItemById').resolves(); getItemByIdStub = Sinon.stub(data, 'getItemById').resolves();
await handleConfigurationMessage( await handleConfigurationMessage(
envelope, envelope,
proto.configurationMessage as SignalService.ConfigurationMessage proto.configurationMessage as SignalService.ConfigurationMessage

@ -1,7 +1,7 @@
// tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression // tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression
import chai from 'chai'; import chai from 'chai';
import * as sinon from 'sinon'; import Sinon, * as sinon from 'sinon';
import { describe } from 'mocha'; import { describe } from 'mocha';
import { randomBytes } from 'crypto'; import { randomBytes } from 'crypto';
import * as Data from '../../../../../ts/data/data'; import * as Data from '../../../../../ts/data/data';
@ -26,7 +26,6 @@ const { expect } = chai;
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
describe('MessageQueue', () => { describe('MessageQueue', () => {
// Initialize new stubbed cache // Initialize new stubbed cache
const sandbox = sinon.createSandbox();
const ourDevice = TestUtils.generateFakePubKey(); const ourDevice = TestUtils.generateFakePubKey();
const ourNumber = ourDevice.key; const ourNumber = ourDevice.key;
@ -47,19 +46,22 @@ describe('MessageQueue', () => {
beforeEach(() => { beforeEach(() => {
// Utils Stubs // Utils Stubs
sandbox.stub(UserUtils, 'getOurPubKeyStrFromCache').returns(ourNumber); Sinon.stub(UserUtils, 'getOurPubKeyStrFromCache').returns(ourNumber);
// Message Sender Stubs // Message Sender Stubs
sendStub = sandbox.stub(MessageSender, 'send'); sendStub = Sinon.stub(MessageSender, 'send');
messageSentHandlerFailedStub = sandbox messageSentHandlerFailedStub = Sinon.stub(
.stub(MessageSentHandler as any, 'handleMessageSentFailure') MessageSentHandler as any,
.resolves(); 'handleMessageSentFailure'
messageSentHandlerSuccessStub = sandbox ).resolves();
.stub(MessageSentHandler as any, 'handleMessageSentSuccess') messageSentHandlerSuccessStub = Sinon.stub(
.resolves(); MessageSentHandler as any,
messageSentPublicHandlerSuccessStub = sandbox 'handleMessageSentSuccess'
.stub(MessageSentHandler as any, 'handlePublicMessageSentSuccess') ).resolves();
.resolves(); messageSentPublicHandlerSuccessStub = Sinon.stub(
MessageSentHandler as any,
'handlePublicMessageSentSuccess'
).resolves();
// Init Queue // Init Queue
pendingMessageCache = new PendingMessageCacheStub(); pendingMessageCache = new PendingMessageCacheStub();
@ -68,8 +70,7 @@ describe('MessageQueue', () => {
}); });
afterEach(() => { afterEach(() => {
TestUtils.restoreStubs(); Sinon.restore();
sandbox.restore();
}); });
describe('processPending', () => { describe('processPending', () => {
@ -117,12 +118,12 @@ describe('MessageQueue', () => {
describe('events', () => { describe('events', () => {
it('should send a success event if message was sent', done => { it('should send a success event if message was sent', done => {
sandbox.stub(Data, 'getMessageById').resolves(); Sinon.stub(Data, 'getMessageById').resolves();
const message = TestUtils.generateVisibleMessage(); const message = TestUtils.generateVisibleMessage();
sendStub.resolves({ effectiveTimestamp: Date.now(), wrappedEnvelope: randomBytes(10) }); sendStub.resolves({ effectiveTimestamp: Date.now(), wrappedEnvelope: randomBytes(10) });
const device = TestUtils.generateFakePubKey(); const device = TestUtils.generateFakePubKey();
sandbox.stub(MessageSender, 'getMinRetryTimeout').returns(10); Sinon.stub(MessageSender, 'getMinRetryTimeout').returns(10);
const waitForMessageSentEvent = async () => const waitForMessageSentEvent = async () =>
new Promise<void>(resolve => { new Promise<void>(resolve => {
resolve(); resolve();
@ -173,7 +174,7 @@ describe('MessageQueue', () => {
describe('sendToPubKey', () => { describe('sendToPubKey', () => {
it('should send the message to the device', async () => { it('should send the message to the device', async () => {
const device = TestUtils.generateFakePubKey(); const device = TestUtils.generateFakePubKey();
const stub = sandbox.stub(messageQueueStub as any, 'process').resolves(); const stub = Sinon.stub(messageQueueStub as any, 'process').resolves();
const message = TestUtils.generateVisibleMessage(); const message = TestUtils.generateVisibleMessage();
await messageQueueStub.sendToPubKey(device, message); await messageQueueStub.sendToPubKey(device, message);
@ -195,9 +196,9 @@ describe('MessageQueue', () => {
describe('closed groups', () => { describe('closed groups', () => {
it('can send to closed group', async () => { it('can send to closed group', async () => {
const members = TestUtils.generateFakePubKeys(4).map(p => new PubKey(p.key)); const members = TestUtils.generateFakePubKeys(4).map(p => new PubKey(p.key));
sandbox.stub(GroupUtils, 'getGroupMembers').returns(members); Sinon.stub(GroupUtils, 'getGroupMembers').returns(members);
const send = sandbox.stub(messageQueueStub, 'sendToPubKey').resolves(); const send = Sinon.stub(messageQueueStub, 'sendToPubKey').resolves();
const message = TestUtils.generateClosedGroupMessage(); const message = TestUtils.generateClosedGroupMessage();
await messageQueueStub.sendToGroup(message); await messageQueueStub.sendToGroup(message);
@ -213,9 +214,9 @@ describe('MessageQueue', () => {
describe('open groupsv2', () => { describe('open groupsv2', () => {
let sendToOpenGroupV2Stub: sinon.SinonStub; let sendToOpenGroupV2Stub: sinon.SinonStub;
beforeEach(() => { beforeEach(() => {
sendToOpenGroupV2Stub = sandbox sendToOpenGroupV2Stub = Sinon.stub(MessageSender, 'sendToOpenGroupV2').resolves(
.stub(MessageSender, 'sendToOpenGroupV2') TestUtils.generateOpenGroupMessageV2()
.resolves(TestUtils.generateOpenGroupMessageV2()); );
}); });
it('can send to open group', async () => { it('can send to open group', async () => {

@ -1,6 +1,6 @@
import { expect } from 'chai'; import { expect } from 'chai';
import * as crypto from 'crypto'; import * as crypto from 'crypto';
import * as sinon from 'sinon'; import Sinon, * as sinon from 'sinon';
import { MessageSender } from '../../../../session/sending'; import { MessageSender } from '../../../../session/sending';
import { TestUtils } from '../../../test-utils'; import { TestUtils } from '../../../test-utils';
import { MessageEncrypter } from '../../../../session/crypto'; import { MessageEncrypter } from '../../../../session/crypto';
@ -14,11 +14,8 @@ import { SNodeAPI } from '../../../../session/apis/snode_api';
import _ from 'lodash'; import _ from 'lodash';
describe('MessageSender', () => { describe('MessageSender', () => {
const sandbox = sinon.createSandbox();
afterEach(() => { afterEach(() => {
sandbox.restore(); sinon.restore();
TestUtils.restoreStubs();
}); });
beforeEach(() => { beforeEach(() => {
@ -32,16 +29,16 @@ describe('MessageSender', () => {
let encryptStub: sinon.SinonStub<[PubKey, Uint8Array, EncryptionType]>; let encryptStub: sinon.SinonStub<[PubKey, Uint8Array, EncryptionType]>;
beforeEach(() => { beforeEach(() => {
sessionMessageAPISendStub = sandbox.stub(MessageSender, 'TEST_sendMessageToSnode').resolves(); sessionMessageAPISendStub = Sinon.stub(MessageSender, 'TEST_sendMessageToSnode').resolves();
sandbox.stub(Data, 'getMessageById').resolves(); Sinon.stub(Data, 'getMessageById').resolves();
encryptStub = sandbox.stub(MessageEncrypter, 'encrypt').resolves({ encryptStub = Sinon.stub(MessageEncrypter, 'encrypt').resolves({
envelopeType: SignalService.Envelope.Type.SESSION_MESSAGE, envelopeType: SignalService.Envelope.Type.SESSION_MESSAGE,
cipherText: crypto.randomBytes(10), cipherText: crypto.randomBytes(10),
}); });
sandbox.stub(UserUtils, 'getOurPubKeyStrFromCache').returns(ourNumber); Sinon.stub(UserUtils, 'getOurPubKeyStrFromCache').returns(ourNumber);
}); });
describe('retry', () => { describe('retry', () => {
@ -117,7 +114,7 @@ describe('MessageSender', () => {
const visibleMessage = TestUtils.generateVisibleMessage(); const visibleMessage = TestUtils.generateVisibleMessage();
const rawMessage = await MessageUtils.toRawMessage(device, visibleMessage); const rawMessage = await MessageUtils.toRawMessage(device, visibleMessage);
const offset = 200000; const offset = 200000;
sandbox.stub(SNodeAPI, 'getLatestTimestampOffset').returns(offset); Sinon.stub(SNodeAPI, 'getLatestTimestampOffset').returns(offset);
await MessageSender.send(rawMessage, 3, 10); await MessageSender.send(rawMessage, 3, 10);
const data = sessionMessageAPISendStub.getCall(0).args[1]; const data = sessionMessageAPISendStub.getCall(0).args[1];
@ -188,20 +185,19 @@ describe('MessageSender', () => {
}); });
describe('sendToOpenGroupV2', () => { describe('sendToOpenGroupV2', () => {
const sandbox2 = sinon.createSandbox();
let postMessageRetryableStub: sinon.SinonStub; let postMessageRetryableStub: sinon.SinonStub;
beforeEach(() => { beforeEach(() => {
sandbox Sinon.stub(UserUtils, 'getOurPubKeyStrFromCache').resolves(
.stub(UserUtils, 'getOurPubKeyStrFromCache') TestUtils.generateFakePubKey().key
.resolves(TestUtils.generateFakePubKey().key); );
postMessageRetryableStub = sandbox postMessageRetryableStub = Sinon.stub(ApiV2, 'postMessageRetryable').resolves(
.stub(ApiV2, 'postMessageRetryable') TestUtils.generateOpenGroupMessageV2()
.resolves(TestUtils.generateOpenGroupMessageV2()); );
}); });
afterEach(() => { afterEach(() => {
sandbox2.restore(); Sinon.restore();
}); });
it('should call postMessageRetryableStub', async () => { it('should call postMessageRetryableStub', async () => {
@ -217,7 +213,7 @@ describe('MessageSender', () => {
const roomInfos = TestUtils.generateOpenGroupV2RoomInfos(); const roomInfos = TestUtils.generateOpenGroupV2RoomInfos();
postMessageRetryableStub.throws('whate'); postMessageRetryableStub.throws('whate');
sandbox2.stub(ApiV2, 'getMinTimeout').returns(2); Sinon.stub(ApiV2, 'getMinTimeout').returns(2);
postMessageRetryableStub.onThirdCall().resolves(); postMessageRetryableStub.onThirdCall().resolves();
await MessageSender.sendToOpenGroupV2(message, roomInfos); await MessageSender.sendToOpenGroupV2(message, roomInfos);
@ -227,7 +223,7 @@ describe('MessageSender', () => {
it('should not retry more than 3 postMessageRetryableStub ', async () => { it('should not retry more than 3 postMessageRetryableStub ', async () => {
const message = TestUtils.generateOpenGroupVisibleMessage(); const message = TestUtils.generateOpenGroupVisibleMessage();
const roomInfos = TestUtils.generateOpenGroupV2RoomInfos(); const roomInfos = TestUtils.generateOpenGroupV2RoomInfos();
sandbox2.stub(ApiV2, 'getMinTimeout').returns(2); Sinon.stub(ApiV2, 'getMinTimeout').returns(2);
postMessageRetryableStub.throws('fake error'); postMessageRetryableStub.throws('fake error');
postMessageRetryableStub.onCall(4).resolves(); postMessageRetryableStub.onCall(4).resolves();
try { try {

@ -1,6 +1,6 @@
// tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression // tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression
import { expect } from 'chai'; import { expect } from 'chai';
import * as sinon from 'sinon'; import Sinon from 'sinon';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { MessageUtils } from '../../../../session/utils'; import { MessageUtils } from '../../../../session/utils';
import { TestUtils } from '../../../../test/test-utils'; import { TestUtils } from '../../../../test/test-utils';
@ -13,7 +13,6 @@ interface StorageItem {
} }
describe('PendingMessageCache', () => { describe('PendingMessageCache', () => {
const sandbox = sinon.createSandbox();
// Initialize new stubbed cache // Initialize new stubbed cache
let data: StorageItem; let data: StorageItem;
let pendingMessageCacheStub: PendingMessageCache; let pendingMessageCacheStub: PendingMessageCache;
@ -42,8 +41,7 @@ describe('PendingMessageCache', () => {
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
TestUtils.restoreStubs();
}); });
it('can initialize cache', async () => { it('can initialize cache', async () => {

@ -30,7 +30,6 @@ const { expect } = chai;
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
describe('SwarmPolling', () => { describe('SwarmPolling', () => {
// Initialize new stubbed cache // Initialize new stubbed cache
const sandbox = sinon.createSandbox();
const ourPubkey = TestUtils.generateFakePubKey(); const ourPubkey = TestUtils.generateFakePubKey();
const ourNumber = ourPubkey.key; const ourNumber = ourPubkey.key;
@ -42,16 +41,16 @@ describe('SwarmPolling', () => {
let clock: Sinon.SinonFakeTimers; let clock: Sinon.SinonFakeTimers;
beforeEach(async () => { beforeEach(async () => {
// Utils Stubs // Utils Stubs
sandbox.stub(UserUtils, 'getOurPubKeyStrFromCache').returns(ourNumber); Sinon.stub(UserUtils, 'getOurPubKeyStrFromCache').returns(ourNumber);
sandbox.stub(Data, 'getAllConversations').resolves(new ConversationCollection()); Sinon.stub(Data, 'getAllConversations').resolves(new ConversationCollection());
sandbox.stub(DataItem, 'getItemById').resolves(); Sinon.stub(DataItem, 'getItemById').resolves();
sandbox.stub(Data, 'saveConversation').resolves(); Sinon.stub(Data, 'saveConversation').resolves();
sandbox.stub(Data, 'getSwarmNodesForPubkey').resolves(); Sinon.stub(Data, 'getSwarmNodesForPubkey').resolves();
sandbox.stub(Data, 'getLastHashBySnode').resolves(); Sinon.stub(Data, 'getLastHashBySnode').resolves();
sandbox.stub(SnodePool, 'getSwarmFor').resolves(generateFakeSnodes(5)); Sinon.stub(SnodePool, 'getSwarmFor').resolves(generateFakeSnodes(5));
sandbox.stub(SNodeAPI, 'retrieveNextMessages').resolves([]); Sinon.stub(SNodeAPI, 'retrieveNextMessages').resolves([]);
TestUtils.stubWindow('inboxStore', undefined); TestUtils.stubWindow('inboxStore', undefined);
TestUtils.stubWindow('getGlobalOnlineStatus', () => true); TestUtils.stubWindow('getGlobalOnlineStatus', () => true);
TestUtils.stubWindowLog(); TestUtils.stubWindowLog();
@ -62,14 +61,13 @@ describe('SwarmPolling', () => {
swarmPolling = getSwarmPollingInstance(); swarmPolling = getSwarmPollingInstance();
swarmPolling.TEST_reset(); swarmPolling.TEST_reset();
TEST_pollOnceForKeySpy = sandbox.spy(swarmPolling, 'TEST_pollOnceForKey'); TEST_pollOnceForKeySpy = Sinon.spy(swarmPolling, 'TEST_pollOnceForKey');
clock = sinon.useFakeTimers(Date.now()); clock = sinon.useFakeTimers(Date.now());
}); });
afterEach(() => { afterEach(() => {
TestUtils.restoreStubs(); Sinon.restore();
sandbox.restore();
getConversationController().reset(); getConversationController().reset();
clock.restore(); clock.restore();
}); });

@ -1,7 +1,6 @@
// tslint:disable: no-implicit-dependencies // tslint:disable: no-implicit-dependencies
import chai from 'chai'; import chai from 'chai';
import * as sinon from 'sinon';
import { TestUtils } from '../../../test-utils'; import { TestUtils } from '../../../test-utils';
import { MessageUtils, UserUtils } from '../../../../session/utils'; import { MessageUtils, UserUtils } from '../../../../session/utils';
import { EncryptionType, PubKey } from '../../../../session/types'; import { EncryptionType, PubKey } from '../../../../session/types';
@ -17,14 +16,13 @@ import { ClosedGroupEncryptionPairMessage } from '../../../../session/messages/o
import { ClosedGroupNameChangeMessage } from '../../../../session/messages/outgoing/controlMessage/group/ClosedGroupNameChangeMessage'; import { ClosedGroupNameChangeMessage } from '../../../../session/messages/outgoing/controlMessage/group/ClosedGroupNameChangeMessage';
import { ClosedGroupNewMessage } from '../../../../session/messages/outgoing/controlMessage/group/ClosedGroupNewMessage'; import { ClosedGroupNewMessage } from '../../../../session/messages/outgoing/controlMessage/group/ClosedGroupNewMessage';
import { ClosedGroupRemovedMembersMessage } from '../../../../session/messages/outgoing/controlMessage/group/ClosedGroupRemovedMembersMessage'; import { ClosedGroupRemovedMembersMessage } from '../../../../session/messages/outgoing/controlMessage/group/ClosedGroupRemovedMembersMessage';
import Sinon from 'sinon';
const { expect } = chai; const { expect } = chai;
describe('Message Utils', () => { describe('Message Utils', () => {
const sandbox = sinon.createSandbox();
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
@ -236,13 +234,13 @@ describe('Message Utils', () => {
beforeEach(() => { beforeEach(() => {
// convos = []; // convos = [];
sandbox.stub(UserUtils, 'getOurPubKeyStrFromCache').resolves(ourNumber); Sinon.stub(UserUtils, 'getOurPubKeyStrFromCache').resolves(ourNumber);
sandbox.stub(UserUtils, 'getOurPubKeyFromCache').resolves(PubKey.cast(ourNumber)); Sinon.stub(UserUtils, 'getOurPubKeyFromCache').resolves(PubKey.cast(ourNumber));
}); });
beforeEach(() => { beforeEach(() => {
// convos = []; // convos = [];
sandbox.restore(); Sinon.restore();
}); });
// it('filter out non active open groups', async () => { // it('filter out non active open groups', async () => {

@ -1,7 +1,7 @@
// tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression // tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression
import chai from 'chai'; import chai from 'chai';
import * as sinon from 'sinon'; import Sinon, * as sinon from 'sinon';
import { PromiseUtils } from '../../../../session/utils'; import { PromiseUtils } from '../../../../session/utils';
@ -20,7 +20,6 @@ chai.should();
const { expect } = chai; const { expect } = chai;
describe('Promise Utils', () => { describe('Promise Utils', () => {
const sandbox = sinon.createSandbox();
let pollSpy: sinon.SinonSpy< let pollSpy: sinon.SinonSpy<
[ [
(done: (arg: any) => void) => Promise<void> | void, (done: (arg: any) => void) => Promise<void> | void,
@ -38,20 +37,20 @@ describe('Promise Utils', () => {
>; >;
beforeEach(() => { beforeEach(() => {
pollSpy = sandbox.spy(PromiseUtils, 'poll'); pollSpy = Sinon.spy(PromiseUtils, 'poll');
waitForTaskSpy = sandbox.spy(PromiseUtils, 'waitForTask'); waitForTaskSpy = Sinon.spy(PromiseUtils, 'waitForTask');
waitUntilSpy = sandbox.spy(PromiseUtils, 'waitUntil'); waitUntilSpy = Sinon.spy(PromiseUtils, 'waitUntil');
TestUtils.stubWindowLog(); TestUtils.stubWindowLog();
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
describe('poll', () => { describe('poll', () => {
it('will call done on finished', async () => { it('will call done on finished', async () => {
// completionSpy will be called on done // completionSpy will be called on done
const completionSpy = sandbox.spy(); const completionSpy = Sinon.spy();
// tslint:disable-next-line: mocha-unneeded-done // tslint:disable-next-line: mocha-unneeded-done
const task = (done: any) => { const task = (done: any) => {
@ -68,7 +67,7 @@ describe('Promise Utils', () => {
it('can timeout a task', () => { it('can timeout a task', () => {
// completionSpy will be called on done // completionSpy will be called on done
const completionSpy = sandbox.spy(); const completionSpy = Sinon.spy();
const task = (_done: any) => undefined; const task = (_done: any) => undefined;
const promise = PromiseUtils.poll(task, { timeoutMs: 1, interval: 10 }); const promise = PromiseUtils.poll(task, { timeoutMs: 1, interval: 10 });
@ -83,7 +82,7 @@ describe('Promise Utils', () => {
const timeout = 3000; const timeout = 3000;
const interval = 3; const interval = 3;
const recurrenceSpy = sandbox.spy(); const recurrenceSpy = Sinon.spy();
const task = (done: any) => { const task = (done: any) => {
recurrenceSpy(); recurrenceSpy();
@ -104,7 +103,7 @@ describe('Promise Utils', () => {
describe('waitForTask', () => { describe('waitForTask', () => {
it('can wait for a task', async () => { it('can wait for a task', async () => {
// completionSpy will be called on done // completionSpy will be called on done
const completionSpy = sandbox.spy(); const completionSpy = Sinon.spy();
// tslint:disable-next-line: mocha-unneeded-done // tslint:disable-next-line: mocha-unneeded-done
const task = (done: any) => { const task = (done: any) => {
@ -121,7 +120,7 @@ describe('Promise Utils', () => {
it('can timeout a task', () => { it('can timeout a task', () => {
// completionSpy will be called on done // completionSpy will be called on done
const completionSpy = sandbox.spy(); const completionSpy = Sinon.spy();
const task = async (_done: any) => undefined; const task = async (_done: any) => undefined;
const promise = PromiseUtils.waitForTask(task, 1); const promise = PromiseUtils.waitForTask(task, 1);

@ -1,17 +1,13 @@
// tslint:disable: no-implicit-dependencies // tslint:disable: no-implicit-dependencies
import chai from 'chai'; import chai from 'chai';
import * as sinon from 'sinon';
import { restoreStubs } from '../../../test-utils/utils';
import chaiAsPromised from 'chai-as-promised'; import chaiAsPromised from 'chai-as-promised';
import Sinon from 'sinon';
chai.use(chaiAsPromised as any); chai.use(chaiAsPromised as any);
describe('SyncUtils', () => { describe('SyncUtils', () => {
const sandbox = sinon.createSandbox();
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
restoreStubs();
}); });
describe('syncConfigurationIfNeeded', () => { describe('syncConfigurationIfNeeded', () => {

@ -1,8 +1,9 @@
import * as sinon from 'sinon'; import Sinon from 'sinon';
import * as DataShape from '../../../../ts/data/data'; import * as DataShape from '../../../../ts/data/data';
import * as utilWorker from '../../../webworker/workers/util_worker_interface';
const globalAny: any = global; const globalAny: any = global;
const sandbox = sinon.createSandbox();
// We have to do this in a weird way because Data uses module.exports // We have to do this in a weird way because Data uses module.exports
// which doesn't play well with sinon or ImportMock // which doesn't play well with sinon or ImportMock
@ -18,20 +19,29 @@ type DataFunction = typeof DataShape;
* Please call `restoreStubs()` or `stub.restore()` to restore original functionality. * Please call `restoreStubs()` or `stub.restore()` to restore original functionality.
*/ */
export function stubData<K extends keyof DataFunction>(fn: K): sinon.SinonStub { export function stubData<K extends keyof DataFunction>(fn: K): sinon.SinonStub {
return sandbox.stub(Data, fn); return Sinon.stub(Data, fn);
} }
export function stubDataItem<K extends keyof DataFunction>(fn: K): sinon.SinonStub { export function stubDataItem<K extends keyof DataFunction>(fn: K): sinon.SinonStub {
return sandbox.stub(DataItem, fn); return Sinon.stub(DataItem, fn);
}
export function stubUtilWorker(fnName: string, returnedValue: any): sinon.SinonStub {
return Sinon.stub(utilWorker, 'callUtilsWorker')
.withArgs(fnName)
.resolves(returnedValue);
}
export function stubCreateObjectUrl() {
(global as any).URL = {};
(global as any).URL.createObjectURL = function() {
return `${Date.now()}:${Math.floor(Math.random() * 1000)}`;
};
} }
type WindowValue<K extends keyof Window> = Partial<Window[K]> | undefined; type WindowValue<K extends keyof Window> = Partial<Window[K]> | undefined;
/** /**
* Stub a window object. * 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>) { export function stubWindow<K extends keyof Window>(fn: K, value: WindowValue<K>) {
// tslint:disable-next-line: no-typeof-undefined // tslint:disable-next-line: no-typeof-undefined
@ -55,11 +65,6 @@ export function stubWindow<K extends keyof Window>(fn: K, value: WindowValue<K>)
}; };
} }
export function restoreStubs() {
globalAny.window = undefined;
sandbox.restore();
}
export const stubWindowLog = () => { export const stubWindowLog = () => {
stubWindow('log', { stubWindow('log', {
// tslint:disable: no-void-expression // tslint:disable: no-void-expression

@ -5,16 +5,14 @@ import { assert } from 'chai';
import * as Settings from '../../../ts/types/Settings'; import * as Settings from '../../../ts/types/Settings';
describe('Settings', () => { describe('Settings', () => {
const sandbox = Sinon.createSandbox();
describe('isAudioNotificationSupported', () => { describe('isAudioNotificationSupported', () => {
context('on macOS', () => { context('on macOS', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('darwin'); Sinon.stub(process, 'platform').value('darwin');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return true', () => { it('should return true', () => {
@ -25,12 +23,12 @@ describe('Settings', () => {
context('on Windows', () => { context('on Windows', () => {
context('version 7', () => { context('version 7', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('win32'); Sinon.stub(process, 'platform').value('win32');
sandbox.stub(os, 'release').returns('7.0.0'); Sinon.stub(os, 'release').returns('7.0.0');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return false', () => { it('should return false', () => {
@ -40,12 +38,12 @@ describe('Settings', () => {
context('version 8+', () => { context('version 8+', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('win32'); Sinon.stub(process, 'platform').value('win32');
sandbox.stub(os, 'release').returns('8.0.0'); Sinon.stub(os, 'release').returns('8.0.0');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return true', () => { it('should return true', () => {
@ -56,11 +54,11 @@ describe('Settings', () => {
context('on Linux', () => { context('on Linux', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('linux'); Sinon.stub(process, 'platform').value('linux');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return false', () => { it('should return false', () => {
@ -72,11 +70,11 @@ describe('Settings', () => {
describe('isNotificationGroupingSupported', () => { describe('isNotificationGroupingSupported', () => {
context('on macOS', () => { context('on macOS', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('darwin'); Sinon.stub(process, 'platform').value('darwin');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return true', () => { it('should return true', () => {
@ -87,12 +85,12 @@ describe('Settings', () => {
context('on Windows', () => { context('on Windows', () => {
context('version 7', () => { context('version 7', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('win32'); Sinon.stub(process, 'platform').value('win32');
sandbox.stub(os, 'release').returns('7.0.0'); Sinon.stub(os, 'release').returns('7.0.0');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return false', () => { it('should return false', () => {
@ -102,12 +100,12 @@ describe('Settings', () => {
context('version 8+', () => { context('version 8+', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('win32'); Sinon.stub(process, 'platform').value('win32');
sandbox.stub(os, 'release').returns('8.0.0'); Sinon.stub(os, 'release').returns('8.0.0');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return true', () => { it('should return true', () => {
@ -118,11 +116,11 @@ describe('Settings', () => {
context('on Linux', () => { context('on Linux', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('linux'); Sinon.stub(process, 'platform').value('linux');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return true', () => { it('should return true', () => {
@ -133,11 +131,11 @@ describe('Settings', () => {
describe('isHideMenuBarSupported', () => { describe('isHideMenuBarSupported', () => {
context('on macOS', () => { context('on macOS', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('darwin'); Sinon.stub(process, 'platform').value('darwin');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return false', () => { it('should return false', () => {
@ -148,12 +146,12 @@ describe('Settings', () => {
context('on Windows', () => { context('on Windows', () => {
context('version 7', () => { context('version 7', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('win32'); Sinon.stub(process, 'platform').value('win32');
sandbox.stub(os, 'release').returns('7.0.0'); Sinon.stub(os, 'release').returns('7.0.0');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return true', () => { it('should return true', () => {
@ -163,12 +161,12 @@ describe('Settings', () => {
context('version 8+', () => { context('version 8+', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('win32'); Sinon.stub(process, 'platform').value('win32');
sandbox.stub(os, 'release').returns('8.0.0'); Sinon.stub(os, 'release').returns('8.0.0');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return true', () => { it('should return true', () => {
@ -179,11 +177,11 @@ describe('Settings', () => {
context('on Linux', () => { context('on Linux', () => {
beforeEach(() => { beforeEach(() => {
sandbox.stub(process, 'platform').value('linux'); Sinon.stub(process, 'platform').value('linux');
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
}); });
it('should return true', () => { it('should return true', () => {

@ -1,15 +1,14 @@
// tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression // tslint:disable: no-implicit-dependencies max-func-body-length no-unused-expression
import { expect } from 'chai'; import { expect } from 'chai';
import * as sinon from 'sinon';
import { BlockedNumberController } from '../../util/blockedNumberController'; import { BlockedNumberController } from '../../util/blockedNumberController';
import { TestUtils } from '../test-utils'; import { TestUtils } from '../test-utils';
import { PubKey } from '../../session/types'; import { PubKey } from '../../session/types';
import { UserUtils } from '../../session/utils'; import { UserUtils } from '../../session/utils';
import Sinon from 'sinon';
// tslint:disable-next-line: max-func-body-length // tslint:disable-next-line: max-func-body-length
describe('BlockedNumberController', () => { describe('BlockedNumberController', () => {
const sandbox = sinon.createSandbox();
let memoryDB: { [key: string]: any }; let memoryDB: { [key: string]: any };
beforeEach(() => { beforeEach(() => {
memoryDB = {}; memoryDB = {};
@ -33,8 +32,7 @@ describe('BlockedNumberController', () => {
}); });
afterEach(() => { afterEach(() => {
sandbox.restore(); Sinon.restore();
TestUtils.restoreStubs();
}); });
describe('load', () => { describe('load', () => {
@ -168,7 +166,7 @@ describe('BlockedNumberController', () => {
let ourDevice: PubKey; let ourDevice: PubKey;
beforeEach(() => { beforeEach(() => {
ourDevice = TestUtils.generateFakePubKey(); ourDevice = TestUtils.generateFakePubKey();
sandbox.stub(UserUtils, 'getOurPubKeyStrFromCache').returns(ourDevice.key); Sinon.stub(UserUtils, 'getOurPubKeyStrFromCache').returns(ourDevice.key);
}); });
it('should return false for our device', async () => { it('should return false for our device', async () => {
const isBlocked = await BlockedNumberController.isBlockedAsync(ourDevice); const isBlocked = await BlockedNumberController.isBlockedAsync(ourDevice);

@ -16,17 +16,6 @@ import {
// tslint:disable: prefer-object-spread // tslint:disable: prefer-object-spread
// FIXME audric
// upgrade: exports._mapAttachments(autoOrientJPEGAttachment),
// upgrade: exports._mapAttachments(replaceUnicodeOrderOverrides),
// upgrade: _mapAttachments(migrateDataToFileSystem),
// upgrade: ._mapQuotedAttachments(migrateDataToFileSystem),
// upgrade: initializeAttachmentMetadata,
// upgrade: initializeAttachmentMetadata,
// upgrade: _mapAttachments(captureDimensionsAndScreenshot),
// upgrade: _mapAttachments(replaceUnicodeV2),
// upgrade: _mapPreviewAttachments(migrateDataToFileSystem),
// I think this is only used on the renderer side, but how?! // I think this is only used on the renderer side, but how?!
export const deleteExternalMessageFiles = async (message: { export const deleteExternalMessageFiles = async (message: {

Loading…
Cancel
Save