From 4f0dbbe2324244c2021840a5b05d7c8dae59bcc1 Mon Sep 17 00:00:00 2001 From: Lawrence Forooghian Date: Mon, 10 Jun 2024 11:29:35 -0300 Subject: [PATCH] Update tests so that each has its own helper instance This removes the per-file SharedHelper instance and instead makes sure that each context which will call SharedHelper instance methods (e.g. test cases, test hooks) has a unique SharedHelper instance that is aware of the context from which it is being called. (Motivation for this change already explained in 1fa5e13.) --- test/browser/connection.test.js | 45 ++- test/browser/http.test.js | 3 +- test/browser/modular.test.js | 540 +++++++++++++++------------ test/browser/push.test.js | 3 +- test/browser/simple.test.js | 40 +- test/common/modules/shared_helper.js | 26 +- test/realtime/auth.test.js | 157 +++++--- test/realtime/channel.test.js | 60 ++- test/realtime/connection.test.js | 16 +- test/realtime/connectivity.test.js | 11 +- test/realtime/crypto.test.js | 74 ++-- test/realtime/delta.test.js | 8 +- test/realtime/encoding.test.js | 11 +- test/realtime/event_emitter.test.js | 48 ++- test/realtime/failure.test.js | 30 +- test/realtime/history.test.js | 4 +- test/realtime/init.test.js | 74 ++-- test/realtime/message.test.js | 45 ++- test/realtime/presence.test.js | 88 +++-- test/realtime/reauth.test.js | 54 +-- test/realtime/resume.test.js | 31 +- test/realtime/sync.test.js | 19 +- test/realtime/transports.test.js | 54 ++- test/realtime/utils.test.js | 3 +- test/rest/auth.test.js | 16 +- test/rest/batch.test.js | 11 +- test/rest/capability.test.js | 3 +- test/rest/fallbacks.test.js | 6 +- test/rest/history.test.js | 11 +- test/rest/http.test.js | 3 +- test/rest/init.test.js | 9 +- test/rest/message.test.js | 24 +- test/rest/presence.test.js | 3 +- test/rest/push.test.js | 70 ++-- test/rest/request.test.js | 5 +- test/rest/stats.test.js | 3 +- test/rest/status.test.js | 3 +- test/rest/time.test.js | 3 +- test/support/root_hooks.js | 14 +- 39 files changed, 1020 insertions(+), 608 deletions(-) diff --git a/test/browser/connection.test.js b/test/browser/connection.test.js index 5239d826e..2c000b148 100644 --- a/test/browser/connection.test.js +++ b/test/browser/connection.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['shared_helper', 'chai'], function (Helper, chai) { - const helper = new Helper(); - var { expect, assert } = chai; var transportPreferenceName = 'ably-transport-preference'; @@ -29,6 +27,7 @@ define(['shared_helper', 'chai'], function (Helper, chai) { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -43,6 +42,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @spec RTN20a */ it('device_going_offline_causes_disconnected_state', function (done) { + const helper = this.test.helper; + var realtime = helper.AblyRealtime(), connection = realtime.connection, offlineEvent = new Event('offline', { bubbles: true }); @@ -86,6 +87,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @spec RTN20b */ it('device_going_online_causes_disconnected_connection_to_reconnect_immediately', function (done) { + const helper = this.test.helper; + /* Give up trying to connect fairly quickly */ var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 1000 }), connection = realtime.connection, @@ -132,6 +135,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @spec RTN20b */ it('device_going_online_causes_suspended_connection_to_reconnect_immediately', function (done) { + const helper = this.test.helper; + /* move to suspended state after 2s of being disconnected */ var realtime = helper.AblyRealtime({ disconnectedRetryTimeout: 500, @@ -178,6 +183,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @spec RTN20c */ it('device_going_online_causes_connecting_connection_to_retry_attempt', function (done) { + const helper = this.test.helper; + var realtime = helper.AblyRealtime({}), connection = realtime.connection, onlineEvent = new Event('online', { bubbles: true }), @@ -217,6 +224,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @specpartial RTN16d */ it('page_refresh_with_recovery', function (done) { + const helper = this.test.helper; + var realtimeOpts = { recover: function (lastConnectionDetails, cb) { cb(true); @@ -259,6 +268,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @nospec */ it('page_refresh_persist_with_denied_recovery', function (done) { + const helper = this.test.helper; + var realtimeOpts = { recover: function (lastConnectionDetails, cb) { cb(false); @@ -302,10 +313,10 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @nospec */ it('page_refresh_with_close_on_unload', function (done) { - var realtime = helper.AblyRealtime({ closeOnUnload: true }), + var realtime = this.test.helper.AblyRealtime({ closeOnUnload: true }), refreshEvent = new Event('beforeunload', { bubbles: true }); - helper.monitorConnection(done, realtime); + this.test.helper.monitorConnection(done, realtime); realtime.connection.once('connected', function () { try { @@ -326,6 +337,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @specpartial RTN16d */ it('page_refresh_with_manual_recovery', function (done) { + const helper = this.test.helper; + var realtime = helper.AblyRealtime({ closeOnUnload: false }), refreshEvent = new Event('beforeunload', { bubbles: true }); @@ -364,12 +377,12 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); /** @nospec */ - it('page_refresh_with_multiple_recovery_scopes', async () => { + it('page_refresh_with_multiple_recovery_scopes', async function () { const realtimeOpts = { recover: (_, cb) => cb(true) }, opts1 = Object.assign({ recoveryKeyStorageName: 'recovery-1' }, realtimeOpts), opts2 = Object.assign({ recoveryKeyStorageName: 'recovery-2' }, realtimeOpts), - realtime1 = helper.AblyRealtime(opts1), - realtime2 = helper.AblyRealtime(opts2), + realtime1 = this.test.helper.AblyRealtime(opts1), + realtime2 = this.test.helper.AblyRealtime(opts2), refreshEvent = new Event('beforeunload', { bubbles: true }); await Promise.all([realtime1.connection.once('connected'), realtime2.connection.once('connected')]); @@ -378,24 +391,26 @@ define(['shared_helper', 'chai'], function (Helper, chai) { document.dispatchEvent(refreshEvent); - helper.simulateDroppedConnection(realtime1); - helper.simulateDroppedConnection(realtime2); + this.test.helper.simulateDroppedConnection(realtime1); + this.test.helper.simulateDroppedConnection(realtime2); await new Promise((res) => setTimeout(res, 1000)); - const newRealtime1 = helper.AblyRealtime(opts1); - const newRealtime2 = helper.AblyRealtime(opts2); + const newRealtime1 = this.test.helper.AblyRealtime(opts1); + const newRealtime2 = this.test.helper.AblyRealtime(opts2); await Promise.all([newRealtime1.connection.once('connected'), newRealtime2.connection.once('connected')]); assert.equal(connId1, newRealtime1.connection.id); assert.equal(connId2, newRealtime2.connection.id); await Promise.all( - [realtime1, realtime2, newRealtime1, newRealtime2].map((rt) => helper.closeAndFinishAsync(rt)), + [realtime1, realtime2, newRealtime1, newRealtime2].map((rt) => this.test.helper.closeAndFinishAsync(rt)), ); }); /** @nospec */ it('persist_preferred_transport', function (done) { + const helper = this.test.helper; + var realtime = helper.AblyRealtime(); realtime.connection.connectionManager.on(function (transport) { @@ -416,15 +431,15 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @nospec */ it('browser_transports', function (done) { - var realtime = helper.AblyRealtime(); + var realtime = this.test.helper.AblyRealtime(); try { expect(realtime.connection.connectionManager.baseTransport).to.equal('xhr_polling'); expect(realtime.connection.connectionManager.webSocketTransportAvailable).to.be.ok; } catch (err) { - helper.closeAndFinish(done, realtime, err); + this.test.helper.closeAndFinish(done, realtime, err); return; } - helper.closeAndFinish(done, realtime); + this.test.helper.closeAndFinish(done, realtime); }); }); } diff --git a/test/browser/http.test.js b/test/browser/http.test.js index f73d840f3..c84f909c2 100644 --- a/test/browser/http.test.js +++ b/test/browser/http.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { - const helper = new Helper(); - var rest; var expect = chai.expect; @@ -10,6 +8,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { this.timeout(60 * 1000); let initialXhrSupported; before(function (done) { + const helper = Helper.forHook(this); initialXhrSupported = Ably.Rest.Platform.Config.xhrSupported; Ably.Rest.Platform.Config.xhrSupported = false; helper.setupApp(function () { diff --git a/test/browser/modular.test.js b/test/browser/modular.test.js index 1e8e4c24b..128e69aaa 100644 --- a/test/browser/modular.test.js +++ b/test/browser/modular.test.js @@ -24,16 +24,15 @@ import { function registerAblyModularTests(Helper) { describe('browser/modular', function () { this.timeout(10 * 1000); - const helper = new Helper(); const expect = chai.expect; const BufferUtils = BaseRest.Platform.BufferUtils; - const loadTestData = async (dataPath) => { + const loadTestData = async (helper, dataPath) => { return new Promise((resolve, reject) => { helper.loadTestData(dataPath, (err, testData) => (err ? reject(err) : resolve(testData))); }); }; - async function monitorConnectionThenCloseAndFinish(action, realtime, states) { + async function monitorConnectionThenCloseAndFinish(helper, action, realtime, states) { try { await helper.monitorConnectionAsync(action, realtime, states); } finally { @@ -41,7 +40,8 @@ function registerAblyModularTests(Helper) { } } - before((done) => { + before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(done); }); @@ -84,10 +84,10 @@ function registerAblyModularTests(Helper) { describe('without any plugins', () => { for (const clientClass of [BaseRest, BaseRealtime]) { - describe(clientClass.name, () => { + describe(clientClass.name, function () { /** @nospec */ - it('throws an error due to the absence of an HTTP plugin', () => { - expect(() => new clientClass(helper.ablyClientOptions())).to.throw( + it('throws an error due to the absence of an HTTP plugin', function () { + expect(() => new clientClass(this.test.helper.ablyClientOptions())).to.throw( 'No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.', ); }); @@ -104,7 +104,7 @@ function registerAblyModularTests(Helper) { { description: 'call `time()`', action: (client) => client.time() }, { description: 'call `auth.createTokenRequest()` with `queryTime` option enabled', - action: (client) => + action: (client, helper) => client.auth.createTokenRequest(undefined, { key: helper.getTestApp().keys[0].keyStr /* if passing authOptions you have to explicitly pass the key */, queryTime: true, @@ -122,7 +122,7 @@ function registerAblyModularTests(Helper) { }, { description: 'call `auth.revokeTokens(...)`', - getAdditionalClientOptions: () => { + getAdditionalClientOptions: (helper) => { const testApp = helper.getTestApp(); return { key: testApp.keys[4].keyStr /* this key has revocableTokens enabled */ }; }, @@ -146,14 +146,15 @@ function registerAblyModularTests(Helper) { describe('BaseRest without explicit Rest', () => { for (const scenario of restScenarios) { /** @nospec */ - it(`allows you to ${scenario.description}`, async () => { + it(`allows you to ${scenario.description}`, async function () { + const helper = this.test.helper; const client = new BaseRest( - helper.ablyClientOptions({ ...scenario.getAdditionalClientOptions?.(), plugins: { FetchRequest } }), + helper.ablyClientOptions({ ...scenario.getAdditionalClientOptions?.(helper), plugins: { FetchRequest } }), ); let thrownError = null; try { - await scenario.action(client); + await scenario.action(client, helper); } catch (error) { thrownError = error; } @@ -166,11 +167,12 @@ function registerAblyModularTests(Helper) { describe('BaseRealtime with Rest', () => { for (const scenario of restScenarios) { /** @nospec */ - it(`allows you to ${scenario.description}`, async () => { + it(`allows you to ${scenario.description}`, async function () { + const helper = this.test.helper; const client = new BaseRealtime( helper.ablyClientOptions({ autoConnect: false, - ...scenario.getAdditionalClientOptions?.(), + ...scenario.getAdditionalClientOptions?.(helper), plugins: { WebSocketTransport, FetchRequest, @@ -182,7 +184,7 @@ function registerAblyModularTests(Helper) { let thrownError = null; try { - await scenario.action(client); + await scenario.action(client, helper); } catch (error) { thrownError = error; } @@ -194,30 +196,37 @@ function registerAblyModularTests(Helper) { describe('BaseRealtime without Rest', () => { /** @nospec */ - it('still allows publishing and subscribing', async () => { - const client = new BaseRealtime(helper.ablyClientOptions({ plugins: { WebSocketTransport, FetchRequest } })); + it('still allows publishing and subscribing', async function () { + const helper = this.test.helper; + const client = new BaseRealtime( + this.test.helper.ablyClientOptions({ plugins: { WebSocketTransport, FetchRequest } }), + ); - await monitorConnectionThenCloseAndFinish(async () => { - const channel = client.channels.get('channel'); - await channel.attach(); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + const channel = client.channels.get('channel'); + await channel.attach(); - const recievedMessagePromise = new Promise((resolve) => { - channel.subscribe((message) => { - resolve(message); + const recievedMessagePromise = new Promise((resolve) => { + channel.subscribe((message) => { + resolve(message); + }); }); - }); - await channel.publish({ data: { foo: 'bar' } }); + await channel.publish({ data: { foo: 'bar' } }); - const receivedMessage = await recievedMessagePromise; - expect(receivedMessage.data).to.eql({ foo: 'bar' }); - }, client); + const receivedMessage = await recievedMessagePromise; + expect(receivedMessage.data).to.eql({ foo: 'bar' }); + }, + client, + ); }); /** @nospec */ - it('allows `auth.createTokenRequest()` without `queryTime` option enabled', async () => { + it('allows `auth.createTokenRequest()` without `queryTime` option enabled', async function () { const client = new BaseRealtime( - helper.ablyClientOptions({ autoConnect: false, plugins: { WebSocketTransport, FetchRequest } }), + this.test.helper.ablyClientOptions({ autoConnect: false, plugins: { WebSocketTransport, FetchRequest } }), ); const tokenRequest = await client.auth.createTokenRequest(); @@ -226,11 +235,12 @@ function registerAblyModularTests(Helper) { for (const scenario of restScenarios) { /** @nospec */ - it(`throws an error when attempting to ${scenario.description}`, async () => { + it(`throws an error when attempting to ${scenario.description}`, async function () { + const helper = this.test.helper; const client = new BaseRealtime( - helper.ablyClientOptions({ + this.test.helper.ablyClientOptions({ autoConnect: false, - ...scenario.getAdditionalClientOptions?.(), + ...scenario.getAdditionalClientOptions?.(helper), plugins: { WebSocketTransport, FetchRequest, @@ -241,7 +251,7 @@ function registerAblyModularTests(Helper) { let thrownError = null; try { - await scenario.action(client); + await scenario.action(client, helper); } catch (error) { thrownError = error; } @@ -274,8 +284,8 @@ function registerAblyModularTests(Helper) { }); describe('Message standalone functions', () => { - async function testDecodesMessageData(functionUnderTest) { - const testData = await loadTestData(helper.testResourcesPath + 'crypto-data-128.json'); + async function testDecodesMessageData(helper, functionUnderTest) { + const testData = await loadTestData(helper, helper.testResourcesPath + 'crypto-data-128.json'); const item = testData.items[1]; const decoded = await functionUnderTest(item.encoded); @@ -290,13 +300,14 @@ function registerAblyModularTests(Helper) { * * @nospec */ - it('decodes a message’s data', async () => { - testDecodesMessageData(decodeMessage); + it('decodes a message’s data', async function () { + testDecodesMessageData(this.test.helper, decodeMessage); }); /** @nospec */ - it('throws an error when given channel options with a cipher', async () => { - const testData = await loadTestData(helper.testResourcesPath + 'crypto-data-128.json'); + it('throws an error when given channel options with a cipher', async function () { + const helper = this.test.helper; + const testData = await loadTestData(helper, helper.testResourcesPath + 'crypto-data-128.json'); const key = BufferUtils.base64Decode(testData.key); const iv = BufferUtils.base64Decode(testData.iv); @@ -314,13 +325,14 @@ function registerAblyModularTests(Helper) { describe('decodeEncryptedMessage', async () => { /** @nospec */ - it('decodes a message’s data', async () => { - testDecodesMessageData(decodeEncryptedMessage); + it('decodes a message’s data', async function () { + testDecodesMessageData(this.test.helper, decodeEncryptedMessage); }); /** @nospec */ - it('decrypts a message', async () => { - const testData = await loadTestData(helper.testResourcesPath + 'crypto-data-128.json'); + it('decrypts a message', async function () { + const helper = this.test.helper; + const testData = await loadTestData(helper, helper.testResourcesPath + 'crypto-data-128.json'); const key = BufferUtils.base64Decode(testData.key); const iv = BufferUtils.base64Decode(testData.iv); @@ -331,13 +343,13 @@ function registerAblyModularTests(Helper) { decodeEncryptedMessage(item.encrypted, { cipher: { key, iv } }), ]); - helper.testMessageEquality(decodedFromEncoded, decodedFromEncrypted); + this.test.helper.testMessageEquality(decodedFromEncoded, decodedFromEncrypted); } }); }); - async function testDecodesMessagesData(functionUnderTest) { - const testData = await loadTestData(helper.testResourcesPath + 'crypto-data-128.json'); + async function testDecodesMessagesData(helper, functionUnderTest) { + const testData = await loadTestData(helper, helper.testResourcesPath + 'crypto-data-128.json'); const items = [testData.items[1], testData.items[3]]; const decoded = await functionUnderTest(items.map((item) => item.encoded)); @@ -353,13 +365,14 @@ function registerAblyModularTests(Helper) { * * @nospec */ - it('decodes messages’ data', async () => { - testDecodesMessagesData(decodeMessages); + it('decodes messages’ data', async function () { + testDecodesMessagesData(this.test.helper, decodeMessages); }); /** @nospec */ - it('throws an error when given channel options with a cipher', async () => { - const testData = await loadTestData(helper.testResourcesPath + 'crypto-data-128.json'); + it('throws an error when given channel options with a cipher', async function () { + const helper = this.test.helper; + const testData = await loadTestData(helper, helper.testResourcesPath + 'crypto-data-128.json'); const key = BufferUtils.base64Decode(testData.key); const iv = BufferUtils.base64Decode(testData.iv); @@ -380,13 +393,14 @@ function registerAblyModularTests(Helper) { describe('decodeEncryptedMessages', () => { /** @nospec */ - it('decodes messages’ data', async () => { - testDecodesMessagesData(decodeEncryptedMessages); + it('decodes messages’ data', async function () { + testDecodesMessagesData(this.test.helper, decodeEncryptedMessages); }); /** @nospec */ - it('decrypts messages', async () => { - const testData = await loadTestData(helper.testResourcesPath + 'crypto-data-128.json'); + it('decrypts messages', async function () { + const helper = this.test.helper; + const testData = await loadTestData(helper, helper.testResourcesPath + 'crypto-data-128.json'); const key = BufferUtils.base64Decode(testData.key); const iv = BufferUtils.base64Decode(testData.iv); @@ -400,7 +414,7 @@ function registerAblyModularTests(Helper) { ]); for (let i = 0; i < decodedFromEncoded.length; i++) { - helper.testMessageEquality(decodedFromEncoded[i], decodedFromEncrypted[i]); + this.test.helper.testMessageEquality(decodedFromEncoded[i], decodedFromEncrypted[i]); } }); }); @@ -408,7 +422,7 @@ function registerAblyModularTests(Helper) { describe('Crypto', () => { describe('without Crypto', () => { - async function testThrowsAnErrorWhenGivenChannelOptionsWithACipher(clientClassConfig) { + async function testThrowsAnErrorWhenGivenChannelOptionsWithACipher(helper, clientClassConfig) { const client = new clientClassConfig.clientClass( helper.ablyClientOptions({ ...clientClassConfig.additionalClientOptions, @@ -432,15 +446,15 @@ function registerAblyModularTests(Helper) { ]) { describe(clientClassConfig.clientClass.name, () => { /** @nospec */ - it('throws an error when given channel options with a cipher', async () => { - await testThrowsAnErrorWhenGivenChannelOptionsWithACipher(clientClassConfig); + it('throws an error when given channel options with a cipher', async function () { + await testThrowsAnErrorWhenGivenChannelOptionsWithACipher(this.test.helper, clientClassConfig); }); }); } }); describe('with Crypto', () => { - async function testIsAbleToPublishEncryptedMessages(clientClassConfig) { + async function testIsAbleToPublishEncryptedMessages(helper, clientClassConfig) { const clientOptions = helper.ablyClientOptions(); const key = await generateRandomKey(); @@ -449,41 +463,48 @@ function registerAblyModularTests(Helper) { const rxClient = new BaseRealtime({ ...clientOptions, plugins: { WebSocketTransport, FetchRequest } }); - await monitorConnectionThenCloseAndFinish(async () => { - const rxChannel = rxClient.channels.get('channel'); - await rxChannel.attach(); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + const rxChannel = rxClient.channels.get('channel'); + await rxChannel.attach(); - const rxMessagePromise = new Promise((resolve, _) => rxChannel.subscribe((message) => resolve(message))); + const rxMessagePromise = new Promise((resolve, _) => rxChannel.subscribe((message) => resolve(message))); - const encryptionChannelOptions = { cipher: { key } }; + const encryptionChannelOptions = { cipher: { key } }; - const txMessage = { name: 'message', data: 'data' }; - const txClient = new clientClassConfig.clientClass({ - ...clientOptions, - plugins: { - ...clientClassConfig.additionalPlugins, - FetchRequest, - Crypto, - }, - }); + const txMessage = { name: 'message', data: 'data' }; + const txClient = new clientClassConfig.clientClass({ + ...clientOptions, + plugins: { + ...clientClassConfig.additionalPlugins, + FetchRequest, + Crypto, + }, + }); - await (clientClassConfig.isRealtime ? monitorConnectionThenCloseAndFinish : async (op) => await op())( - async () => { - const txChannel = txClient.channels.get('channel', encryptionChannelOptions); - await txChannel.publish(txMessage); + await (clientClassConfig.isRealtime + ? monitorConnectionThenCloseAndFinish + : async (helper, op) => await op())( + helper, + async () => { + const txChannel = txClient.channels.get('channel', encryptionChannelOptions); + await txChannel.publish(txMessage); - const rxMessage = await rxMessagePromise; + const rxMessage = await rxMessagePromise; - // Verify that the message was published with encryption - expect(rxMessage.encoding).to.equal('utf-8/cipher+aes-256-cbc'); + // Verify that the message was published with encryption + expect(rxMessage.encoding).to.equal('utf-8/cipher+aes-256-cbc'); - // Verify that the message was correctly encrypted - const rxMessageDecrypted = await decodeEncryptedMessage(rxMessage, encryptionChannelOptions); - helper.testMessageEquality(rxMessageDecrypted, txMessage); - }, - txClient, - ); - }, rxClient); + // Verify that the message was correctly encrypted + const rxMessageDecrypted = await decodeEncryptedMessage(rxMessage, encryptionChannelOptions); + helper.testMessageEquality(rxMessageDecrypted, txMessage); + }, + txClient, + ); + }, + rxClient, + ); } for (const clientClassConfig of [ @@ -496,8 +517,8 @@ function registerAblyModularTests(Helper) { ]) { describe(clientClassConfig.clientClass.name, () => { /** @nospec */ - it('is able to publish encrypted messages', async () => { - await testIsAbleToPublishEncryptedMessages(clientClassConfig); + it('is able to publish encrypted messages', async function () { + await testIsAbleToPublishEncryptedMessages(this.test.helper, clientClassConfig); }); }); } @@ -541,9 +562,9 @@ function registerAblyModularTests(Helper) { describe('without MsgPack', () => { describe('BaseRest', () => { /** @nospec */ - it('uses JSON', async () => { + it('uses JSON', async function () { const client = new BaseRest( - helper.ablyClientOptions({ useBinaryProtocol: true, plugins: { FetchRequest } }), + this.test.helper.ablyClientOptions({ useBinaryProtocol: true, plugins: { FetchRequest } }), ); await testRestUsesContentType(client, 'application/json'); }); @@ -551,7 +572,8 @@ function registerAblyModularTests(Helper) { describe('BaseRealtime', () => { /** @nospec */ - it('uses JSON', async () => { + it('uses JSON', async function () { + const helper = this.test.helper; const client = new BaseRealtime( helper.ablyClientOptions({ useBinaryProtocol: true, @@ -563,9 +585,13 @@ function registerAblyModularTests(Helper) { }), ); - await monitorConnectionThenCloseAndFinish(async () => { - await testRealtimeUsesFormat(client, 'json'); - }, client); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + await testRealtimeUsesFormat(client, 'json'); + }, + client, + ); }); }); }); @@ -573,9 +599,9 @@ function registerAblyModularTests(Helper) { describe('with MsgPack', () => { describe('BaseRest', () => { /** @nospec */ - it('uses MessagePack', async () => { + it('uses MessagePack', async function () { const client = new BaseRest( - helper.ablyClientOptions({ + this.test.helper.ablyClientOptions({ useBinaryProtocol: true, plugins: { FetchRequest, @@ -589,7 +615,8 @@ function registerAblyModularTests(Helper) { describe('BaseRealtime', () => { /** @nospec */ - it('uses MessagePack', async () => { + it('uses MessagePack', async function () { + const helper = this.test.helper; const client = new BaseRealtime( helper.ablyClientOptions({ useBinaryProtocol: true, @@ -602,9 +629,13 @@ function registerAblyModularTests(Helper) { }), ); - await monitorConnectionThenCloseAndFinish(async () => { - await testRealtimeUsesFormat(client, 'msgpack'); - }, client); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + await testRealtimeUsesFormat(client, 'msgpack'); + }, + client, + ); }); }); }); @@ -614,51 +645,65 @@ function registerAblyModularTests(Helper) { describe('RealtimePresence', () => { describe('BaseRealtime without RealtimePresence', () => { /** @nospec */ - it('throws an error when attempting to access the `presence` property', async () => { + it('throws an error when attempting to access the `presence` property', async function () { + const helper = this.test.helper; const client = new BaseRealtime(helper.ablyClientOptions({ plugins: { WebSocketTransport, FetchRequest } })); - await monitorConnectionThenCloseAndFinish(async () => { - const channel = client.channels.get('channel'); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + const channel = client.channels.get('channel'); - expect(() => channel.presence).to.throw('RealtimePresence plugin not provided'); - }, client); + expect(() => channel.presence).to.throw('RealtimePresence plugin not provided'); + }, + client, + ); }); /** @nospec */ - it('doesn’t break when it receives a PRESENCE ProtocolMessage', async () => { + it('doesn’t break when it receives a PRESENCE ProtocolMessage', async function () { + const helper = this.test.helper; const rxClient = new BaseRealtime( helper.ablyClientOptions({ plugins: { WebSocketTransport, FetchRequest } }), ); - await monitorConnectionThenCloseAndFinish(async () => { - const rxChannel = rxClient.channels.get('channel'); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + const rxChannel = rxClient.channels.get('channel'); - await rxChannel.attach(); + await rxChannel.attach(); - const receivedMessagePromise = new Promise((resolve) => rxChannel.subscribe(resolve)); + const receivedMessagePromise = new Promise((resolve) => rxChannel.subscribe(resolve)); - const txClient = new BaseRealtime( - helper.ablyClientOptions({ - clientId: Helper.randomString(), - plugins: { - WebSocketTransport, - FetchRequest, - RealtimePresence, - }, - }), - ); + const txClient = new BaseRealtime( + this.test.helper.ablyClientOptions({ + clientId: Helper.randomString(), + plugins: { + WebSocketTransport, + FetchRequest, + RealtimePresence, + }, + }), + ); - await monitorConnectionThenCloseAndFinish(async () => { - const txChannel = txClient.channels.get('channel'); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + const txChannel = txClient.channels.get('channel'); - await txChannel.publish('message', 'body'); - await txChannel.presence.enter(); + await txChannel.publish('message', 'body'); + await txChannel.presence.enter(); - // The idea being here that in order for receivedMessagePromise to resolve, rxClient must have first processed the PRESENCE ProtocolMessage that resulted from txChannel.presence.enter() + // The idea being here that in order for receivedMessagePromise to resolve, rxClient must have first processed the PRESENCE ProtocolMessage that resulted from txChannel.presence.enter() - await receivedMessagePromise; - }, txClient); - }, rxClient); + await receivedMessagePromise; + }, + txClient, + ); + }, + rxClient, + ); }); }); @@ -669,7 +714,8 @@ function registerAblyModularTests(Helper) { * * @nospec */ - it('offers realtime presence functionality', async () => { + it('offers realtime presence functionality', async function () { + const helper = this.test.helper; const rxClient = new BaseRealtime( helper.ablyClientOptions({ plugins: { @@ -681,33 +727,41 @@ function registerAblyModularTests(Helper) { ); const rxChannel = rxClient.channels.get('channel'); - await monitorConnectionThenCloseAndFinish(async () => { - const txClientId = Helper.randomString(); - const txClient = new BaseRealtime( - helper.ablyClientOptions({ - clientId: txClientId, - plugins: { - WebSocketTransport, - FetchRequest, - RealtimePresence, - }, - }), - ); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + const txClientId = Helper.randomString(); + const txClient = new BaseRealtime( + this.test.helper.ablyClientOptions({ + clientId: txClientId, + plugins: { + WebSocketTransport, + FetchRequest, + RealtimePresence, + }, + }), + ); - await monitorConnectionThenCloseAndFinish(async () => { - const txChannel = txClient.channels.get('channel'); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + const txChannel = txClient.channels.get('channel'); - let resolveRxPresenceMessagePromise; - const rxPresenceMessagePromise = new Promise((resolve, reject) => { - resolveRxPresenceMessagePromise = resolve; - }); - await rxChannel.presence.subscribe('enter', resolveRxPresenceMessagePromise); - await txChannel.presence.enter(); + let resolveRxPresenceMessagePromise; + const rxPresenceMessagePromise = new Promise((resolve, reject) => { + resolveRxPresenceMessagePromise = resolve; + }); + await rxChannel.presence.subscribe('enter', resolveRxPresenceMessagePromise); + await txChannel.presence.enter(); - const rxPresenceMessage = await rxPresenceMessagePromise; - expect(rxPresenceMessage.clientId).to.equal(txClientId); - }, txClient); - }, rxClient); + const rxPresenceMessage = await rxPresenceMessagePromise; + expect(rxPresenceMessage.clientId).to.equal(txClientId); + }, + txClient, + ); + }, + rxClient, + ); }); }); }); @@ -772,8 +826,8 @@ function registerAblyModularTests(Helper) { describe('BaseRealtime', () => { describe('without a transport plugin', () => { /** @nospec */ - it('throws an error due to absence of a transport plugin', () => { - expect(() => new BaseRealtime(helper.ablyClientOptions({ plugins: { FetchRequest } }))).to.throw( + it('throws an error due to absence of a transport plugin', function () { + expect(() => new BaseRealtime(this.test.helper.ablyClientOptions({ plugins: { FetchRequest } }))).to.throw( 'no requested transports available', ); }); @@ -788,7 +842,8 @@ function registerAblyModularTests(Helper) { * Tests RTN1 support for modular bundle. * @nospec */ - it(`is able to use the ${scenario.transportName} transport`, async () => { + it(`is able to use the ${scenario.transportName} transport`, async function () { + const helper = this.test.helper; const realtime = new BaseRealtime( helper.ablyClientOptions({ autoConnect: false, @@ -800,22 +855,26 @@ function registerAblyModularTests(Helper) { }), ); - await monitorConnectionThenCloseAndFinish(async () => { - let firstTransportCandidate; - const connectionManager = realtime.connection.connectionManager; - const originalTryATransport = connectionManager.tryATransport; - realtime.connection.connectionManager.tryATransport = (transportParams, candidate, callback) => { - if (!firstTransportCandidate) { - firstTransportCandidate = candidate; - } - originalTryATransport.bind(connectionManager)(transportParams, candidate, callback); - }; - - realtime.connect(); - - await realtime.connection.once('connected'); - expect(firstTransportCandidate).to.equal(scenario.transportName); - }, realtime); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + let firstTransportCandidate; + const connectionManager = realtime.connection.connectionManager; + const originalTryATransport = connectionManager.tryATransport; + realtime.connection.connectionManager.tryATransport = (transportParams, candidate, callback) => { + if (!firstTransportCandidate) { + firstTransportCandidate = candidate; + } + originalTryATransport.bind(connectionManager)(transportParams, candidate, callback); + }; + + realtime.connect(); + + await realtime.connection.once('connected'); + expect(firstTransportCandidate).to.equal(scenario.transportName); + }, + realtime, + ); }); }); } @@ -825,7 +884,7 @@ function registerAblyModularTests(Helper) { describe('HTTP request implementations', () => { describe('with multiple HTTP request implementations', () => { /** @nospec */ - it('prefers XHR', async () => { + it('prefers XHR', async function () { let usedXHR = false; const XHRRequestSpy = class XHRRequestSpy extends XHRRequest { @@ -835,7 +894,9 @@ function registerAblyModularTests(Helper) { } }; - const rest = new BaseRest(helper.ablyClientOptions({ plugins: { FetchRequest, XHRRequest: XHRRequestSpy } })); + const rest = new BaseRest( + this.test.helper.ablyClientOptions({ plugins: { FetchRequest, XHRRequest: XHRRequestSpy } }), + ); await rest.time(); expect(usedXHR).to.be.true; @@ -847,43 +908,53 @@ function registerAblyModularTests(Helper) { describe('BaseRealtime', () => { describe('without MessageInteractions', () => { /** @nospec */ - it('is able to subscribe to and unsubscribe from channel events, as long as a MessageFilter isn’t passed', async () => { + it('is able to subscribe to and unsubscribe from channel events, as long as a MessageFilter isn’t passed', async function () { + const helper = this.test.helper; const realtime = new BaseRealtime( helper.ablyClientOptions({ plugins: { WebSocketTransport, FetchRequest } }), ); - await monitorConnectionThenCloseAndFinish(async () => { - const channel = realtime.channels.get('channel'); - await channel.attach(); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + const channel = realtime.channels.get('channel'); + await channel.attach(); - const subscribeReceivedMessagePromise = new Promise((resolve) => channel.subscribe(resolve)); + const subscribeReceivedMessagePromise = new Promise((resolve) => channel.subscribe(resolve)); - await channel.publish('message', 'body'); + await channel.publish('message', 'body'); - const subscribeReceivedMessage = await subscribeReceivedMessagePromise; - expect(subscribeReceivedMessage.data).to.equal('body'); - }, realtime); + const subscribeReceivedMessage = await subscribeReceivedMessagePromise; + expect(subscribeReceivedMessage.data).to.equal('body'); + }, + realtime, + ); }); /** @nospec */ - it('throws an error when attempting to subscribe to channel events using a MessageFilter', async () => { + it('throws an error when attempting to subscribe to channel events using a MessageFilter', async function () { + const helper = this.test.helper; const realtime = new BaseRealtime( helper.ablyClientOptions({ plugins: { WebSocketTransport, FetchRequest } }), ); - await monitorConnectionThenCloseAndFinish(async () => { - const channel = realtime.channels.get('channel'); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + const channel = realtime.channels.get('channel'); - let thrownError = null; - try { - await channel.subscribe({ clientId: 'someClientId' }, () => {}); - } catch (error) { - thrownError = error; - } + let thrownError = null; + try { + await channel.subscribe({ clientId: 'someClientId' }, () => {}); + } catch (error) { + thrownError = error; + } - expect(thrownError).not.to.be.null; - expect(thrownError.message).to.equal('MessageInteractions plugin not provided'); - }, realtime); + expect(thrownError).not.to.be.null; + expect(thrownError.message).to.equal('MessageInteractions plugin not provided'); + }, + realtime, + ); }); }); @@ -892,7 +963,8 @@ function registerAblyModularTests(Helper) { * Tests RTL22d, MFI2e but for a MessageInteractions plugin with modular BaseRealtime. * @nospec */ - it('can take a MessageFilter argument when subscribing to and unsubscribing from channel events', async () => { + it('can take a MessageFilter argument when subscribing to and unsubscribing from channel events', async function () { + const helper = this.test.helper; const realtime = new BaseRealtime( helper.ablyClientOptions({ plugins: { @@ -903,52 +975,56 @@ function registerAblyModularTests(Helper) { }), ); - await monitorConnectionThenCloseAndFinish(async () => { - const channel = realtime.channels.get('channel'); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + const channel = realtime.channels.get('channel'); - await channel.attach(); + await channel.attach(); - // Test `subscribe` with a filter: send two messages with different clientIds, and check that unfiltered subscription receives both messages but clientId-filtered subscription only receives the matching one. - const messageFilter = { clientId: 'someClientId' }; // note that `unsubscribe` compares filter by reference, I found that a bit surprising + // Test `subscribe` with a filter: send two messages with different clientIds, and check that unfiltered subscription receives both messages but clientId-filtered subscription only receives the matching one. + const messageFilter = { clientId: 'someClientId' }; // note that `unsubscribe` compares filter by reference, I found that a bit surprising - const filteredSubscriptionReceivedMessages = []; - channel.subscribe(messageFilter, (message) => { - filteredSubscriptionReceivedMessages.push(message); - }); + const filteredSubscriptionReceivedMessages = []; + channel.subscribe(messageFilter, (message) => { + filteredSubscriptionReceivedMessages.push(message); + }); - const unfilteredSubscriptionReceivedFirstTwoMessagesPromise = new Promise((resolve) => { - const receivedMessages = []; - channel.subscribe(function listener(message) { - receivedMessages.push(message); - if (receivedMessages.length === 2) { - channel.unsubscribe(listener); - resolve(); - } + const unfilteredSubscriptionReceivedFirstTwoMessagesPromise = new Promise((resolve) => { + const receivedMessages = []; + channel.subscribe(function listener(message) { + receivedMessages.push(message); + if (receivedMessages.length === 2) { + channel.unsubscribe(listener); + resolve(); + } + }); }); - }); - await channel.publish(await decodeMessage({ clientId: 'someClientId' })); - await channel.publish(await decodeMessage({ clientId: 'someOtherClientId' })); - await unfilteredSubscriptionReceivedFirstTwoMessagesPromise; + await channel.publish(await decodeMessage({ clientId: 'someClientId' })); + await channel.publish(await decodeMessage({ clientId: 'someOtherClientId' })); + await unfilteredSubscriptionReceivedFirstTwoMessagesPromise; - expect(filteredSubscriptionReceivedMessages.length).to.equal(1); - expect(filteredSubscriptionReceivedMessages[0].clientId).to.equal('someClientId'); + expect(filteredSubscriptionReceivedMessages.length).to.equal(1); + expect(filteredSubscriptionReceivedMessages[0].clientId).to.equal('someClientId'); - // Test `unsubscribe` with a filter: call `unsubscribe` with the clientId filter, publish a message matching the filter, check that only the unfiltered listener recieves it - channel.unsubscribe(messageFilter); + // Test `unsubscribe` with a filter: call `unsubscribe` with the clientId filter, publish a message matching the filter, check that only the unfiltered listener recieves it + channel.unsubscribe(messageFilter); - const unfilteredSubscriptionReceivedNextMessagePromise = new Promise((resolve) => { - channel.subscribe(function listener() { - channel.unsubscribe(listener); - resolve(); + const unfilteredSubscriptionReceivedNextMessagePromise = new Promise((resolve) => { + channel.subscribe(function listener() { + channel.unsubscribe(listener); + resolve(); + }); }); - }); - await channel.publish(await decodeMessage({ clientId: 'someClientId' })); - await unfilteredSubscriptionReceivedNextMessagePromise; + await channel.publish(await decodeMessage({ clientId: 'someClientId' })); + await unfilteredSubscriptionReceivedNextMessagePromise; - expect(filteredSubscriptionReceivedMessages.length).to./* (still) */ equal(1); - }, realtime); + expect(filteredSubscriptionReceivedMessages.length).to./* (still) */ equal(1); + }, + realtime, + ); }); }); }); diff --git a/test/browser/push.test.js b/test/browser/push.test.js index 216d370c8..cef28ecc8 100644 --- a/test/browser/push.test.js +++ b/test/browser/push.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'chai', 'push'], function (Ably, Helper, chai, PushPlugin) { - const helper = new Helper(); - const expect = chai.expect; const swUrl = '/push_sw.js'; let rest; @@ -29,6 +27,7 @@ define(['ably', 'shared_helper', 'chai', 'push'], function (Ably, Helper, chai, this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function () { rest = helper.AblyRest({ pushServiceWorkerUrl: swUrl, diff --git a/test/browser/simple.test.js b/test/browser/simple.test.js index 1ca61c8d3..5e4e15df8 100644 --- a/test/browser/simple.test.js +++ b/test/browser/simple.test.js @@ -1,13 +1,12 @@ 'use strict'; define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { - const helper = new Helper(); - var expect = chai.expect; describe('browser/simple', function () { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -21,7 +20,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { return transport in Ably.Realtime.ConnectionManager.supportedTransports(Ably.Realtime._transports); } - function realtimeConnection(transports) { + function realtimeConnection(helper, transports) { var options = {}; if (transports) options.transports = transports; return helper.AblyRealtime(options); @@ -40,9 +39,9 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }; } - function connectionWithTransport(done, transport) { + function connectionWithTransport(done, helper, transport) { try { - var ably = realtimeConnection(transport && [transport]), + var ably = realtimeConnection(helper, transport && [transport]), connectionTimeout = failWithin(10, done, ably, 'connect'); ably.connection.on('connected', function () { connectionTimeout.stop(); @@ -64,9 +63,9 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { } } - function heartbeatWithTransport(done, transport) { + function heartbeatWithTransport(done, helper, transport) { try { - var ably = realtimeConnection(transport && [transport]), + var ably = realtimeConnection(helper, transport && [transport]), connectionTimeout = failWithin(10, done, ably, 'connect'), heartbeatTimeout; @@ -95,7 +94,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { } } - function publishWithTransport(done, transport) { + function publishWithTransport(done, helper, transport) { var count = 5; var sentCount = 0, receivedCount = 0, @@ -108,7 +107,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { ably.close(); } }; - var ably = realtimeConnection(transport && [transport]), + var ably = realtimeConnection(helper, transport && [transport]), connectionTimeout = failWithin(5, done, ably, 'connect'), receiveMessagesTimeout; @@ -140,8 +139,9 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { */ it('simpleInitBase0', function (done) { try { - var timeout, - ably = realtimeConnection(); + var helper = this.test.helper, + timeout, + ably = realtimeConnection(helper); ably.connection.on('connected', function () { clearTimeout(timeout); @@ -173,7 +173,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('wsbase0', function (done) { - connectionWithTransport(done, wsTransport); + connectionWithTransport(done, this.test.helper, wsTransport); }); /** @@ -183,7 +183,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('wspublish0', function (done) { - publishWithTransport(done, wsTransport); + publishWithTransport(done, this.test.helper, wsTransport); }); /** @@ -193,7 +193,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('wsheartbeat0', function (done) { - heartbeatWithTransport(done, wsTransport); + heartbeatWithTransport(done, this.test.helper, wsTransport); }); } @@ -205,7 +205,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('xhrpollingbase0', function (done) { - connectionWithTransport(done, xhrPollingTransport); + connectionWithTransport(done, this.test.helper, xhrPollingTransport); }); /** @@ -215,7 +215,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('xhrpollingpublish0', function (done) { - publishWithTransport(done, xhrPollingTransport); + publishWithTransport(done, this.test.helper, xhrPollingTransport); }); /** @@ -225,7 +225,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('xhrpollingheartbeat0', function (done) { - heartbeatWithTransport(done, xhrPollingTransport); + heartbeatWithTransport(done, this.test.helper, xhrPollingTransport); }); } @@ -235,7 +235,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('auto_transport_base0', function (done) { - connectionWithTransport(done); + connectionWithTransport(done, this.test.helper); }); /** @@ -245,7 +245,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('auto_transport_publish0', function (done) { - publishWithTransport(done); + publishWithTransport(done, this.test.helper); }); /** @@ -255,7 +255,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('auto_transport_heartbeat0', function (done) { - heartbeatWithTransport(done); + heartbeatWithTransport(done, this.test.helper); }); }); }); diff --git a/test/common/modules/shared_helper.js b/test/common/modules/shared_helper.js index e0d0906eb..139213ad9 100644 --- a/test/common/modules/shared_helper.js +++ b/test/common/modules/shared_helper.js @@ -43,6 +43,28 @@ define([ unroutableAddress = unroutableAddress; flushTestLogs = globals.flushLogs; + constructor(context) { + if (!context) { + throw new Error('SharedHelper created without context'); + } + this.context = context; + } + + static forTest(thisInBeforeEach) { + return new this(thisInBeforeEach.currentTest.fullTitle()); + } + + static forHook(thisInHook) { + return new this(thisInHook.test.fullTitle()); + } + + static forTestDefinition(thisInDescribe, label) { + if (!label) { + throw new Error('SharedHelper.forTestDefinition called without label'); + } + return new this(`${thisInDescribe.title} (defining ${label})`); + } + displayError(err) { if (typeof err == 'string' || err == null) return err; @@ -198,10 +220,10 @@ define([ static restTestOnJsonMsgpack(name, testFn, skip) { var itFn = skip ? it.skip : it; itFn(name + ' with binary protocol', async function () { - await testFn(new clientModule.AblyRest({ useBinaryProtocol: true }), name + '_binary'); + await testFn(new clientModule.AblyRest({ useBinaryProtocol: true }), name + '_binary', this.test.helper); }); itFn(name + ' with text protocol', async function () { - await testFn(new clientModule.AblyRest({ useBinaryProtocol: false }), name + '_text'); + await testFn(new clientModule.AblyRest({ useBinaryProtocol: false }), name + '_text', this.test.helper); }); } diff --git a/test/realtime/auth.test.js b/test/realtime/auth.test.js index 1d4c4ae5f..ac5487676 100644 --- a/test/realtime/auth.test.js +++ b/test/realtime/auth.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var currentTime; var exampleTokenDetails; var exports = {}; @@ -29,6 +27,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -61,7 +60,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSA8a */ it('authbase0', function (done) { - var realtime = helper.AblyRealtime({ queryTime: true }); + var helper = this.test.helper, + realtime = helper.AblyRealtime({ queryTime: true }); Helper.whenPromiseSettles(realtime.auth.requestToken(), function (err, tokenDetails) { if (err) { helper.closeAndFinish(done, realtime, err); @@ -87,7 +87,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSA8c - expect JSON TokenDetails */ it('auth_useAuthUrl_json', function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { @@ -117,7 +118,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSA8c - expect JSON TokenDetails from a POST request */ it('auth_useAuthUrl_post_json', function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { @@ -146,7 +148,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSA8g - test authURL returned ably token string */ it('auth_useAuthUrl_plainText', function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { @@ -175,7 +178,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial TO3j5 - can pass authCallback property */ it('auth_useAuthCallback_tokenRequestResponse', function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); var authCallback = function (tokenParams, callback) { Helper.whenPromiseSettles(rest.auth.createTokenRequest(tokenParams, null), function (err, tokenRequest) { @@ -216,7 +220,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial TO3j5 - can pass authCallback property */ it('auth_useAuthCallback_tokenDetailsResponse', function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { @@ -258,7 +263,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSA8g - authCallback returned ably token string */ it('auth_useAuthCallback_tokenStringResponse', function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); var authCallback = function (tokenParams, callback) { Helper.whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { @@ -298,7 +304,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSA8c1c */ it('auth_useAuthUrl_mixed_authParams_qsParams', function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.createTokenRequest(null, null), function (err, tokenRequest) { if (err) { @@ -336,7 +343,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSA7b2 */ it('auth_clientid_inheritance', function (done) { - var rest = helper.AblyRest(), + var helper = this.test.helper, + rest = helper.AblyRest(), testClientId = 'testClientId'; var authCallback = function (tokenParams, callback) { Helper.whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { @@ -376,7 +384,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSA15c */ it('auth_clientid_inheritance2', function (done) { - var clientRealtime, + var helper = this.test.helper, + clientRealtime, testClientId = 'test client id'; var rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { @@ -404,7 +413,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSA15b */ it('auth_clientid_inheritance3', function (done) { - var realtime, + var helper = this.test.helper, + realtime, testClientId = 'test client id'; var rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ clientId: '*' }), function (err, tokenDetails) { @@ -434,7 +444,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSA15b */ it('auth_clientid_inheritance4', function (done) { - var realtime, + var helper = this.test.helper, + realtime, testClientId = 'test client id'; var rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ clientId: '*' }), function (err, tokenDetails) { @@ -464,7 +475,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSA7b3 */ it('auth_clientid_inheritance5', function (done) { - var clientRealtime, + var helper = this.test.helper, + clientRealtime, testClientId = 'test client id'; var rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { @@ -490,9 +502,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * RSA4c, RSA4e * Try to connect with an authCallback that fails in various ways (calling back with an error, calling back with nothing, timing out, etc) should go to disconnected, not failed, and wrapped in a 80019 error code */ - function authCallback_failures(realtimeOptions, expectFailure) { + function authCallback_failures(createRealtimeOptions, expectFailure) { return function (done) { - var realtime = helper.AblyRealtime(realtimeOptions); + const helper = this.test.helper; + var realtime = helper.AblyRealtime(createRealtimeOptions(helper)); realtime.connection.on(function (stateChange) { if (stateChange.previous !== 'initialized') { try { @@ -526,11 +539,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it( 'authCallback_error', - authCallback_failures({ + authCallback_failures(() => ({ authCallback: function (tokenParams, callback) { callback(new Error('An error from client code that the authCallback might return')); }, - }), + })), ); /** @@ -540,12 +553,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it( 'authCallback_timeout', - authCallback_failures({ + authCallback_failures(() => ({ authCallback: function () { /* (^._.^)ノ */ }, realtimeRequestTimeout: 100, - }), + })), ); /** @@ -555,11 +568,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it( 'authCallback_nothing', - authCallback_failures({ + authCallback_failures(() => ({ authCallback: function (tokenParams, callback) { callback(); }, - }), + })), ); /** @@ -570,11 +583,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it( 'authCallback_malformed', - authCallback_failures({ + authCallback_failures(() => ({ authCallback: function (tokenParams, callback) { callback(null, { horse: 'ebooks' }); }, - }), + })), ); /** @@ -585,7 +598,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it( 'authCallback_too_long_string', - authCallback_failures({ + authCallback_failures(() => ({ authCallback: function (tokenParams, callback) { var token = ''; for (var i = 0; i < Math.pow(2, 17) + 1; i++) { @@ -593,7 +606,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async } callback(null, token); }, - }), + })), ); /** @@ -603,11 +616,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it( 'authCallback_empty_string', - authCallback_failures({ + authCallback_failures(() => ({ authCallback: function (tokenParams, callback) { callback(null, ''); }, - }), + })), ); /** @@ -617,10 +630,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it( 'authUrl_timeout', - authCallback_failures({ + authCallback_failures((helper) => ({ authUrl: helper.unroutableAddress, realtimeRequestTimeout: 100, - }), + })), ); /** @@ -630,9 +643,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it( 'authUrl_404', - authCallback_failures({ + authCallback_failures(() => ({ authUrl: 'http://example.com/404', - }), + })), ); /** @@ -643,9 +656,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it( 'authUrl_wrong_content_type', - authCallback_failures({ + authCallback_failures(() => ({ authUrl: 'http://example.com/', - }), + })), ); /** @@ -655,9 +668,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it( 'authUrl_401', - authCallback_failures({ + authCallback_failures(() => ({ authUrl: echoServer + '/respondwith?status=401', - }), + })), ); /** @@ -667,10 +680,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it( 'authUrl_double_encoded', - authCallback_failures({ + authCallback_failures(() => ({ authUrl: echoServer + '/?type=json&body=' + encodeURIComponent(JSON.stringify(JSON.stringify({ keyName: 'foo.bar' }))), - }), + })), ); /** @@ -681,9 +694,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async it( 'authUrl_403', authCallback_failures( - { + () => ({ authUrl: echoServer + '/respondwith?status=403', - }, + }), true, ), ); /* expectFailed: */ @@ -696,12 +709,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async it( 'authUrl_403_custom_error', authCallback_failures( - { + () => ({ authUrl: echoServer + '/?status=403&type=json&body=' + encodeURIComponent(JSON.stringify({ error: { some_custom: 'error' } })), - }, + }), true, ), ); @@ -711,7 +724,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSA4d1 - explicit authorize() call */ it('authUrl_403_previously_active', function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { @@ -756,7 +770,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('auth_token_expires', function (realtimeOpts) { return function (done) { - var clientRealtime, + var helper = this.test.helper, + clientRealtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ ttl: 5000 }, null), function (err, tokenDetails) { @@ -796,7 +811,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec TO3j10 */ it('auth_query_time_once', function (done) { - var rest = helper.AblyRest({ queryTime: true }), + var helper = this.test.helper, + rest = helper.AblyRest({ queryTime: true }), timeRequestCount = 0, originalTime = rest.time; @@ -857,7 +873,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('auth_tokenDetails_expiry_with_authcallback', function (realtimeOpts) { return function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { @@ -904,7 +921,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('auth_token_string_expiry_with_authcallback', function (realtimeOpts) { return function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { @@ -949,7 +967,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('auth_token_string_expiry_with_token', function (realtimeOpts) { return function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); var clientId = 'test clientid'; Helper.whenPromiseSettles( @@ -995,7 +1014,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('auth_expired_token_string', function (realtimeOpts) { return function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); var clientId = 'test clientid'; Helper.whenPromiseSettles( @@ -1043,7 +1063,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports.skip('reauth_authCallback', function (realtimeOpts) { return function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); var firstTime = true; var authCallback = function (tokenParams, callback) { @@ -1096,12 +1117,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RSA10j */ it('authorize_updates_stored_details', function (done) { - var realtime = helper.AblyRealtime({ - autoConnect: false, - defaultTokenParams: { version: 1 }, - token: '1', - authUrl: '1', - }); + var helper = this.test.helper, + realtime = helper.AblyRealtime({ + autoConnect: false, + defaultTokenParams: { version: 1 }, + token: '1', + authUrl: '1', + }); try { expect(realtime.auth.tokenParams.version).to.equal(1, 'Check initial defaultTokenParams stored'); @@ -1129,7 +1151,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTN22 */ it('mocked_reauth', function (done) { - var rest = helper.AblyRest(), + var helper = this.test.helper, + rest = helper.AblyRest(), authCallback = function (tokenParams, callback) { // Request a token (should happen twice) Helper.whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { @@ -1171,6 +1194,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSA8g - authCallback returned JWT token string */ it('auth_jwt_with_clientid', function (done) { + const helper = this.test.helper; var currentKey = helper.getTestApp().keys[0]; var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var clientId = 'testJWTClientId'; @@ -1209,6 +1233,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSA8g - authCallback returned JWT token string */ it('auth_jwt_with_clientid_application_jwt', function (done) { + const helper = this.test.helper; var currentKey = helper.getTestApp().keys[0]; var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret, returnType: 'jwt' }; var clientId = 'testJWTClientId'; @@ -1244,6 +1269,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('auth_jwt_with_subscribe_only_capability', function (done) { + const helper = this.test.helper; var currentKey = helper.getTestApp().keys[3]; // get subscribe-only keys { "*":["subscribe"] } var params = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var authCallback = function (tokenParams, callback) { @@ -1273,6 +1299,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('auth_jwt_with_publish_capability', function (done) { + const helper = this.test.helper; var currentKey = helper.getTestApp().keys[0]; var params = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var authCallback = function (tokenParams, callback) { @@ -1304,6 +1331,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSA4b */ it('auth_jwt_with_token_that_expires', function (done) { + const helper = this.test.helper; var currentKey = helper.getTestApp().keys[0]; var params = { keyName: currentKey.keyName, keySecret: currentKey.keySecret, expiresIn: 5 }; var authCallback = function (tokenParams, callback) { @@ -1332,6 +1360,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSA10e - obtain new token from authcallback when previous expires */ it('auth_jwt_with_token_that_renews', function (done) { + const helper = this.test.helper; var currentKey = helper.getTestApp().keys[0]; // Sandbox sends an auth protocol message 30 seconds before a token expires. // We create a token that lasts 35 so there's room to receive the update event message. @@ -1362,6 +1391,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec TN3 */ it('init_client_with_simple_jwt_token', function (done) { + const helper = this.test.helper; var currentKey = helper.getTestApp().keys[0]; var params = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; getJWT(params, function (err, token) { @@ -1384,7 +1414,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTN14b */ it('reauth_consistently_expired_token', function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ ttl: 1 }), function (err, token) { if (err) { @@ -1417,7 +1448,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @specpartial RSA4b1 - only autoremove expired tokens if have a server time offset set */ it('expired_token_no_autoremove_when_dont_have_servertime', function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(), function (err, token) { if (err) { @@ -1445,7 +1477,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @specpartial RSA4b1 - second case */ it('expired_token_autoremove_when_have_servertime', function (done) { - var realtime, + var helper = this.test.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(), function (err, token) { if (err) { @@ -1484,6 +1517,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('multiple_concurrent_authorize', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime({ useTokenAuth: true, defaultTokenParams: { capability: { wrong: ['*'] } }, @@ -1532,6 +1566,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @nospec */ Helper.testOnAllTransports('authorize_immediately_after_init', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime({ useTokenAuth: true, defaultTokenParams: { capability: { wrong: ['*'] } }, diff --git a/test/realtime/channel.test.js b/test/realtime/channel.test.js index 3d9d13ace..68c88723b 100644 --- a/test/realtime/channel.test.js +++ b/test/realtime/channel.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var exports = {}; var _exports = {}; var expect = chai.expect; @@ -154,6 +152,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -173,6 +172,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelinit0', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { @@ -209,6 +209,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattach0', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { @@ -235,6 +236,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattach2', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); var channel2 = realtime.channels.get('channelattach2'); @@ -263,6 +265,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async 'channelattach3', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { @@ -300,6 +303,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattachempty', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -334,6 +338,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattachinvalid', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -374,6 +379,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('publish_no_attach', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -403,6 +409,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattach_publish_invalid', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -436,6 +443,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattach_invalid_twice', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -475,6 +483,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('channelattachWhenState', function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(), channel = realtime.channels.get('channelattachWhenState'); @@ -496,6 +505,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTL25b */ it('channelattachOnceOrIfBefore', function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(), channel = realtime.channels.get('channelattachOnceOrIf'), @@ -528,6 +538,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('attachWithChannelParamsBasicChannelsGet', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; var testName = 'attachWithChannelParamsBasicChannelsGet'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -589,6 +600,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('attachWithChannelParamsBasicSetOptions', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; var testName = 'attachWithChannelParamsBasicSetOptions'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -642,6 +654,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('subscribeAfterSetOptions', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; var testName = 'subscribeAfterSetOptions'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -672,6 +685,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTS3c1 */ it('channelGetShouldThrowWhenWouldCauseReattach', function (done) { + const helper = this.test.helper; var testName = 'channelGetShouldThrowWhenWouldCauseReattach'; try { var realtime = helper.AblyRealtime(); @@ -716,6 +730,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTL16a */ Helper.testOnAllTransports('setOptionsCallbackBehaviour', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; var testName = 'setOptionsCallbackBehaviour'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -794,6 +809,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('attachWithChannelParamsModesAndChannelModes', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; var testName = 'attachWithChannelParamsModesAndChannelModes'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -855,6 +871,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('attachWithChannelModes', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; var testName = 'attachWithChannelModes'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -913,6 +930,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('attachWithChannelParamsDeltaAndModes', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; var testName = 'attachWithChannelParamsDeltaAndModes'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -968,6 +986,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTL4k1 */ it('attachWithInvalidChannelParams', function (done) { + const helper = this.test.helper; var testName = 'attachWithInvalidChannelParams'; var defaultChannelModes = 'presence,publish,subscribe,presence_subscribe'; try { @@ -1081,6 +1100,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it('channelsubscribe0', function (done) { try { + const helper = this.test.helper; var realtime = helper.AblyRealtime({ useBinaryProtocol: true }); realtime.connection.on('connected', function () { var channel6 = realtime.channels.get('channelsubscribe0'); @@ -1120,6 +1140,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTL8b */ it('channelsubscribe1', function (done) { + const helper = this.test.helper; var messagesReceived = 0; try { @@ -1200,7 +1221,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTL13 */ it('server_sent_detached', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channelName = 'server_sent_detached', channel = realtime.channels.get(channelName); @@ -1253,7 +1275,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTL13b - tests transition to the SUSPENDED state with emitted error */ it('server_sent_detached_while_attaching', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channelName = 'server_sent_detached_while_attaching', channel = realtime.channels.get(channelName); @@ -1295,7 +1318,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTL14 - tests transition to the FAILED state */ it('server_sent_error', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channelName = 'server_sent_error', channel = realtime.channels.get(channelName); @@ -1334,7 +1358,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTL12 */ it('server_sent_attached_err', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.test.helper, + realtime = helper.AblyRealtime(), channelName = 'server_sent_attached_err', channel = realtime.channels.get(channelName); @@ -1380,7 +1405,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec TO3g */ it('publish_no_queueing', function (done) { - var realtime = helper.AblyRealtime({ queueMessages: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ queueMessages: false }), channel = realtime.channels.get('publish_no_queueing'); /* try a publish while not yet connected */ @@ -1402,7 +1428,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it('channel_attach_timeout', function (done) { /* Use a fixed transport as attaches are resent when the transport changes */ - var realtime = helper.AblyRealtime({ + var helper = this.test.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport], realtimeRequestTimeout: 2000, channelRetryTimeout: 100, @@ -1453,7 +1480,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async it('suspended_connection', function (done) { /* Use a fixed transport as attaches are resent when the transport changes */ /* Browsers throttle setTimeouts to min 1s in in active tabs; having timeouts less than that screws with the relative timings */ - var realtime = helper.AblyRealtime({ + var helper = this.test.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport], channelRetryTimeout: 1010, suspendedRetryTimeout: 1100, @@ -1521,7 +1549,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTL5i */ it('attached_while_detaching', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channelName = 'server_sent_detached', channel = realtime.channels.get(channelName); @@ -1563,6 +1592,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTL5j */ it('detaching from suspended channel transitions channel to detached state', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); var channelName = 'detach_from_suspended'; var channel = realtime.channels.get(channelName); @@ -1584,6 +1614,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTL5b */ it('detaching from failed channel results in error', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); var channelName = 'detach_from_failed'; var channel = realtime.channels.get(channelName); @@ -1601,6 +1632,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @nospec */ it('rewind works on channel after reattaching', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); var channelName = 'rewind_after_detach'; var channel = realtime.channels.get(channelName); @@ -1629,6 +1661,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTL4d1 */ it('attach_returns_state_change', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime(); var channelName = 'attach_returns_state_chnage'; var channel = realtime.channels.get(channelName); @@ -1666,6 +1699,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTL7c */ it('subscribe_returns_state_change', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime(); var channelName = 'subscribe_returns_state_chnage'; var channel = realtime.channels.get(channelName); @@ -1693,6 +1727,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @specpartial RTL2i - hasBacklog is false with no backlog */ it('rewind_has_backlog_0', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime(); var channelName = 'rewind_has_backlog_0'; var channelOpts = { params: { rewind: '1' } }; @@ -1717,6 +1752,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @specpartial RTL2i - hasBacklog is true with backlog */ it('rewind_has_backlog_1', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime(); var rest = helper.AblyRest(); var channelName = 'rewind_has_backlog_1'; @@ -1749,6 +1785,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTS3c1 - test .get() with same options should not trigger reattachment and exception */ it('should not throw exception then run RealtimeChannels.get() with same options', function (done) { + const helper = this.test.helper; const realtime = helper.AblyRealtime(); const channel = realtime.channels.get('channel-with-options', { modes: ['PRESENCE'] }); channel.attach(); @@ -1766,7 +1803,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTL25a * @spec RTL25b */ - it('whenState', async () => { + it('whenState', async function () { + const helper = this.test.helper; const realtime = helper.AblyRealtime(); await helper.monitorConnectionAsync(async () => { diff --git a/test/realtime/connection.test.js b/test/realtime/connection.test.js index 23563b14f..eae128a33 100644 --- a/test/realtime/connection.test.js +++ b/test/realtime/connection.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; var createPM = Ably.protocolMessageFromDeserialized; @@ -10,6 +8,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -20,6 +19,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTN13 */ it('connectionPing', function (done) { + const helper = this.test.helper; var realtime; try { realtime = helper.AblyRealtime(); @@ -39,6 +39,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @specpartial RTN13a - callback is called with response time */ it('connectionPingWithCallback', function (done) { + const helper = this.test.helper; var realtime; try { realtime = helper.AblyRealtime(); @@ -68,6 +69,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTN16g - connectionKey, the current msgSerial */ it('connectionAttributes', function (done) { + const helper = this.test.helper; var realtime; try { realtime = helper.AblyRealtime(); @@ -129,6 +131,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTN15c7 */ it('unrecoverableConnection', function (done) { + const helper = this.test.helper; var realtime; const fakeRecoveryKey = JSON.stringify({ connectionKey: '_____!ablyjs_test_fake-key____', @@ -176,7 +179,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTN19a2 */ it('connectionQueuing', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channel = realtime.channels.get('connectionQueuing'), connectionManager = realtime.connection.connectionManager; @@ -295,7 +299,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial TO3l8 - default can be overridden by the maxMessageSize in the connectionDetails */ it('connectionDetails', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.test.helper, + realtime = helper.AblyRealtime(), connectionManager = realtime.connection.connectionManager; realtime.connection.once('connected', function () { connectionManager.once('connectiondetails', function (details) { @@ -335,7 +340,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTN26a * @spec RTN26b */ - it('whenState', async () => { + it('whenState', async function () { + const helper = this.test.helper; const realtime = helper.AblyRealtime({ autoConnect: false }); await helper.monitorConnectionAsync(async () => { diff --git a/test/realtime/connectivity.test.js b/test/realtime/connectivity.test.js index 64f905240..abf44cd57 100644 --- a/test/realtime/connectivity.test.js +++ b/test/realtime/connectivity.test.js @@ -1,14 +1,13 @@ 'use strict'; define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { - const helper = new Helper(); - var expect = chai.expect; describe('realtime/connectivity', function () { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -23,6 +22,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('http_connectivity_check', function (done) { + const helper = this.test.helper; Helper.whenPromiseSettles(new Ably.Realtime._Http().checkConnectivity(), function (err, res) { try { expect(res && !err, 'Connectivity check completed ' + (err && helper.Utils.inspectError(err))).to.be.ok; @@ -50,6 +50,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /** @nospec */ it('succeeds with scheme', function (done) { + const helper = this.test.helper; Helper.whenPromiseSettles( helper.AblyRealtime(options(urlScheme + successUrl)).http.checkConnectivity(), function (err, res) { @@ -66,6 +67,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /** @nospec */ it('fails with scheme', function (done) { + const helper = this.test.helper; Helper.whenPromiseSettles( helper.AblyRealtime(options(urlScheme + failUrl)).http.checkConnectivity(), function (err, res) { @@ -81,6 +83,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /** @nospec */ it('succeeds with querystring', function (done) { + const helper = this.test.helper; Helper.whenPromiseSettles( helper.AblyRealtime(options(successUrl)).http.checkConnectivity(), function (err, res) { @@ -96,6 +99,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /** @nospec */ it('fails with querystring', function (done) { + const helper = this.test.helper; Helper.whenPromiseSettles(helper.AblyRealtime(options(failUrl)).http.checkConnectivity(), function (err, res) { try { expect(!res, 'Connectivity check expected to return false').to.be.ok; @@ -108,6 +112,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /** @nospec */ it('succeeds with plain url', function (done) { + const helper = this.test.helper; Helper.whenPromiseSettles( helper.AblyRealtime(options('sandbox-rest.ably.io/time')).http.checkConnectivity(), function (err, res) { @@ -123,6 +128,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /** @nospec */ it('fails with plain url', function (done) { + const helper = this.test.helper; Helper.whenPromiseSettles( helper.AblyRealtime(options('echo.ably.io')).http.checkConnectivity(), function (err, res) { @@ -139,6 +145,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /** @nospec */ it('disable_connectivity_check', function (done) { + const helper = this.test.helper; Helper.whenPromiseSettles( helper.AblyRealtime(options('notarealhost', true)).http.checkConnectivity(), function (err, res) { diff --git a/test/realtime/crypto.test.js b/test/realtime/crypto.test.js index a8c9f60c4..c0a988abf 100644 --- a/test/realtime/crypto.test.js +++ b/test/realtime/crypto.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; var BufferUtils = Ably.Realtime.Platform.BufferUtils; var Crypto = Ably.Realtime.Platform.Crypto; @@ -19,7 +17,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async ); } - function testMessageEquality(done, one, two) { + function testMessageEquality(done, helper, one, two) { try { helper.testMessageEquality(one, two); } catch (err) { @@ -27,7 +25,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async } } - function testEachFixture(done, filename, channelName, testsPerFixture, testPlaintextVariants, fixtureTest) { + function testEachFixture(done, helper, filename, channelName, testsPerFixture, testPlaintextVariants, fixtureTest) { if (!Crypto) { done(new Error('Encryption not supported')); return; @@ -85,6 +83,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -245,8 +244,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL5b - aes 128 */ it('encrypt_message_128', function (done) { + const helper = this.test.helper; testEachFixture( done, + helper, 'crypto-data-128.json', 'encrypt_message_128', 2, @@ -255,7 +256,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* encrypt plaintext message; encode() also to handle data that is not already string or buffer */ Helper.whenPromiseSettles(Message.encode(testMessage, channelOpts), function () { /* compare */ - testMessageEquality(done, testMessage, encryptedMessage); + testMessageEquality(done, helper, testMessage, encryptedMessage); }); }, ); @@ -266,8 +267,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL5b - aes 256 */ it('encrypt_message_256', function (done) { + const helper = this.test.helper; testEachFixture( done, + helper, 'crypto-data-256.json', 'encrypt_message_256', 2, @@ -276,7 +279,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* encrypt plaintext message; encode() also to handle data that is not already string or buffer */ Helper.whenPromiseSettles(Message.encode(testMessage, channelOpts), function () { /* compare */ - testMessageEquality(done, testMessage, encryptedMessage); + testMessageEquality(done, helper, testMessage, encryptedMessage); }); }, ); @@ -287,8 +290,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL5b - aes 128 */ it('decrypt_message_128', function (done) { + const helper = this.test.helper; testEachFixture( done, + helper, 'crypto-data-128.json', 'decrypt_message_128', 2, @@ -297,7 +302,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* decrypt encrypted message; decode() also to handle data that is not string or buffer */ await Message.decode(encryptedMessage, channelOpts); /* compare */ - testMessageEquality(done, testMessage, encryptedMessage); + testMessageEquality(done, helper, testMessage, encryptedMessage); }, ); }); @@ -307,8 +312,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL5b - aes 256 */ it('decrypt_message_256', function (done) { + const helper = this.test.helper; testEachFixture( done, + helper, 'crypto-data-256.json', 'decrypt_message_256', 2, @@ -317,7 +324,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* decrypt encrypted message; decode() also to handle data that is not string or buffer */ await Message.decode(encryptedMessage, channelOpts); /* compare */ - testMessageEquality(done, testMessage, encryptedMessage); + testMessageEquality(done, helper, testMessage, encryptedMessage); }, ); }); @@ -329,6 +336,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } + const helper = this.test.helper; + helper.loadTestData(helper.testResourcesPath + 'crypto-data-256.json', async function (err, testData) { if (err) { done(err); @@ -341,7 +350,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async var item = testData.items[i]; var testMessage = await Message.fromEncoded(item.encoded); var decryptedMessage = await Message.fromEncoded(item.encrypted, { cipher: { key: key, iv: iv } }); - testMessageEquality(done, testMessage, decryptedMessage); + testMessageEquality(done, helper, testMessage, decryptedMessage); } done(); }); @@ -354,8 +363,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('msgpack_128', function (done) { + const helper = this.test.helper; testEachFixture( done, + helper, 'crypto-data-128.json', 'msgpack_128', 2, @@ -392,8 +403,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('msgpack_256', function (done) { + const helper = this.test.helper; testEachFixture( done, + helper, 'crypto-data-256.json', 'msgpack_256', 2, @@ -426,7 +439,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); } - function single_send(done, realtimeOpts, keyLength) { + function single_send(done, helper, realtimeOpts, keyLength) { if (!Crypto) { done(new Error('Encryption not supported')); return; @@ -473,18 +486,18 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @specpartial RSL5b - test aes 128 */ Helper.testOnAllTransports('single_send_128', function (realtimeOpts) { return function (done) { - single_send(done, realtimeOpts, 128); + single_send(done, this.test.helper, realtimeOpts, 128); }; }); /** @specpartial RSL5b - test aes 256 */ Helper.testOnAllTransports('single_send_256', function (realtimeOpts) { return function (done) { - single_send(done, realtimeOpts, 256); + single_send(done, this.test.helper, realtimeOpts, 256); }; }); - function _multiple_send(done, text, iterations, delay) { + function _multiple_send(done, helper, text, iterations, delay) { if (!Crypto) { done(new Error('Encryption not supported')); return; @@ -546,7 +559,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL5a - cipher is set via setOptions instead on channel instantiation */ it('multiple_send_binary_2_200', function (done) { - _multiple_send(done, false, 2, 200); + _multiple_send(done, this.test.helper, false, 2, 200); }); /** @@ -555,7 +568,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL5a - cipher is set via setOptions instead on channel instantiation */ it('multiple_send_text_2_200', function (done) { - _multiple_send(done, true, 2, 200); + _multiple_send(done, this.test.helper, true, 2, 200); }); /** @@ -564,7 +577,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL5a - cipher is set via setOptions instead on channel instantiation */ it('multiple_send_binary_20_100', function (done) { - _multiple_send(done, false, 20, 100); + _multiple_send(done, this.test.helper, false, 20, 100); }); /** @@ -573,7 +586,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL5a - cipher is set via setOptions instead on channel instantiation */ it('multiple_send_text_20_100', function (done) { - _multiple_send(done, true, 20, 100); + _multiple_send(done, this.test.helper, true, 20, 100); }); /** @@ -582,7 +595,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL5a - cipher is set via setOptions instead on channel instantiation */ it('multiple_send_binary_10_10', function (done) { - _multiple_send(done, false, 10, 10); + _multiple_send(done, this.test.helper, false, 10, 10); }); /** @@ -591,10 +604,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL5a - cipher is set via setOptions instead on channel instantiation */ it('multiple_send_text_10_10', function (done) { - _multiple_send(done, true, 10, 10); + _multiple_send(done, this.test.helper, true, 10, 10); }); - function _single_send_separate_realtimes(done, txOpts, rxOpts) { + function _single_send_separate_realtimes(done, helper, txOpts, rxOpts) { if (!Crypto) { done(new Error('Encryption not supported')); return; @@ -661,7 +674,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('single_send_binary_text', function (done) { - _single_send_separate_realtimes(done, { useBinaryProtocol: true }, { useBinaryProtocol: false }); + _single_send_separate_realtimes( + done, + this.test.helper, + { useBinaryProtocol: true }, + { useBinaryProtocol: false }, + ); }); /** @@ -673,7 +691,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('single_send_text_binary', function (done) { - _single_send_separate_realtimes(done, { useBinaryProtocol: false }, { useBinaryProtocol: true }); + _single_send_separate_realtimes( + done, + this.test.helper, + { useBinaryProtocol: false }, + { useBinaryProtocol: true }, + ); }); /** @@ -687,7 +710,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } - var txRealtime = helper.AblyRealtime(), + var helper = this.test.helper, + txRealtime = helper.AblyRealtime(), rxRealtime = helper.AblyRealtime(), channelName = 'publish_immediately', messageText = 'Test message'; @@ -731,6 +755,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } + const helper = this.test.helper; var txRealtime = helper.AblyRealtime(); var rxRealtime = helper.AblyRealtime(); var channelName = 'single_send_key_mismatch', @@ -800,6 +825,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } + const helper = this.test.helper; var txRealtime = helper.AblyRealtime(); var rxRealtime = helper.AblyRealtime(); var channelName = 'single_send_unencrypted', @@ -846,6 +872,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } + const helper = this.test.helper; var txRealtime = helper.AblyRealtime(); var rxRealtime = helper.AblyRealtime(); var channelName = 'single_send_encrypted_unhandled', @@ -894,6 +921,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } + const helper = this.test.helper; var txRealtime = helper.AblyRealtime(); var rxRealtime = helper.AblyRealtime(); var channelName = 'set_cipher_params', diff --git a/test/realtime/delta.test.js b/test/realtime/delta.test.js index cd8d41c4c..e0045abd8 100644 --- a/test/realtime/delta.test.js +++ b/test/realtime/delta.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, vcdiffDecoder, async, chai) { - const helper = new Helper(); - var expect = chai.expect; var testData = [ { foo: 'bar', count: 1, status: 'active' }, @@ -30,6 +28,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, v this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -40,6 +39,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, v /** @spec PC3 */ it('deltaPlugin', function (done) { + const helper = this.test.helper; var testName = 'deltaPlugin'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); @@ -95,6 +95,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, v * @nospec */ it('unusedPlugin', function (done) { + const helper = this.test.helper; var testName = 'unusedPlugin'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); @@ -140,6 +141,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, v * @spec RTL18c */ it('lastMessageNotFoundRecovery', function (done) { + const helper = this.test.helper; var testName = 'lastMessageNotFoundRecovery'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); @@ -208,6 +210,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, v * @spec RTL18c */ it('deltaDecodeFailureRecovery', function (done) { + const helper = this.test.helper; var testName = 'deltaDecodeFailureRecovery'; try { var failingTestVcdiffDecoder = { @@ -265,6 +268,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, v * @nospec */ it('noPlugin', function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(); var channel = realtime.channels.get('noPlugin', { params: { delta: 'vcdiff' } }); diff --git a/test/realtime/encoding.test.js b/test/realtime/encoding.test.js index 30b8841b9..5511ae5e9 100644 --- a/test/realtime/encoding.test.js +++ b/test/realtime/encoding.test.js @@ -1,13 +1,11 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; var BufferUtils = Ably.Realtime.Platform.BufferUtils; var Defaults = Ably.Rest.Platform.Defaults; - function encodingFixturesPath() { + function encodingFixturesPath(helper) { return helper.testResourcesPath + 'messages-encoding.json'; } @@ -15,6 +13,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -31,7 +30,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL6a1 - publish through REST API, receive via realtime for all transports */ it('message_decoding', function (done) { - helper.loadTestData(encodingFixturesPath(), function (err, testData) { + const helper = this.test.helper; + helper.loadTestData(encodingFixturesPath(helper), function (err, testData) { if (err) { done(err); return; @@ -135,7 +135,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL6a1 - publish through realtime, receive via rest (history) for all transports */ it('message_encoding', function (done) { - helper.loadTestData(encodingFixturesPath(), function (err, testData) { + const helper = this.test.helper; + helper.loadTestData(encodingFixturesPath(helper), function (err, testData) { if (err) { done(new Error('Unable to get test assets; err = ' + helper.displayError(err))); return; diff --git a/test/realtime/event_emitter.test.js b/test/realtime/event_emitter.test.js index a0ec885c8..4e56b55af 100644 --- a/test/realtime/event_emitter.test.js +++ b/test/realtime/event_emitter.test.js @@ -1,13 +1,12 @@ 'use strict'; define(['shared_helper', 'chai'], function (Helper, chai) { - const helper = new Helper(); - var expect = chai.expect; describe('realtime/event_emitter', function () { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -30,6 +29,7 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @specpartial RTL2 - RealtimeChannel implements EventEmitter */ it('attachdetach0', function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(), index, @@ -78,7 +78,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @specpartial RTE6 - test exceptions in callbacks do not propagate */ it('emitCallsAllCallbacksIgnoringExceptions', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = false, eventEmitter = realtime.connection; @@ -104,7 +105,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @specpartial RTE4 - ensure that each registration is only invoked once */ it('onceCalledOnlyOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), onCallbackCalled = 0, onceCallbackCalled = 0, eventEmitter = realtime.connection; @@ -137,7 +139,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @specpartial RTE4 - same listener is added multiple times listener registry */ it('onceCallbackDoesNotImpactOnCallback', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -164,7 +167,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @specpartial RTE5 - test remove matching listeners */ it('offRemovesAllMatchingListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -194,7 +198,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @specpartial RTE5 - test remove all listeners */ it('offRemovesAllListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -224,7 +229,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @specpartial RTE5 - test remove matching both event and listener */ it('offRemovesAllMatchingEventListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -258,7 +264,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @nospec */ it('offRemovesAllMatchingEvents', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -297,7 +304,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @nospec */ it('offRemovesEmptyEventNameListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection; var callback = function () {}; @@ -330,7 +338,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @nospec */ it('arrayOfEvents', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -374,7 +383,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @nospec */ it('arrayOfEventsWithOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -405,7 +415,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @nospec */ it('listenerAddedInListenerCb', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection, firstCbCalled = false, secondCbCalled = false; @@ -436,7 +447,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @nospec */ it('listenerRemovedInListenerCb', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection, onCbCalledTimes = 0, onceCbCalledTimes = 0, @@ -481,6 +493,7 @@ define(['shared_helper', 'chai'], function (Helper, chai) { describe('event_emitter_promise', function () { /** @specpartial RTN26b - tests only that listener was called, not the params */ it('whenState', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime(); var eventEmitter = realtime.connection; @@ -499,6 +512,7 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @nospec */ it('once', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime(); var eventEmitter = realtime.connection; @@ -514,7 +528,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /** @specpartial RTE4 - promise is resolved for the first event that is emitted when no event argument is provided */ it('anyEventsWithOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection; const p = eventEmitter.once(); @@ -531,7 +546,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * @nospec */ it('arrayOfEventsWithOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection; const p = eventEmitter.once(['a', 'b', 'c']); diff --git a/test/realtime/failure.test.js b/test/realtime/failure.test.js index dcc3c6d6b..57ed68435 100644 --- a/test/realtime/failure.test.js +++ b/test/realtime/failure.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; var noop = function () {}; var createPM = Ably.protocolMessageFromDeserialized; @@ -10,6 +8,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async describe('realtime/failure', function () { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -25,6 +24,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTN14a */ it('invalid_cred_failure', function (done) { + const helper = this.test.helper; try { var failure_test = function (transports) { return function (cb) { @@ -76,6 +76,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTN14d - test only transition to DISCONNECTED */ it('break_transport', function (done) { + const helper = this.test.helper; try { var break_test = function (transports) { return function (cb) { @@ -119,6 +120,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTN14d - doesn't test fallback hosts used */ it('no_connection_lifecycle', function (done) { + const helper = this.test.helper; try { var lifecycleTest = function (transports) { return function (cb) { @@ -197,7 +199,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async expect(value).to.be.below(max); } - helper.availableTransports.forEach(function (transport) { + Helper.forTestDefinition(this, 'disconnected_backoff_').availableTransports.forEach(function (transport) { /** * @spec RTB1a * @spec RTB1b @@ -207,6 +209,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial TA2 - retryIn passed in ConnectionStateChange */ it('disconnected_backoff_' + transport, function (done) { + const helper = this.test.helper; var disconnectedRetryTimeout = 150; var realtime = helper.AblyRealtime({ disconnectedRetryTimeout: disconnectedRetryTimeout, @@ -253,6 +256,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP15d - error on leave presence */ it('failed_channel', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime(); var failChan; var channelFailedCode = 90001; @@ -363,7 +367,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTL13b - tests re-attach attempt once */ it('attach_timeout', function (done) { - var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000, channelRetryTimeout: 1000 }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000, channelRetryTimeout: 1000 }), channel = realtime.channels.get('failed_attach'), originalProcessMessage = channel.processMessage.bind(channel); @@ -396,7 +401,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); }); - helper.availableTransports.forEach(function (transport) { + Helper.forTestDefinition(this, 'channel_backoff_').availableTransports.forEach(function (transport) { /** * @spec RTL13b * @spec RTB1a @@ -405,6 +410,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTB1 - test backoff for channel */ it('channel_backoff_' + transport, function (done) { + const helper = this.test.helper; var channelRetryTimeout = 150; var realtime = helper.AblyRealtime({ channelRetryTimeout: channelRetryTimeout, @@ -473,7 +479,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async function nack_on_connection_failure(failureFn, expectedRealtimeState, expectedNackCode) { return function (done) { /* Use one transport because stubbing out transport#onProtocolMesage */ - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channel = realtime.channels.get('nack_on_connection_failure'); async.series( @@ -510,7 +517,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async } }); Ably.Realtime.Platform.Config.nextTick(function () { - failureFn(realtime); + failureFn(realtime, helper); }); }, ], @@ -525,7 +532,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async it( 'nack_on_connection_suspended', nack_on_connection_failure( - function (realtime) { + function (realtime, helper) { helper.becomeSuspended(realtime); }, 'suspended', @@ -562,7 +569,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTN23a */ it('idle_transport_timeout', function (done) { - var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000 }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000 }), originalOnProtocolMessage; realtime.connection.connectionManager.on('transport.pending', function (transport) { @@ -599,7 +607,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return function (done) { /* Use the echoserver as a fallback host because it doesn't support * websockets, so it'll fail to connect, which we can detect */ - var realtime = helper.AblyRealtime(helper.Utils.mixin({ fallbackHosts: ['echo.ably.io'] }, realtimeOpts)), + var helper = this.test.helper, + realtime = helper.AblyRealtime(helper.Utils.mixin({ fallbackHosts: ['echo.ably.io'] }, realtimeOpts)), connection = realtime.connection, connectionManager = connection.connectionManager; @@ -634,6 +643,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RTL17 */ it('no_messages_if_not_attached', function (done) { + const helper = this.test.helper; var testName = 'no_messages_if_not_attached'; var testMessage = { foo: 'bar', count: 1, status: 'active' }; var testMessage2 = { foo: 'bar', count: 2, status: 'active' }; diff --git a/test/realtime/history.test.js b/test/realtime/history.test.js index bb47ba48c..5a468ba0e 100644 --- a/test/realtime/history.test.js +++ b/test/realtime/history.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; var indexes = [1, 2, 3, 4, 5]; var preAttachMessages = indexes.map(function (i) { @@ -36,6 +34,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -51,6 +50,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * @specpartial RTL10b - tests only messages prior to the moment that the channel was attached */ it('history_until_attach', function (done) { + const helper = this.test.helper; var rest = helper.AblyRest(); var realtime = helper.AblyRealtime(); var restChannel = rest.channels.get('persisted:history_until_attach'); diff --git a/test/realtime/init.test.js b/test/realtime/init.test.js index dcdd30b10..cdf83ed74 100644 --- a/test/realtime/init.test.js +++ b/test/realtime/init.test.js @@ -1,13 +1,12 @@ 'use strict'; define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { - const helper = new Helper(); - var expect = chai.expect; describe('realtime/init', function () { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -19,33 +18,36 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* Restrict to websocket or xhr polling for the v= test as if stream=false the * recvRequest may not be the connectRequest by the time we check it. */ - if (helper.bestTransport === 'web_socket' || helper.bestTransport === 'xhr_polling') { - /** - * Base init case. - * @spec RTN2f - */ - it('initbase0', function (done) { - var realtime; - try { - realtime = helper.AblyRealtime({ transports: ['web_socket', 'xhr_polling'] }); - realtime.connection.on('connected', function () { - /* check api version */ - var transport = realtime.connection.connectionManager.activeProtocol.transport; - var connectUri = helper.isWebsocket(transport) ? transport.uri : transport.recvRequest.recvUri; - try { - expect(connectUri.indexOf('v=3') > -1, 'Check uri includes v=3').to.be.ok; - } catch (err) { - helper.closeAndFinish(done, realtime, err); - return; - } - helper.closeAndFinish(done, realtime); - }); - helper.monitorConnection(done, realtime); - } catch (err) { - helper.closeAndFinish(done, realtime, err); - } - }); - } + ((testDefinitionHelper) => { + if (testDefinitionHelper.bestTransport === 'web_socket' || testDefinitionHelper.bestTransport === 'xhr_polling') { + /* + * Base init case. + * @spec RTN2f + */ + it('initbase0', function (done) { + const helper = this.test.helper; + var realtime; + try { + realtime = helper.AblyRealtime({ transports: ['web_socket', 'xhr_polling'] }); + realtime.connection.on('connected', function () { + /* check api version */ + var transport = realtime.connection.connectionManager.activeProtocol.transport; + var connectUri = helper.isWebsocket(transport) ? transport.uri : transport.recvRequest.recvUri; + try { + expect(connectUri.indexOf('v=3') > -1, 'Check uri includes v=3').to.be.ok; + } catch (err) { + helper.closeAndFinish(done, realtime, err); + return; + } + helper.closeAndFinish(done, realtime); + }); + helper.monitorConnection(done, realtime); + } catch (err) { + helper.closeAndFinish(done, realtime, err); + } + }); + } + })(Helper.forTestDefinition(this, 'initbase0')); /** * Init with key string. @@ -54,6 +56,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @specpartial RSC1c - test Realtime constructor with an API key */ it('init_key_string', function (done) { + const helper = this.test.helper; var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; @@ -79,6 +82,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @specpartial RSC1c - test Realtime constructor with a token string */ it('init_token_string', function (done) { + const helper = this.test.helper; try { /* first generate a token ... */ var rest = helper.AblyRest(); @@ -111,6 +115,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @spec TO3j4 */ it('init_key_with_usetokenauth', function (done) { + const helper = this.test.helper; var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; @@ -138,6 +143,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @spec RSA7b4 */ it('init_usetokenauth_defaulttokenparams_wildcard', function (done) { + const helper = this.test.helper; var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; @@ -169,6 +175,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @spec RSA7b3 */ it('init_defaulttokenparams_nonwildcard', function (done) { + const helper = this.test.helper; var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; @@ -198,6 +205,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @spec RSA7a4 */ it('init_conflicting_clientids', function (done) { + const helper = this.test.helper; var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; @@ -229,6 +237,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('init_with_usetokenauth_false_and_a_clientid', function (done) { + const helper = this.test.helper; try { var keyStr = helper.getTestApp().keys[0].keyStr; expect(function () { @@ -245,6 +254,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @specpartial RSC11 - tests only default value */ it('init_defaulthost', function (done) { + const helper = this.test.helper; try { /* want to check the default host when no custom environment or custom * host set, so not using helpers.realtime this time, which will use a @@ -268,6 +278,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @specpartial TO3l6 - test property can be set */ it('init_timeouts', function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime({ key: 'not_a.real:key', @@ -315,6 +326,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @specpartial RSC15a - httpMaxRetryCount has been reached */ it('init_fallbacks', function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime({ key: 'not_a.real:key', @@ -366,6 +378,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @nospec */ it('node_transports', function (done) { + const helper = this.test.helper; var realtime; try { realtime = helper.AblyRealtime({ transports: helper.availableTransports }); @@ -389,6 +402,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @spec RSA7b3 */ it('init_and_connection_details', function (done) { + const helper = this.test.helper; try { var keyStr = helper.getTestApp().keys[0].keyStr; var realtime = helper.AblyRealtime({ key: keyStr, useTokenAuth: true }); @@ -431,6 +445,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /** @spec RTN17b2 */ it('init_fallbacks_once_connected', function (done) { + const helper = this.test.helper; var realtime = helper.AblyRealtime({ httpMaxRetryCount: 3, fallbackHosts: ['a', 'b', 'c'], @@ -453,6 +468,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /** @specpartial RTN17e */ it('init_fallbacks_once_connected_2', function (done) { + const helper = this.test.helper; var goodHost = helper.AblyRest().options.realtimeHost; var realtime = helper.AblyRealtime({ httpMaxRetryCount: 3, diff --git a/test/realtime/message.test.js b/test/realtime/message.test.js index c145c1f85..131a1aa92 100644 --- a/test/realtime/message.test.js +++ b/test/realtime/message.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; let config = Ably.Realtime.Platform.Config; var createPM = Ably.protocolMessageFromDeserialized; @@ -24,6 +22,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async describe('realtime/message', function () { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -37,6 +36,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTL7b */ it('publishonce', function (done) { + const helper = this.test.helper; try { /* set up realtime */ var realtime = helper.AblyRealtime(); @@ -80,6 +80,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('publishfast', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -146,7 +147,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('publishQueued', function (realtimeOpts) { return function (done) { - var txRealtime, rxRealtime; + var helper = this.test.helper, + txRealtime, + rxRealtime; try { txRealtime = helper.AblyRealtime(helper.Utils.mixin(realtimeOpts, { autoConnect: false })); rxRealtime = helper.AblyRealtime(); @@ -239,7 +242,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it('publishEcho', function (done) { // set up two realtimes - var rtNoEcho = helper.AblyRealtime({ echoMessages: false }), + var helper = this.test.helper, + rtNoEcho = helper.AblyRealtime({ echoMessages: false }), rtEcho = helper.AblyRealtime({ echoMessages: true }), rtNoEchoChannel = rtNoEcho.channels.get('publishecho'), rtEchoChannel = rtEcho.channels.get('publishecho'), @@ -315,6 +319,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL1a - doesn't test array of Message objects */ it('publishVariations', function (done) { + const helper = this.test.helper; var testData = 'Some data'; var testArguments = [ [{ name: 'objectWithName' }], @@ -432,6 +437,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RSL4a */ it('publishDisallowed', function (done) { + const helper = this.test.helper; var testArguments = [ [{ name: 'objectAndBoolData', data: false }], ['nameAndBoolData', false], @@ -489,6 +495,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL6b */ it('publishEncodings', function (done) { + const helper = this.test.helper; var testData = 'testData'; var testArguments = [ // valid @@ -588,6 +595,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTL7b */ it('restpublish', function (done) { + const helper = this.test.helper; var count = 10; var rest = helper.AblyRest(); var realtime = helper.AblyRealtime(); @@ -621,6 +629,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('publish', function (realtimeOpts) { return function (done) { + const helper = this.test.helper; var count = 10; var cbCount = 10; var checkFinish = function () { @@ -657,7 +666,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL1m1 - in the context of RealtimeChannel */ it('implicit_client_id_0', function (done) { - var clientId = 'implicit_client_id_0', + var helper = this.test.helper, + clientId = 'implicit_client_id_0', realtime = helper.AblyRealtime({ clientId: clientId }); realtime.connection.once('connected', function () { @@ -699,7 +709,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL1m2 - in the context of RealtimeChannel */ it('explicit_client_id_0', function (done) { - var clientId = 'explicit_client_id_0', + var helper = this.test.helper, + clientId = 'explicit_client_id_0', /* Use a fixed transport as intercepting transport.send */ realtime = helper.AblyRealtime({ clientId: clientId, transports: [helper.bestTransport] }); @@ -765,7 +776,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL1m4 - in the context of RealtimeChannel */ it('explicit_client_id_1', function (done) { - var clientId = 'explicit_client_id_1', + var helper = this.test.helper, + clientId = 'explicit_client_id_1', invalidClientId = 'invalid', rest = helper.AblyRest(); @@ -826,7 +838,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('subscribe_with_event_array', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.test.helper, + realtime = helper.AblyRealtime(), channel = realtime.channels.get('subscribe_with_event_array'); async.series( @@ -892,6 +905,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTL22a - doesn't test for name */ it('subscribe_with_filter_object', function (done) { + const helper = this.test.helper; const realtime = helper.AblyRealtime(); const channel = realtime.channels.get('subscribe_with_filter_object'); @@ -982,6 +996,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTL22a - doesn't test for name */ it('unsubscribe_with_filter_object', function (done) { + const helper = this.test.helper; const realtime = helper.AblyRealtime(); const channel = realtime.channels.get('unsubscribe_with_filter_object'); @@ -1041,7 +1056,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @spec RSL6a2 */ it('extras_field', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.test.helper, + realtime = helper.AblyRealtime(), channel = realtime.channels.get('extras_field'), extras = { headers: { some: 'metadata' } }; @@ -1090,7 +1106,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSL1i */ it('maxMessageSize', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.test.helper, + realtime = helper.AblyRealtime(), connectionManager = realtime.connection.connectionManager, channel = realtime.channels.get('maxMessageSize'); @@ -1134,7 +1151,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specskip */ it.skip('bundling', function (done) { - var realtime = helper.AblyRealtime({ maxMessageSize: 256, autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ maxMessageSize: 256, autoConnect: false }), channelOne = realtime.channels.get('bundlingOne'), channelTwo = realtime.channels.get('bundlingTwo'); @@ -1200,7 +1218,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSL1k5 */ it('idempotentRealtimePublishing', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.test.helper, + realtime = helper.AblyRealtime(), channel = realtime.channels.get('idempotentRealtimePublishing'); Helper.whenPromiseSettles(channel.attach(), function (err) { @@ -1241,6 +1260,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec DO2a */ it('subscribes to filtered channel', function (done) { + const helper = this.test.helper; + var testData = [ { name: 'filtered', diff --git a/test/realtime/presence.test.js b/test/realtime/presence.test.js index 88a3f9c48..f54fe7644 100644 --- a/test/realtime/presence.test.js +++ b/test/realtime/presence.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; var createPM = Ably.protocolMessageFromDeserialized; var PresenceMessage = Ably.Realtime.PresenceMessage; @@ -25,7 +23,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async var testClientId = 'testclient', testClientId2 = 'testclient2'; - var createListenerChannel = function (channelName, callback) { + var createListenerChannel = function (helper, channelName, callback) { var channel, realtime; try { realtime = helper.AblyRealtime(); @@ -55,9 +53,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }; }; - var runTestWithEventListener = function (done, channel, eventListener, testRunner) { + var runTestWithEventListener = function (done, helper, channel, eventListener, testRunner) { try { - createListenerChannel(channel, function (err, listenerRealtime, presenceChannel) { + createListenerChannel(helper, channel, function (err, listenerRealtime, presenceChannel) { if (err) { helper.closeAndFinish(done, listenerRealtime, err); return; @@ -93,6 +91,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async describe('realtime/presence', function () { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -145,6 +144,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specskip */ it.skip('presenceAttachAndEnter', function (done) { + const helper = this.test.helper; var channelName = 'attachAndEnter'; var attachAndEnter = function (cb) { /* set up authenticated connection */ @@ -165,7 +165,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, listenerFor('enter'), attachAndEnter); + runTestWithEventListener(done, helper, channelName, listenerFor('enter'), attachAndEnter); }); /** @@ -175,6 +175,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP8a - doesn't test entering with data */ it('presenceEnterWithoutAttach', function (done) { + const helper = this.test.helper; var channelName = 'enterWithoutAttach'; var enterWithoutAttach = function (cb) { var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -191,7 +192,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, listenerFor('enter'), enterWithoutAttach); + runTestWithEventListener(done, helper, channelName, listenerFor('enter'), enterWithoutAttach); }); /** @@ -200,6 +201,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('presenceEnterWithoutConnect', function (done) { + const helper = this.test.helper; var channelName = 'enterWithoutConnect'; var enterWithoutConnect = function (cb) { var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -213,7 +215,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, listenerFor('enter'), enterWithoutConnect); + runTestWithEventListener(done, helper, channelName, listenerFor('enter'), enterWithoutConnect); }); /** @@ -225,6 +227,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specskip */ it.skip('presenceEnterDetachRace', function (done) { + const helper = this.test.helper; // Can't use runTestWithEventListener helper as one of the successful // outcomes is an error in presence enter, in which case listenForEventOn // will not run its callback @@ -233,7 +236,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async try { /* listen for the enter event, test is complete when received */ - createListenerChannel(channelName, function (err, listenerRealtime, presenceChannel) { + createListenerChannel(helper, channelName, function (err, listenerRealtime, presenceChannel) { if (err) { helper.closeAndFinish(done, listenerRealtime, err); return; @@ -290,6 +293,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP8b - test successful callback */ it('presenceEnterWithCallback', function (done) { + const helper = this.test.helper; var channelName = 'enterWithCallback'; var enterWithCallback = function (cb) { /* set up authenticated connection */ @@ -310,7 +314,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, listenerFor('enter'), enterWithCallback); + runTestWithEventListener(done, helper, channelName, listenerFor('enter'), enterWithCallback); }); /** @@ -318,6 +322,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP8a - test entering presence without data and callback */ it('presenceEnterWithNothing', function (done) { + const helper = this.test.helper; var channelName = 'enterWithNothing'; var enterWithNothing = function (cb) { var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -336,7 +341,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, listenerFor('enter'), enterWithNothing); + runTestWithEventListener(done, helper, channelName, listenerFor('enter'), enterWithNothing); }); /** @@ -345,6 +350,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP8a - test entering presence with data */ it('presenceEnterWithData', function (done) { + const helper = this.test.helper; var channelName = 'enterWithData'; var enterWithData = function (cb) { var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -363,7 +369,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, listenerFor('enter'), enterWithData); + runTestWithEventListener(done, helper, channelName, listenerFor('enter'), enterWithData); }); /** @@ -373,6 +379,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP8c - test sending ENTER action */ it('presenceMessageAction', function (done) { + const helper = this.test.helper; var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var channelName = 'presenceMessageAction'; var clientChannel = clientRealtime.channels.get(channelName); @@ -406,6 +413,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP8e - doesn't test leaving without extras */ it('presenceMessageExtras', function (done) { + const helper = this.test.helper; var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var channelName = 'presenceEnterWithExtras'; var clientChannel = clientRealtime.channels.get(channelName); @@ -478,6 +486,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('presenceEnterDetachEnter', function (done) { + const helper = this.test.helper; var channelName = 'enterDetachEnter'; var secondEventListener = function (channel, callback) { var presenceHandler = function (presenceMsg) { @@ -515,7 +524,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, secondEventListener, enterDetachEnter); + runTestWithEventListener(done, helper, channelName, secondEventListener, enterDetachEnter); }); /** @@ -525,6 +534,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP8d - test throwing error if channel in DETACHED or FAILED state */ it('presenceEnterInvalid', function (done) { + const helper = this.test.helper; var clientRealtime; try { clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -556,6 +566,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP10 */ it('presenceEnterAndLeave', function (done) { + const helper = this.test.helper; var channelName = 'enterAndLeave'; var enterAndLeave = function (cb) { var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -581,7 +592,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, listenerFor('leave'), enterAndLeave); + runTestWithEventListener(done, helper, channelName, listenerFor('leave'), enterAndLeave); }); /** @@ -591,6 +602,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP9a - tests passing new data */ it('presenceEnterUpdate', function (done) { + const helper = this.test.helper; var newData = 'New data'; var channelName = 'enterUpdate'; var eventListener = function (channel, callback) { @@ -632,7 +644,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, eventListener, enterUpdate); + runTestWithEventListener(done, helper, channelName, eventListener, enterUpdate); }); /** @@ -640,6 +652,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP11a */ it('presenceEnterGet', function (done) { + const helper = this.test.helper; var channelName = 'enterGet'; var testData = 'some data for presenceEnterGet'; var eventListener = function (channel, callback) { @@ -681,7 +694,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, eventListener, enterGet); + runTestWithEventListener(done, helper, channelName, eventListener, enterGet); }); /** @@ -689,6 +702,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP6c */ it('presenceSubscribeUnattached', function (done) { + const helper = this.test.helper; var channelName = 'subscribeUnattached'; var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var clientRealtime2; @@ -720,6 +734,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP11c1 - tests default behavior waitForSync=true */ it('presenceGetUnattached', function (done) { + const helper = this.test.helper; var channelName = 'getUnattached'; var testData = 'some data'; var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -764,6 +779,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP10c */ it('presenceEnterLeaveGet', function (done) { + const helper = this.test.helper; var channelName = 'enterLeaveGet'; var eventListener = function (channel, callback) { var presenceHandler = function () { @@ -811,7 +827,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, eventListener, enterLeaveGet); + runTestWithEventListener(done, helper, channelName, eventListener, enterLeaveGet); }); /** @@ -820,6 +836,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP12c */ it('presenceHistory', function (done) { + const helper = this.test.helper; var clientRealtime; var channelName = 'history'; var testClientData = 'Test client data (history0)'; @@ -895,6 +912,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('presenceSecondConnection', function (done) { + const helper = this.test.helper; var clientRealtime1, clientRealtime2; var channelName = 'secondConnection'; try { @@ -978,6 +996,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP11c3 */ it('presenceTwoMembers', function (done) { + const helper = this.test.helper; var clientRealtime1, clientRealtime2, clientChannel1, clientChannel2; var channelName = 'twoMembers'; try { @@ -1147,6 +1166,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('presenceEnterAfterClose', function (done) { + const helper = this.test.helper; var channelName = 'enterAfterClose'; var secondEnterListener = function (channel, callback) { var presenceHandler = function (presenceMsg) { @@ -1182,7 +1202,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, clientRealtime); }; - runTestWithEventListener(done, channelName, secondEnterListener, enterAfterClose); + runTestWithEventListener(done, helper, channelName, secondEnterListener, enterAfterClose); }); /** @@ -1190,6 +1210,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP15e - tests only enterClient */ it('presenceEnterClosed', function (done) { + const helper = this.test.helper; var clientRealtime; var channelName = 'enterClosed'; try { @@ -1222,7 +1243,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP10c */ it('presenceClientIdIsImplicit', function (done) { - var clientId = 'implicitClient', + var helper = this.test.helper, + clientId = 'implicitClient', client = helper.AblyRealtime({ clientId: clientId }); var channel = client.channels.get('presenceClientIdIsImplicit'), @@ -1267,7 +1289,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP8e - test encoding of message and data */ it('presenceEncoding', function (done) { - var data = { foo: 'bar' }, + var helper = this.test.helper, + data = { foo: 'bar' }, encodedData = JSON.stringify(data), options = { clientId: testClientId, @@ -1333,6 +1356,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('presence_enter_inherited_clientid', function (done) { + const helper = this.test.helper; var channelName = 'enter_inherited_clientid'; var authCallback = function (tokenParams, callback) { @@ -1362,7 +1386,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async helper.monitorConnection(done, realtime); }; - runTestWithEventListener(done, channelName, listenerFor('enter', testClientId), enterInheritedClientId); + runTestWithEventListener(done, helper, channelName, listenerFor('enter', testClientId), enterInheritedClientId); }); /** @@ -1374,6 +1398,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('presence_enter_before_know_clientid', function (done) { + const helper = this.test.helper; var channelName = 'enter_before_know_clientid'; var enterInheritedClientId = function (cb) { @@ -1404,7 +1429,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); }; - runTestWithEventListener(done, channelName, listenerFor('enter', testClientId), enterInheritedClientId); + runTestWithEventListener(done, helper, channelName, listenerFor('enter', testClientId), enterInheritedClientId); }); /** @@ -1414,6 +1439,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP15b */ it('presence_refresh_on_detach', function (done) { + const helper = this.test.helper; var channelName = 'presence_refresh_on_detach'; var realtime = helper.AblyRealtime(); var observer = helper.AblyRealtime(); @@ -1529,6 +1555,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /** @nospec */ it('presence_detach_during_sync', function (done) { + const helper = this.test.helper; var channelName = 'presence_detach_during_sync'; var enterer = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var detacher = helper.AblyRealtime(); @@ -1591,6 +1618,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP17i - tests simple re-entry, no RESUMED flag test */ it('presence_auto_reenter', function (done) { + const helper = this.test.helper; var channelName = 'presence_auto_reenter'; var realtime = helper.AblyRealtime(); var channel = realtime.channels.get(channelName); @@ -1704,7 +1732,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specskip */ it.skip('presence_failed_auto_reenter', function (done) { - var channelName = 'presence_failed_auto_reenter', + var helper = this.test.helper, + channelName = 'presence_failed_auto_reenter', realtime, channel, token; @@ -1804,7 +1833,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('multiple_pending', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.test.helper, + realtime = helper.AblyRealtime(), channel = realtime.channels.get('multiple_pending'), originalAttachImpl = channel.attachImpl; @@ -1859,7 +1889,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP19 */ it('leave_published_for_member_missing_from_sync', function (done) { - var realtime = helper.AblyRealtime({ transports: helper.availableTransports }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ transports: helper.availableTransports }), continuousClientId = 'continuous', goneClientId = 'gone', continuousRealtime = helper.AblyRealtime({ clientId: continuousClientId }), @@ -1977,7 +2008,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP19a */ it('leave_published_for_members_on_presenceless_attached', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.test.helper, + realtime = helper.AblyRealtime(), channelName = 'leave_published_for_members_on_presenceless_attached', channel = realtime.channels.get(channelName), fakeClientId = 'faker'; @@ -2073,7 +2105,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP11d */ it('suspended_preserves_presence', function (done) { - var mainRealtime = helper.AblyRealtime({ clientId: 'main' }), + var helper = this.test.helper, + mainRealtime = helper.AblyRealtime({ clientId: 'main' }), continuousRealtime = helper.AblyRealtime({ clientId: 'continuous' }), leavesRealtime = helper.AblyRealtime({ clientId: 'leaves' }), channelName = 'suspended_preserves_presence', @@ -2213,6 +2246,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP9a */ it('presence_many_updates', function (done) { + const helper = this.test.helper; var client = helper.AblyRealtime({ clientId: testClientId }); var channel = client.channels.get('presence_many_updates'), diff --git a/test/realtime/reauth.test.js b/test/realtime/reauth.test.js index c7daf7ab2..b08393515 100644 --- a/test/realtime/reauth.test.js +++ b/test/realtime/reauth.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; var clientId = 'testClientId'; var rest; @@ -11,6 +9,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -23,7 +22,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { /* Waterfall helpers */ - function getToken(tokenParams) { + function getToken(helper, tokenParams) { return function (state, callback) { Helper.whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, token) { callback(err, helper.Utils.mixin(state, { token: token })); @@ -41,7 +40,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { }; } - function connectWithToken() { + function connectWithToken(helper) { return function (state, callback) { var realtime = helper.AblyRealtime(helper.Utils.mixin({ token: state.token }, state.realtimeOpts)); realtime.connection.once('connected', function () { @@ -51,7 +50,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { } /* For when connection should stay connected right through till it's closed */ - function monitorConnectionContinuity() { + function monitorConnectionContinuity(helper) { return function (state, callback) { var listener = function () { if (this.event !== 'update') { @@ -178,10 +177,11 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { }; } - function testCase(name, steps) { + function testCase(name, createSteps) { Helper.testOnAllTransports(name, function (realtimeOpts) { return function (done) { - var _steps = steps.slice(); + const helper = this.test.helper; + var _steps = createSteps(helper).slice(); _steps.unshift(function (cb) { cb(null, { realtimeOpts: realtimeOpts }); }); @@ -203,24 +203,24 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { ****************/ /** @specpartial RTC8a1 - change capability without loss of continuity */ - testCase('reauthCapabilityUpgradeNewChannel', [ - getToken({ clientId: clientId, capability: { wrongchannel: ['*'] } }), - connectWithToken(), - monitorConnectionContinuity(), + testCase('reauthCapabilityUpgradeNewChannel', (helper) => [ + getToken(helper, { clientId: clientId, capability: { wrongchannel: ['*'] } }), + connectWithToken(helper), + monitorConnectionContinuity(helper), checkCantAttach('rightchannel'), - getToken({ clientId: clientId, capability: { wrongchannel: ['*'], rightchannel: ['*'] } }), + getToken(helper, { clientId: clientId, capability: { wrongchannel: ['*'], rightchannel: ['*'] } }), reauthWithToken(), attach('rightchannel'), close(), ]); /** @specpartial RTC8a1 - capability downgrade leads to an error an failed channel state */ - testCase('reauthCapabilityDowngradeFullChannel', [ - getToken({ clientId: clientId, capability: { channel: ['*'], another: ['*'] } }), - connectWithToken(), - monitorConnectionContinuity(), + testCase('reauthCapabilityDowngradeFullChannel', (helper) => [ + getToken(helper, { clientId: clientId, capability: { channel: ['*'], another: ['*'] } }), + connectWithToken(helper), + monitorConnectionContinuity(helper), attach('channel'), - getToken({ clientId: clientId, capability: { another: ['*'] } }), + getToken(helper, { clientId: clientId, capability: { another: ['*'] } }), reauthWithToken(), waitChannelState('channel', 'failed'), checkChannelErrorCode('channel', 40160), @@ -232,13 +232,13 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * Related to RTC8a1. * @nospec */ - testCase('reauthCapabilityUpgradeAddPublish', [ - getToken({ clientId: clientId, capability: { channel: ['subscribe'] } }), - connectWithToken(), - monitorConnectionContinuity(), + testCase('reauthCapabilityUpgradeAddPublish', (helper) => [ + getToken(helper, { clientId: clientId, capability: { channel: ['subscribe'] } }), + connectWithToken(helper), + monitorConnectionContinuity(helper), attach('channel'), checkCantPublish('channel'), - getToken({ clientId: clientId, capability: { channel: ['subscribe', 'publish'] } }), + getToken(helper, { clientId: clientId, capability: { channel: ['subscribe', 'publish'] } }), reauthWithToken(), checkAttached('channel'), checkCanPublish('channel'), @@ -249,13 +249,13 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * Related to RTC8a1. * @nospec */ - testCase('reauthCapabilityDowngradePublish', [ - getToken({ clientId: clientId, capability: { channel: ['subscribe', 'publish'] } }), - connectWithToken(), - monitorConnectionContinuity(), + testCase('reauthCapabilityDowngradePublish', (helper) => [ + getToken(helper, { clientId: clientId, capability: { channel: ['subscribe', 'publish'] } }), + connectWithToken(helper), + monitorConnectionContinuity(helper), attach('channel'), checkCanPublish('channel'), - getToken({ clientId: clientId, capability: { channel: ['subscribe'] } }), + getToken(helper, { clientId: clientId, capability: { channel: ['subscribe'] } }), reauthWithToken(), attach('channel'), checkAttached('channel'), diff --git a/test/realtime/resume.test.js b/test/realtime/resume.test.js index 5ac302e1c..d41af8e56 100644 --- a/test/realtime/resume.test.js +++ b/test/realtime/resume.test.js @@ -1,14 +1,13 @@ 'use strict'; define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; describe('realtime/resume', function () { this.timeout(120 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -38,7 +37,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * Empty resume case * Send 5 messages; disconnect; reconnect; send 5 messages */ - function resume_inactive(done, channelName, txOpts, rxOpts) { + function resume_inactive(done, helper, channelName, txOpts, rxOpts) { var count = 5; var txRest = helper.AblyRest(mixin(txOpts)); @@ -141,7 +140,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { */ Helper.testOnAllTransports('resume_inactive', function (realtimeOpts) { return function (done) { - resume_inactive(done, 'resume_inactive' + String(Math.random()), {}, realtimeOpts); + resume_inactive(done, this.test.helper, 'resume_inactive' + String(Math.random()), {}, realtimeOpts); }; }); @@ -149,7 +148,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * Simple resume case * Send 5 messages; disconnect; send 5 messages; reconnect */ - function resume_active(done, channelName, txOpts, rxOpts) { + function resume_active(done, helper, channelName, txOpts, rxOpts) { var count = 5; var txRest = helper.AblyRest(mixin(txOpts)); @@ -265,7 +264,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { */ Helper.testOnAllTransports('resume_active', function (realtimeOpts) { return function (done) { - resume_active(done, 'resume_active' + String(Math.random()), {}, realtimeOpts); + resume_active(done, this.test.helper, 'resume_active' + String(Math.random()), {}, realtimeOpts); }; }); @@ -277,7 +276,8 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { 'resume_lost_continuity', function (realtimeOpts) { return function (done) { - var realtime = helper.AblyRealtime(realtimeOpts), + var helper = this.test.helper, + realtime = helper.AblyRealtime(realtimeOpts), connection = realtime.connection, attachedChannelName = 'resume_lost_continuity_attached', suspendedChannelName = 'resume_lost_continuity_suspended', @@ -344,7 +344,8 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { 'resume_token_error', function (realtimeOpts) { return function (done) { - var realtime = helper.AblyRealtime(mixin(realtimeOpts, { useTokenAuth: true })), + var helper = this.test.helper, + realtime = helper.AblyRealtime(mixin(realtimeOpts, { useTokenAuth: true })), badtoken, connection = realtime.connection; @@ -398,7 +399,8 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { 'resume_fatal_error', function (realtimeOpts) { return function (done) { - var realtime = helper.AblyRealtime(realtimeOpts), + var helper = this.test.helper, + realtime = helper.AblyRealtime(realtimeOpts), connection = realtime.connection; async.series( @@ -450,7 +452,8 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * @spec RTL2f */ it('channel_resumed_flag', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), realtimeTwo, recoveryKey, connection = realtime.connection, @@ -517,7 +520,8 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * @nospec */ it('no_resume_once_suspended', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.test.helper, + realtime = helper.AblyRealtime(), connection = realtime.connection, channelName = 'no_resume_once_suspended'; @@ -557,7 +561,8 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * @spec RTN15g */ it('no_resume_last_activity', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.test.helper, + realtime = helper.AblyRealtime(), connection = realtime.connection, connectionManager = connection.connectionManager; @@ -581,6 +586,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { /** @spec RTL4j2 */ it('resume_rewind_1', function (done) { + const helper = this.test.helper; var testName = 'resume_rewind_1'; var testMessage = { foo: 'bar', count: 1, status: 'active' }; try { @@ -644,6 +650,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * @spec RTN15a */ it('recover multiple channels', function (done) { + const helper = this.test.helper; const NUM_MSGS = 5; const txRest = helper.AblyRest(); diff --git a/test/realtime/sync.test.js b/test/realtime/sync.test.js index c53b1c68f..b4520f3b7 100644 --- a/test/realtime/sync.test.js +++ b/test/realtime/sync.test.js @@ -1,14 +1,13 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; var createPM = Ably.protocolMessageFromDeserialized; describe('realtime/sync', function () { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -46,7 +45,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP19 */ it('sync_existing_set', async function () { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'syncexistingset', channel = realtime.channels.get(channelName); @@ -170,7 +170,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('sync_member_arrives_in_middle', async function () { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_member_arrives_in_middle', channel = realtime.channels.get(channelName); @@ -275,7 +276,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('sync_member_arrives_normally_after_came_in_sync', async function () { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_member_arrives_normally_after_came_in_sync', channel = realtime.channels.get(channelName); @@ -361,7 +363,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @nospec */ it('sync_member_arrives_normally_before_comes_in_sync', async function () { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_member_arrives_normally_before_comes_in_sync', channel = realtime.channels.get(channelName); @@ -451,7 +454,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RTP2c */ it('presence_ordering', async function () { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.test.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_ordering', channel = realtime.channels.get(channelName); @@ -607,6 +611,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RTP4 - not enough members tested, should be 250 */ it('presence_sync_interruptus', function (done) { + const helper = this.test.helper; var channelName = 'presence_sync_interruptus'; var interrupterClientId = 'dark_horse'; var enterer = helper.AblyRealtime(); diff --git a/test/realtime/transports.test.js b/test/realtime/transports.test.js index 0ea8e7c51..e947d8919 100644 --- a/test/realtime/transports.test.js +++ b/test/realtime/transports.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai, Ably) { - const helper = new Helper(); - const expect = chai.expect; const Defaults = Ably.Rest.Platform.Defaults; const originialWsCheckUrl = Defaults.wsConnectivityUrl; @@ -14,7 +12,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai const defaultTransports = new Ably.Realtime({ key: 'xxx:yyy', autoConnect: false }).connection.connectionManager .transports; - function baseTransport() { + function baseTransport(helper) { return new Ably.Realtime({ key: 'xxx:yyy', autoConnect: false, @@ -42,6 +40,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -54,9 +53,12 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai afterEach(restoreWsConnectivityUrl); afterEach(restoreWebSocketConstructor); - if (helper.availableTransports.length > 1) { + if ( + Helper.forTestDefinition(this, 'tests that are run if there are multiple transports').availableTransports.length > + 1 + ) { // ensure comet transport is used for nodejs tests - function options(opts) { + function options(helper, opts) { return helper.Utils.mixin( { transports: helper.availableTransports, @@ -67,7 +69,8 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai /** @nospec */ it('websocket_is_default', function (done) { - const realtime = helper.AblyRealtime(options()); + const helper = this.test.helper; + const realtime = helper.AblyRealtime(options(helper)); realtime.connection.on('connected', function () { try { @@ -83,16 +86,21 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai /** @nospec */ it('no_ws_connectivity', function (done) { + const helper = this.test.helper; Config.WebSocket = FakeWebSocket; - const realtime = helper.AblyRealtime(options({ webSocketSlowTimeout: 1000, webSocketConnectTimeout: 3000 })); + const realtime = helper.AblyRealtime( + options(helper, { webSocketSlowTimeout: 1000, webSocketConnectTimeout: 3000 }), + ); realtime.connection.on('connected', function () { try { - expect(realtime.connection.connectionManager.activeProtocol.transport.shortName).to.equal(baseTransport()); + expect(realtime.connection.connectionManager.activeProtocol.transport.shortName).to.equal( + baseTransport(helper), + ); // check that transport preference is set if (localStorageSupported) { expect(window.localStorage.getItem(transportPreferenceName)).to.equal( - JSON.stringify({ value: baseTransport() }), + JSON.stringify({ value: baseTransport(helper) }), ); } } catch (err) { @@ -106,9 +114,10 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai /** @nospec */ it('ws_primary_host_fails', function (done) { + const helper = this.test.helper; const goodHost = helper.AblyRest().options.realtimeHost; const realtime = helper.AblyRealtime( - options({ realtimeHost: helper.unroutableAddress, fallbackHosts: [goodHost] }), + options(helper, { realtimeHost: helper.unroutableAddress, fallbackHosts: [goodHost] }), ); realtime.connection.on('connected', function () { @@ -121,8 +130,11 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai /** @specpartial RTN14d */ it('no_internet_connectivity', function (done) { + const helper = this.test.helper; Config.WebSocket = FakeWebSocket; - const realtime = helper.AblyRealtime(options({ connectivityCheckUrl: failUrl, webSocketSlowTimeout: 1000 })); + const realtime = helper.AblyRealtime( + options(helper, { connectivityCheckUrl: failUrl, webSocketSlowTimeout: 1000 }), + ); // expect client to transition to disconnected rather than attempting base transport (which would succeed in this instance) realtime.connection.on('disconnected', function () { @@ -132,6 +144,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai /** @specpartial RTN14d */ it('no_websocket_or_base_transport', function (done) { + const helper = this.test.helper; Config.WebSocket = FakeWebSocket; const realtime = helper.AblyRealtime({ transports: ['web_socket'], @@ -147,8 +160,9 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai if (localStorageSupported) { /** @nospec */ it('base_transport_preference', function (done) { - window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: baseTransport() })); - const realtime = helper.AblyRealtime(options()); + const helper = this.test.helper; + window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: baseTransport(helper) })); + const realtime = helper.AblyRealtime(options(helper)); // make ws connectivity check only resolve after connected with base transport. // prevents a race condition where the wsConnectivity check succeeds before base transport is activated; @@ -164,7 +178,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai realtime.connection.on('connected', function () { try { expect(realtime.connection.connectionManager.activeProtocol.transport.shortName).to.equal( - baseTransport(), + baseTransport(helper), ); } catch (err) { helper.closeAndFinish(done, realtime, err); @@ -176,8 +190,9 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai /** @nospec */ it('transport_preference_reset_while_connecting', function (done) { - window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: baseTransport() })); - const realtime = helper.AblyRealtime(options()); + const helper = this.test.helper; + window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: baseTransport(helper) })); + const realtime = helper.AblyRealtime(options(helper)); // make ws connectivity check fast so that it succeeds while base transport is still connecting realtime.connection.connectionManager.checkWsConnectivity = function () { @@ -201,8 +216,9 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai /** @nospec */ it('transport_preference_reset_after_connected', function (done) { - window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: baseTransport() })); - const realtime = helper.AblyRealtime(options()); + const helper = this.test.helper; + window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: baseTransport(helper) })); + const realtime = helper.AblyRealtime(options(helper)); // make ws connectivity check only resolve after connected with base transport realtime.connection.connectionManager.checkWsConnectivity = function () { @@ -210,7 +226,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai realtime.connection.once('connected', () => { try { expect(realtime.connection.connectionManager.activeProtocol.transport.shortName).to.equal( - baseTransport(), + baseTransport(helper), ); resolve(); } catch (err) { diff --git a/test/realtime/utils.test.js b/test/realtime/utils.test.js index 5e20ee3ff..63800371d 100644 --- a/test/realtime/utils.test.js +++ b/test/realtime/utils.test.js @@ -1,13 +1,12 @@ 'use strict'; define(['shared_helper', 'chai'], function (Helper, chai) { - const helper = new Helper(); - var expect = chai.expect; describe('incremental backoff and jitter', function () { /** @spec RTB1 */ it('should calculate retry timeouts using incremental backoff and jitter', function () { + const helper = this.test.helper; var retryAttempts = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; var initialTimeout = 15; diff --git a/test/rest/auth.test.js b/test/rest/auth.test.js index 4727ce818..1e123a5e2 100644 --- a/test/rest/auth.test.js +++ b/test/rest/auth.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, async, globals) { - const helper = new Helper(); - var currentTime; var rest; var expect = chai.expect; @@ -12,6 +10,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function () { rest = helper.AblyRest({ queryTime: true }); rest @@ -55,6 +54,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * @specpartial TO3j2 - test passing token in ClientOptions for Rest client */ it('Generate token and init library with it', async function () { + const helper = this.test.helper; var tokenDetails = await rest.auth.requestToken(); expect(tokenDetails.token, 'Verify token value').to.be.ok; helper.AblyRest({ token: tokenDetails.token }); @@ -162,6 +162,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * @specpartial RSA6 - infer capability from provided key */ it('Token generation with specified key', async function () { + const helper = this.test.helper; var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; var testCapability = JSON.parse(helper.getTestApp().keys[1].capability); var tokenDetails = await rest.auth.requestToken(null, testKeyOpts); @@ -174,6 +175,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as /** @nospec */ it('Token generation with explicit auth', async function () { + const helper = this.test.helper; const authHeaders = await rest.auth.getAuthHeaders(); rest.auth.authOptions.requestHeaders = authHeaders; var tokenDetails = await rest.auth.requestToken(); @@ -189,6 +191,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * @nospec */ it('Token generation with explicit auth, different key', async function () { + const helper = this.test.helper; const authHeaders = await rest.auth.getAuthHeaders(); var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; var testCapability = JSON.parse(helper.getTestApp().keys[1].capability); @@ -216,6 +219,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as /** @spec TO3j11 */ it('Token generation with defaultTokenParams set and no tokenParams passed in', async function () { + const helper = this.test.helper; var rest1 = helper.AblyRest({ defaultTokenParams: { ttl: 123, clientId: 'foo' } }); var tokenDetails = await rest1.auth.requestToken(); expect(tokenDetails.token, 'Verify token value').to.be.ok; @@ -228,6 +232,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * @specpartial RSA8e - test passing any options overrides library default */ it('Token generation: if tokenParams passed in, defaultTokenParams should be ignored altogether, not merged', async function () { + const helper = this.test.helper; var rest1 = helper.AblyRest({ defaultTokenParams: { ttl: 123, clientId: 'foo' } }); var tokenDetails = await rest1.auth.requestToken({ clientId: 'bar' }, null); expect(tokenDetails.clientId).to.equal( @@ -320,6 +325,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * @specpartial RSA9h - test passing null for TokenParams and AuthOptions */ it('createTokenRequest without authOptions', async function () { + const helper = this.test.helper; var tokenRequest = await rest.auth.createTokenRequest(null, null); expect('mac' in tokenRequest, 'check tokenRequest contains a mac').to.be.ok; expect('nonce' in tokenRequest, 'check tokenRequest contains a nonce').to.be.ok; @@ -334,6 +340,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * @nospec */ it('createTokenRequest uses the key it was initialized with if authOptions does not have a "key" key', async function () { + const helper = this.test.helper; var tokenRequest = await rest.auth.createTokenRequest(); expect(tokenRequest.keyName).to.equal(helper.getTestApp().keys[0].keyName); }); @@ -369,6 +376,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * @specpartial RSA3d - test JWT is correctly passed in REST request */ it(description, async function () { + const helper = this.test.helper; var currentKey = helper.getTestApp().keys[0]; var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var authParams = helper.Utils.mixin(keys, params); @@ -400,6 +408,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * @nospec */ it('JWT request with invalid key', async function () { + const helper = this.test.helper; var keys = { keyName: 'invalid.invalid', keySecret: 'invalidinvalid' }; var authUrl = echoServer + '/createJWT' + helper.Utils.toQueryString(keys); var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); @@ -418,6 +427,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as /** @specpartial RSA8g - test using authCallback with JWT */ it('Rest JWT with authCallback', async function () { + const helper = this.test.helper; var currentKey = helper.getTestApp().keys[0]; var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var authUrl = echoServer + '/createJWT' + helper.Utils.toQueryString(keys); @@ -438,6 +448,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * @nospec */ it('Rest JWT with authCallback and invalid keys', async function () { + const helper = this.test.helper; var keys = { keyName: 'invalid.invalid', keySecret: 'invalidinvalid' }; var authUrl = echoServer + '/createJWT' + helper.Utils.toQueryString(keys); var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); @@ -464,6 +475,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * @nospec */ it('authCallback is only invoked once on concurrent auth', async function () { + const helper = this.test.helper; var authCallbackInvocations = 0; function authCallback(tokenParams, callback) { authCallbackInvocations++; diff --git a/test/rest/batch.test.js b/test/rest/batch.test.js index 2b19faaa6..ce6ccc724 100644 --- a/test/rest/batch.test.js +++ b/test/rest/batch.test.js @@ -1,14 +1,13 @@ 'use strict'; define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { - const helper = new Helper(); - var expect = chai.expect; describe('rest/batchPublish', function () { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -33,6 +32,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @specpartial RSC22b - test returns an array of BatchResult */ it('performs a batch publish and returns an array of results', async function () { + const helper = this.test.helper; const testApp = helper.getTestApp(); const rest = helper.AblyRest({ promises: true, @@ -123,6 +123,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @specpartial RSC22b - test returns a single BatchResult */ it('performs a batch publish and returns a single result', async function () { + const helper = this.test.helper; const testApp = helper.getTestApp(); const rest = helper.AblyRest({ promises: true, @@ -168,6 +169,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -187,6 +189,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @spec BGF2b */ it('performs a batch presence fetch and returns a result', async function () { + const helper = this.test.helper; const testApp = helper.getTestApp(); const rest = helper.AblyRest({ promises: true, @@ -239,6 +242,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -263,6 +267,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @specpartial RSA17g - test passing an array of TokenRevocationTargetSpecifier */ it('revokes tokens matching the given specifiers', async function () { + const helper = this.test.helper; const testApp = helper.getTestApp(); const rest = helper.AblyRest({ promises: true, @@ -359,6 +364,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @spec TRS2c */ it('accepts optional issuedBefore and allowReauthMargin parameters', async function () { + const helper = this.test.helper; const testApp = helper.getTestApp(); const rest = helper.AblyRest({ promises: true, @@ -387,6 +393,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @spec RSA17d */ it('throws an error when using token auth', async function () { + const helper = this.test.helper; const rest = helper.AblyRest({ useTokenAuth: true, }); diff --git a/test/rest/capability.test.js b/test/rest/capability.test.js index 52df30bd1..b145ee3c7 100644 --- a/test/rest/capability.test.js +++ b/test/rest/capability.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['shared_helper', 'chai'], function (Helper, chai) { - const helper = new Helper(); - var currentTime; var rest; var testApp; @@ -21,6 +19,7 @@ define(['shared_helper', 'chai'], function (Helper, chai) { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function () { rest = helper.AblyRest({ queryTime: true }); testApp = helper.getTestApp(); diff --git a/test/rest/fallbacks.test.js b/test/rest/fallbacks.test.js index e8bafb93b..b817e8111 100644 --- a/test/rest/fallbacks.test.js +++ b/test/rest/fallbacks.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; var goodHost; @@ -10,6 +8,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -22,6 +21,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { /** @spec RSC15f */ it('Store working fallback', async function () { + const helper = this.test.helper; var rest = helper.AblyRest({ restHost: helper.unroutableHost, fallbackHosts: [goodHost], @@ -56,6 +56,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { describe('Max elapsed time for host retries', function () { /** @spec TO3l6 */ it('can timeout after default host', async function () { + const helper = this.test.helper; const httpRequestTimeout = 1000; // set httpMaxRetryDuration lower than httpRequestTimeout so it would timeout after default host attempt const httpMaxRetryDuration = Math.floor(httpRequestTimeout / 2); @@ -82,6 +83,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { /** @spec TO3l6 */ it('can timeout after fallback host retries', async function () { + const helper = this.test.helper; const httpRequestTimeout = 1000; // set httpMaxRetryDuration higher than httpRequestTimeout and lower than 2*httpRequestTimeout so it would timeout after first fallback host retry attempt const httpMaxRetryDuration = Math.floor(httpRequestTimeout * 1.5); diff --git a/test/rest/history.test.js b/test/rest/history.test.js index 5d037f121..105f5cba4 100644 --- a/test/rest/history.test.js +++ b/test/rest/history.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { - const helper = new Helper(); - var rest; var expect = chai.expect; var exports = {}; @@ -21,6 +19,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function () { rest = helper.AblyRest(); done(); @@ -32,7 +31,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * @spec RSL2 * @spec RSL2a */ - Helper.restTestOnJsonMsgpack('history_simple', async function (rest, channelName) { + Helper.restTestOnJsonMsgpack('history_simple', async function (rest, channelName, helper) { var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ @@ -63,7 +62,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * @spec RSL2 * @spec RSL2a */ - Helper.restTestOnJsonMsgpack('history_multiple', async function (rest, channelName) { + Helper.restTestOnJsonMsgpack('history_multiple', async function (rest, channelName, helper) { var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ @@ -91,7 +90,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * @spec RSL2b2 * @specpartial RSL2b3 - should also test maximum supported limit of 1000 */ - Helper.restTestOnJsonMsgpack('history_simple_paginated_b', async function (rest, channelName) { + Helper.restTestOnJsonMsgpack('history_simple_paginated_b', async function (rest, channelName, helper) { var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ @@ -134,6 +133,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * @specpartial RSL2b3 - should also test maximum supported limit of 1000 */ it('history_simple_paginated_f', async function () { + const helper = this.test.helper; var testchannel = rest.channels.get('persisted:history_simple_paginated_f'); /* first, send a number of events to this channel */ @@ -215,6 +215,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * @specpartial RSL2b3 - should also test maximum supported limit of 1000 */ it('history_multiple_paginated_f', async function () { + const helper = this.test.helper; var testchannel = rest.channels.get('persisted:history_multiple_paginated_f'); /* first, send a number of events to this channel */ diff --git a/test/rest/http.test.js b/test/rest/http.test.js index eee16156d..2ffd375f0 100644 --- a/test/rest/http.test.js +++ b/test/rest/http.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { - const helper = new Helper(); - var rest; var expect = chai.expect; var Defaults = Ably.Rest.Platform.Defaults; @@ -10,6 +8,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { describe('rest/http', function () { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function () { rest = helper.AblyRest({ agents: { diff --git a/test/rest/init.test.js b/test/rest/init.test.js index c218b7c57..00cb1a44a 100644 --- a/test/rest/init.test.js +++ b/test/rest/init.test.js @@ -1,14 +1,13 @@ 'use strict'; define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { - const helper = new Helper(); - var expect = chai.expect; describe('rest/init', function () { this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -23,6 +22,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @specpartial RSC1c - test with key string */ it('Init with key string', function () { + const helper = this.test.helper; var keyStr = helper.getTestApp().keys[0].keyStr; var rest = new helper.Ably.Rest(keyStr); @@ -34,6 +34,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @specpartial RSC1c - test with token string */ it('Init with token string', async function () { + const helper = this.test.helper; /* first generate a token ... */ var rest = helper.AblyRest(); var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; @@ -52,6 +53,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @spec TO3k5 */ it('Init with tls: false', function () { + const helper = this.test.helper; var rest = helper.AblyRest({ tls: false, port: 123, tlsPort: 456 }); expect(rest.baseUri('example.com')).to.equal('http://example.com:123'); }); @@ -62,6 +64,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @spec TO3k5 */ it('Init with tls: true', function () { + const helper = this.test.helper; var rest = helper.AblyRest({ tls: true, port: 123, tlsPort: 456 }); expect(rest.baseUri('example.com')).to.equal('https://example.com:456'); }); @@ -75,6 +78,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { */ it('Init without any tls key should enable tls', function () { + const helper = this.test.helper; var rest = helper.AblyRest({ port: 123, tlsPort: 456 }); expect(rest.baseUri('example.com')).to.equal('https://example.com:456'); }); @@ -85,6 +89,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * @spec RSA15c */ it("Init with clientId set to '*' or anything other than a string or null should error", function () { + const helper = this.test.helper; expect(function () { var rest = helper.AblyRest({ clientId: '*' }); }, 'Check can’t init library with a wildcard clientId').to.throw; diff --git a/test/rest/message.test.js b/test/rest/message.test.js index f22c2ee5f..4eac3391e 100644 --- a/test/rest/message.test.js +++ b/test/rest/message.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var expect = chai.expect; var noop = function () {}; @@ -10,6 +8,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -25,7 +24,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSL1m1 */ it('Should implicitly send clientId when authenticated with clientId', async function () { - var clientId = 'implicit_client_id_0', + var helper = this.test.helper, + clientId = 'implicit_client_id_0', rest = helper.AblyRest({ clientId: clientId, useBinaryProtocol: false }), channel = rest.channels.get('rest_implicit_client_id_0'); @@ -51,7 +51,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSL1m2 */ it('Should publish clientId when provided explicitly in message', async function () { - var clientId = 'explicit_client_id_0', + var helper = this.test.helper, + clientId = 'explicit_client_id_0', rest = helper.AblyRest({ clientId: clientId, useBinaryProtocol: false }), channel = rest.channels.get('rest_explicit_client_id_0'); @@ -79,7 +80,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSL1m4 */ it('Should error when clientId sent in message is different than authenticated clientId', async function () { - var clientId = 'explicit_client_id_0', + var helper = this.test.helper, + clientId = 'explicit_client_id_0', invalidClientId = 'invalid'; var token = await helper.AblyRest().auth.requestToken({ clientId: clientId }); @@ -118,7 +120,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it('Should error when publishing message larger than maxMessageSize', async function () { /* No connectionDetails mechanism for REST, so just pass the override into the constructor */ - var realtime = helper.AblyRest({ maxMessageSize: 64 }), + var helper = this.test.helper, + realtime = helper.AblyRest({ maxMessageSize: 64 }), channel = realtime.channels.get('maxMessageSize'); try { @@ -140,7 +143,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSL1k5 */ it('Should send correct IDs when idempotentRestPublishing set to false', async function () { - var rest = helper.AblyRest({ idempotentRestPublishing: false, useBinaryProtocol: false }), + var helper = this.test.helper, + rest = helper.AblyRest({ idempotentRestPublishing: false, useBinaryProtocol: false }), channel = rest.channels.get('idempotent_rest_publishing'), message = { name: 'test', id: 'idempotent-msg-id:0' }; @@ -160,7 +164,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it('Should add IDs when automatic idempotent rest publishing option enabled', async function () { /* easiest way to get the host we're using for tests */ - var dummyRest = helper.AblyRest(), + var helper = this.test.helper, + dummyRest = helper.AblyRest(), host = dummyRest.options.restHost, /* Add the same host as a bunch of fallback hosts, so after the first * request 'fails' we retry on the same host using the fallback mechanism */ @@ -220,7 +225,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @specpartial RSL1e - test only passing null to the function */ it('Rest publish params', async function () { - var rest = helper.AblyRest(), + var helper = this.test.helper, + rest = helper.AblyRest(), channel = rest.channels.get('publish_params'); var originalPublish = channel._publish; diff --git a/test/rest/presence.test.js b/test/rest/presence.test.js index 55e1471d4..21ebbe0df 100644 --- a/test/rest/presence.test.js +++ b/test/rest/presence.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var rest; var cipherConfig; var expect = chai.expect; @@ -25,6 +23,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function () { rest = helper.AblyRest(); cipherConfig = helper.getTestApp().cipherConfig; diff --git a/test/rest/push.test.js b/test/rest/push.test.js index e00406bfd..0b958d5db 100644 --- a/test/rest/push.test.js +++ b/test/rest/push.test.js @@ -8,16 +8,14 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra pushChannelTransport, PushPlugin, ) { - const helper = new Helper(); - var expect = chai.expect; var originalPushConfig = Ably.Realtime.Platform.Config.push; - function PushRealtime(options) { + function PushRealtime(helper, options) { return helper.AblyRealtime({ ...options, plugins: { Push: PushPlugin } }); } - function PushRest(options) { + function PushRest(helper, options) { return helper.AblyRest({ ...options, plugins: { Push: PushPlugin } }); } @@ -50,6 +48,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); Ably.Realtime.Platform.Config.push = pushChannelTransport; helper.setupApp(function (err) { if (err) { @@ -73,6 +72,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra * @specpartial RSH1c1 - tests only filtering by 'channel', should also tests other params */ it('Get subscriptions', async function () { + const helper = this.test.helper; var subscribes = []; var deletes = []; var subsByChannel = {}; @@ -105,6 +105,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @specpartial RSH1a - tests only valid recipient and payload data, should test empty and invalid data too */ it('Publish', async function () { + const helper = this.test.helper; try { var realtime = helper.AblyRealtime(); @@ -143,6 +144,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @specpartial RSH1b3 - tests only successful save, should also test a successful subsequent save with an update, and a failed save operation */ it('deviceRegistrations save', async function () { + const helper = this.test.helper; var rest = helper.AblyRest(); var saved = await rest.push.admin.deviceRegistrations.save(testDevice); @@ -163,6 +165,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra * @specpartial RSH1b2 - tests .list only with no params and filtered by clientId, should also test with other supported parameters */ it('deviceRegistrations get and list', async function () { + const helper = this.test.helper; var registrations = []; var deletes = []; var devices = []; @@ -242,6 +245,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra * @specpartial RSH1b5 - tests .removeWhere only with filtering by deviceId, should also test with other supported params and with no matching params */ it('deviceRegistrations remove removeWhere', async function () { + const helper = this.test.helper; var rest = helper.AblyRest(); await rest.push.admin.deviceRegistrations.save(testDevice); @@ -267,6 +271,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @specpartial RSH1c3 - tests only successful save, should also test a successful subsequent save with an update, and a failed save operation */ it('channelSubscriptions save', async function () { + const helper = this.test.helper; var rest = helper.AblyRest({ clientId: 'testClient' }); var subscription = { clientId: 'testClient', channel: 'pushenabled:foo' }; @@ -288,6 +293,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra * @specpartial RSH1c1 - tests only filtering by 'channel', should also tests other params */ it('channelSubscriptions get', async function () { + const helper = this.test.helper; var subscribes = []; var deletes = []; var subsByChannel = {}; @@ -327,6 +333,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra * @specpartial RSH1c4 - tests .remove only with clientId and channel parameters, should also test other supported parameters and test non-matching parameters */ it('push_channelSubscriptions_remove', async function () { + const helper = this.test.helper; var rest = helper.AblyRest({ clientId: 'testClient' }); var subscription = { clientId: 'testClient', channel: 'pushenabled:foo' }; @@ -339,6 +346,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra * @specpartial RSH1c2 - only tests .listChannels with no parameters */ it('channelSubscriptions listChannels', async function () { + const helper = this.test.helper; var subscribes = []; var deletes = []; for (var i = 0; i < 5; i++) { @@ -368,15 +376,17 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra describe('push activation', function () { /** @spec RSH2a */ it('push_activation_succeeds', async function () { - const rest = PushRealtime({ pushRecipientChannel: 'my_channel' }); + const rest = PushRealtime(this.test.helper, { pushRecipientChannel: 'my_channel' }); await rest.push.activate(); expect(rest.device.deviceIdentityToken).to.be.ok; }); /** @nospec */ it('device_push', function (done) { + const helper = this.test.helper; + const channelName = 'pushenabled:device_push'; - const realtime = PushRealtime({ pushRecipientChannel: channelName }); + const realtime = PushRealtime(helper, { pushRecipientChannel: channelName }); const pushPayload = { notification: { title: 'Test message', body: 'Test message body' }, @@ -417,9 +427,11 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @spec RSH7b */ it('subscribe_client', async function () { + const helper = this.test.helper; + const clientId = 'me'; const channelName = 'pushenabled:subscribe_client'; - const rest = PushRest({ clientId, pushRecipientChannel: channelName }); + const rest = PushRest(helper, { clientId, pushRecipientChannel: channelName }); const channel = rest.channels.get(channelName); await rest.push.activate(); @@ -435,8 +447,10 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @spec RSH7b1 */ it('subscribe_client_without_clientId', async function () { + const helper = this.test.helper; + const channelName = 'pushenabled:subscribe_client_without_clientId'; - const rest = PushRest({ pushRecipientChannel: 'hello' }); + const rest = PushRest(helper, { pushRecipientChannel: 'hello' }); await rest.push.activate(); const channel = rest.channels.get(channelName); try { @@ -451,9 +465,11 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @spec RSH7d */ it('unsubscribe_client', async function () { + const helper = this.test.helper; + const clientId = 'me'; const channelName = 'pushenabled:unsubscribe_client'; - const rest = PushRest({ clientId, pushRecipientChannel: channelName }); + const rest = PushRest(helper, { clientId, pushRecipientChannel: channelName }); const channel = rest.channels.get(channelName); await rest.push.activate(); @@ -469,10 +485,12 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @nospec */ it('direct_publish_client_id', async function () { + const helper = this.test.helper; + const clientId = 'me2'; const channelName = 'pushenabled:direct_publish_client_id'; - const rest = PushRest({ clientId, pushRecipientChannel: channelName }); - const realtime = PushRealtime(); + const rest = PushRest(helper, { clientId, pushRecipientChannel: channelName }); + const realtime = PushRealtime(helper); const rtChannel = realtime.channels.get(channelName); const channel = rest.channels.get(channelName); @@ -505,8 +523,10 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @spec RSH7a */ it('subscribe_device', async function () { + const helper = this.test.helper; + const channelName = 'pushenabled:subscribe_device'; - const rest = PushRest({ pushRecipientChannel: channelName }); + const rest = PushRest(helper, { pushRecipientChannel: channelName }); const channel = rest.channels.get(channelName); await rest.push.activate(); @@ -522,8 +542,10 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @spec RSH7c */ it('unsubscribe_device', async function () { + const helper = this.test.helper; + const channelName = 'pushenabled:unsubscribe_device'; - const rest = PushRest({ pushRecipientChannel: channelName }); + const rest = PushRest(helper, { pushRecipientChannel: channelName }); const channel = rest.channels.get(channelName); await rest.push.activate(); @@ -539,9 +561,11 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @nospec */ it('direct_publish_device_id', async function () { + const helper = this.test.helper; + const channelName = 'direct_publish_device_id'; - const rest = PushRest({ pushRecipientChannel: channelName }); - const realtime = PushRealtime(); + const rest = PushRest(helper, { pushRecipientChannel: channelName }); + const realtime = PushRealtime(helper); const rtChannel = realtime.channels.get(channelName); const channel = rest.channels.get(channelName); @@ -574,10 +598,12 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @nospec */ it('push_channel_subscription_device_id', async function () { + const helper = this.test.helper; + const pushRecipientChannel = 'push_channel_subscription_device_id'; const channelName = 'pushenabled:push_channel_subscription_device_id'; - const rest = PushRest({ pushRecipientChannel }); - const realtime = PushRealtime(); + const rest = PushRest(helper, { pushRecipientChannel }); + const realtime = PushRealtime(helper); const channel = rest.channels.get(channelName); const rtChannel = realtime.channels.get(pushRecipientChannel); @@ -615,10 +641,12 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @nospec */ it('push_channel_subscription_client_id', async function () { + const helper = this.test.helper; + const pushRecipientChannel = 'push_channel_subscription_client_id'; const channelName = 'pushenabled:push_channel_subscription_client_id'; - const rest = PushRest({ clientId: 'me', pushRecipientChannel }); - const realtime = PushRealtime(); + const rest = PushRest(helper, { clientId: 'me', pushRecipientChannel }); + const realtime = PushRealtime(helper); const channel = rest.channels.get(channelName); const rtChannel = realtime.channels.get(pushRecipientChannel); @@ -656,7 +684,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @spec RSH8h */ it('failed_getting_device_details', async function () { - const rest = PushRest(); + const rest = PushRest(this.test.helper); try { await rest.push.activate(); } catch (err) { @@ -670,7 +698,7 @@ define(['ably', 'shared_helper', 'async', 'chai', 'test/support/push_channel_tra /** @spec RSH3b3c */ it('failed_registration', async function () { const pushRecipientChannel = 'failed_registration'; - const rest = PushRest({ pushRecipientChannel }); + const rest = PushRest(this.test.helper, { pushRecipientChannel }); rest.device.platform = 'not_a_real_platform'; try { await rest.push.activate(); diff --git a/test/rest/request.test.js b/test/rest/request.test.js index bba9f0744..541e42386 100644 --- a/test/rest/request.test.js +++ b/test/rest/request.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async, chai) { - const helper = new Helper(); - var rest; var expect = chai.expect; var echoServerHost = 'echo.ably.io'; @@ -12,6 +10,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async this.timeout(60 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); @@ -88,6 +87,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * @spec RSC19e */ it('request_network_error', async function () { + const helper = this.test.helper; rest = helper.AblyRest({ restHost: helper.unroutableAddress }); try { var res = await rest.request('get', '/time', 3, null, null, null); @@ -212,6 +212,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async ['put', 'patch', 'delete'].forEach(function (method) { /** @specpartial RSC19f - tests put, patch, delete methods are supported */ it('check' + method, async function () { + const helper = this.test.helper; var restEcho = helper.AblyRest({ useBinaryProtocol: false, restHost: echoServerHost, tls: true }); var res = await restEcho.request(method, '/methods', 3, {}, {}, {}); expect(res.items[0] && res.items[0].method).to.equal(method); diff --git a/test/rest/stats.test.js b/test/rest/stats.test.js index a92334069..41e46347c 100644 --- a/test/rest/stats.test.js +++ b/test/rest/stats.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['shared_helper', 'chai'], function (Helper, chai) { - const helper = new Helper(); - var rest; var expect = chai.expect; @@ -65,6 +63,7 @@ define(['shared_helper', 'chai'], function (Helper, chai) { before(function (done) { // force a new app to be created with first argument true so that stats are not effected by other tests + const helper = Helper.forHook(this); helper.setupApp(true, function () { rest = helper.AblyRest(); helper.createStats(helper.getTestApp(), statsFixtures, function (err) { diff --git a/test/rest/status.test.js b/test/rest/status.test.js index 422868913..c1e52a20b 100644 --- a/test/rest/status.test.js +++ b/test/rest/status.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['shared_helper', 'chai'], function (Helper, chai) { - const helper = new Helper(); - var rest; var expect = chai.expect; @@ -10,6 +8,7 @@ define(['shared_helper', 'chai'], function (Helper, chai) { this.timeout(30 * 1000); before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); diff --git a/test/rest/time.test.js b/test/rest/time.test.js index bce93d1b4..4374116f7 100644 --- a/test/rest/time.test.js +++ b/test/rest/time.test.js @@ -1,13 +1,12 @@ 'use strict'; define(['shared_helper', 'chai'], function (Helper, chai) { - const helper = new Helper(); - var rest; var expect = chai.expect; describe('rest/time', function () { before(function (done) { + const helper = Helper.forHook(this); helper.setupApp(function (err) { if (err) { done(err); diff --git a/test/support/root_hooks.js b/test/support/root_hooks.js index 7e7ed1005..a3e999c33 100644 --- a/test/support/root_hooks.js +++ b/test/support/root_hooks.js @@ -1,7 +1,6 @@ define(['shared_helper'], function (Helper) { - const helper = new Helper(); - after(function (done) { + const helper = Helper.forHook(this); this.timeout(10 * 1000); helper.tearDownApp(function (err) { if (err) { @@ -13,15 +12,18 @@ define(['shared_helper'], function (Helper) { }); afterEach(function () { - helper.closeActiveClients(); + this.currentTest.helper.closeActiveClients(); }); afterEach(function () { - helper.logTestResults(this); + this.currentTest.helper.logTestResults(this); }); afterEach(function () { - helper.flushTestLogs(); + this.currentTest.helper.flushTestLogs(); + }); + beforeEach(function () { + this.currentTest.helper = Helper.forTest(this); }); beforeEach(function () { - helper.clearTransportPreference(); + this.currentTest.helper.clearTransportPreference(); }); });