diff --git a/test/browser/connection.test.js b/test/browser/connection.test.js index 69abc4fb4..86d304b77 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); @@ -42,6 +41,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('device_going_offline_causes_disconnected_state', function (done) { + const helper = this.helper; + var realtime = helper.AblyRealtime(), connection = realtime.connection, offlineEvent = new Event('offline', { bubbles: true }); @@ -84,6 +85,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('device_going_online_causes_disconnected_connection_to_reconnect_immediately', function (done) { + const helper = this.helper; + /* Give up trying to connect fairly quickly */ var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 1000 }), connection = realtime.connection, @@ -129,6 +132,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('device_going_online_causes_suspended_connection_to_reconnect_immediately', function (done) { + const helper = this.helper; + /* move to suspended state after 2s of being disconnected */ var realtime = helper.AblyRealtime({ disconnectedRetryTimeout: 500, @@ -174,6 +179,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('device_going_online_causes_connecting_connection_to_retry_attempt', function (done) { + const helper = this.helper; + var realtime = helper.AblyRealtime({}), connection = realtime.connection, onlineEvent = new Event('online', { bubbles: true }), @@ -209,6 +216,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { } it('page_refresh_with_recovery', function (done) { + const helper = this.helper; + var realtimeOpts = { recover: function (lastConnectionDetails, cb) { cb(true); @@ -250,6 +259,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('page_refresh_persist_with_denied_recovery', function (done) { + const helper = this.helper; + var realtimeOpts = { recover: function (lastConnectionDetails, cb) { cb(false); @@ -292,10 +303,10 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('page_refresh_with_close_on_unload', function (done) { - var realtime = helper.AblyRealtime({ closeOnUnload: true }), + var realtime = this.helper.AblyRealtime({ closeOnUnload: true }), refreshEvent = new Event('beforeunload', { bubbles: true }); - helper.monitorConnection(done, realtime); + this.helper.monitorConnection(done, realtime); realtime.connection.once('connected', function () { try { @@ -312,6 +323,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('page_refresh_with_manual_recovery', function (done) { + const helper = this.helper; + var realtime = helper.AblyRealtime({ closeOnUnload: false }), refreshEvent = new Event('beforeunload', { bubbles: true }); @@ -349,12 +362,12 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); }); - 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.helper.AblyRealtime(opts1), + realtime2 = this.helper.AblyRealtime(opts2), refreshEvent = new Event('beforeunload', { bubbles: true }); await Promise.all([realtime1.connection.once('connected'), realtime2.connection.once('connected')]); @@ -363,23 +376,25 @@ define(['shared_helper', 'chai'], function (Helper, chai) { document.dispatchEvent(refreshEvent); - helper.simulateDroppedConnection(realtime1); - helper.simulateDroppedConnection(realtime2); + this.helper.simulateDroppedConnection(realtime1); + this.helper.simulateDroppedConnection(realtime2); await new Promise((res) => setTimeout(res, 1000)); - const newRealtime1 = helper.AblyRealtime(opts1); - const newRealtime2 = helper.AblyRealtime(opts2); + const newRealtime1 = this.helper.AblyRealtime(opts1); + const newRealtime2 = this.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.helper.closeAndFinishAsync(rt)), ); }); it('persist_preferred_transport', function (done) { + const helper = this.helper; + var realtime = helper.AblyRealtime(); realtime.connection.connectionManager.on(function (transport) { @@ -399,15 +414,15 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('browser_transports', function (done) { - var realtime = helper.AblyRealtime(); + var realtime = this.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.helper.closeAndFinish(done, realtime, err); return; } - helper.closeAndFinish(done, realtime); + this.helper.closeAndFinish(done, realtime); }); }); } diff --git a/test/browser/http.test.js b/test/browser/http.test.js index f60daa1f1..5c60ade3f 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 be476d4a7..d52e3b678 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); }); @@ -81,9 +81,9 @@ function registerAblyModularTests(Helper) { describe('without any plugins', () => { for (const clientClass of [BaseRest, BaseRealtime]) { - describe(clientClass.name, () => { + describe(clientClass.name, function () { it('throws an error due to the absence of an HTTP plugin', () => { - expect(() => new clientClass(helper.ablyClientOptions())).to.throw( + expect(() => new clientClass(this.helper.ablyClientOptions())).to.throw( 'No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.', ); }); @@ -100,7 +100,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, @@ -118,7 +118,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 */ }; }, @@ -141,14 +141,15 @@ function registerAblyModularTests(Helper) { describe('BaseRest without explicit Rest', () => { for (const scenario of restScenarios) { - it(`allows you to ${scenario.description}`, async () => { + it(`allows you to ${scenario.description}`, async function () { + const helper = this.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; } @@ -160,9 +161,9 @@ function registerAblyModularTests(Helper) { describe('BaseRealtime with Rest', () => { for (const scenario of restScenarios) { - it(`allows you to ${scenario.description}`, async () => { + it(`allows you to ${scenario.description}`, async function () { const client = new BaseRealtime( - helper.ablyClientOptions({ + this.helper.ablyClientOptions({ autoConnect: false, ...scenario.getAdditionalClientOptions?.(), plugins: { @@ -187,29 +188,36 @@ function registerAblyModularTests(Helper) { }); describe('BaseRealtime without Rest', () => { - 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.helper; + const client = new BaseRealtime( + this.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, + ); }); - 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.helper.ablyClientOptions({ autoConnect: false, plugins: { WebSocketTransport, FetchRequest } }), ); const tokenRequest = await client.auth.createTokenRequest(); @@ -217,9 +225,9 @@ function registerAblyModularTests(Helper) { }); for (const scenario of restScenarios) { - it(`throws an error when attempting to ${scenario.description}`, async () => { + it(`throws an error when attempting to ${scenario.description}`, async function () { const client = new BaseRealtime( - helper.ablyClientOptions({ + this.helper.ablyClientOptions({ autoConnect: false, ...scenario.getAdditionalClientOptions?.(), plugins: { @@ -258,8 +266,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); @@ -268,12 +276,13 @@ function registerAblyModularTests(Helper) { } describe('decodeMessage', () => { - it('decodes a message’s data', async () => { - testDecodesMessageData(decodeMessage); + it('decodes a message’s data', async function () { + testDecodesMessageData(this.helper, decodeMessage); }); it('throws an error when given channel options with a cipher', async () => { - const testData = await loadTestData(helper.testResourcesPath + 'crypto-data-128.json'); + const helper = this.helper; + const testData = await loadTestData(helper, helper.testResourcesPath + 'crypto-data-128.json'); const key = BufferUtils.base64Decode(testData.key); const iv = BufferUtils.base64Decode(testData.iv); @@ -290,12 +299,13 @@ function registerAblyModularTests(Helper) { }); describe('decodeEncryptedMessage', async () => { - it('decodes a message’s data', async () => { - testDecodesMessageData(decodeEncryptedMessage); + it('decodes a message’s data', async function () { + testDecodesMessageData(this.helper, decodeEncryptedMessage); }); - it('decrypts a message', async () => { - const testData = await loadTestData(helper.testResourcesPath + 'crypto-data-128.json'); + it('decrypts a message', async function () { + const helper = this.helper; + const testData = await loadTestData(helper, helper.testResourcesPath + 'crypto-data-128.json'); const key = BufferUtils.base64Decode(testData.key); const iv = BufferUtils.base64Decode(testData.iv); @@ -306,13 +316,13 @@ function registerAblyModularTests(Helper) { decodeEncryptedMessage(item.encrypted, { cipher: { key, iv } }), ]); - helper.testMessageEquality(decodedFromEncoded, decodedFromEncrypted); + this.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)); @@ -322,12 +332,13 @@ function registerAblyModularTests(Helper) { } describe('decodeMessages', () => { - it('decodes messages’ data', async () => { - testDecodesMessagesData(decodeMessages); + it('decodes messages’ data', async function () { + testDecodesMessagesData(this.helper, decodeMessages); }); - 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.helper; + const testData = await loadTestData(helper, helper.testResourcesPath + 'crypto-data-128.json'); const key = BufferUtils.base64Decode(testData.key); const iv = BufferUtils.base64Decode(testData.iv); @@ -347,12 +358,13 @@ function registerAblyModularTests(Helper) { }); describe('decodeEncryptedMessages', () => { - it('decodes messages’ data', async () => { - testDecodesMessagesData(decodeEncryptedMessages); + it('decodes messages’ data', async function () { + testDecodesMessagesData(this.helper, decodeEncryptedMessages); }); - it('decrypts messages', async () => { - const testData = await loadTestData(helper.testResourcesPath + 'crypto-data-128.json'); + it('decrypts messages', async function () { + const helper = this.helper; + const testData = await loadTestData(helper, helper.testResourcesPath + 'crypto-data-128.json'); const key = BufferUtils.base64Decode(testData.key); const iv = BufferUtils.base64Decode(testData.iv); @@ -366,7 +378,7 @@ function registerAblyModularTests(Helper) { ]); for (let i = 0; i < decodedFromEncoded.length; i++) { - helper.testMessageEquality(decodedFromEncoded[i], decodedFromEncrypted[i]); + this.helper.testMessageEquality(decodedFromEncoded[i], decodedFromEncrypted[i]); } }); }); @@ -374,7 +386,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, @@ -397,15 +409,15 @@ function registerAblyModularTests(Helper) { }, ]) { describe(clientClassConfig.clientClass.name, () => { - 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.helper, clientClassConfig); }); }); } }); describe('with Crypto', () => { - async function testIsAbleToPublishEncryptedMessages(clientClassConfig) { + async function testIsAbleToPublishEncryptedMessages(helper, clientClassConfig) { const clientOptions = helper.ablyClientOptions(); const key = await generateRandomKey(); @@ -414,41 +426,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 [ @@ -460,8 +479,8 @@ function registerAblyModularTests(Helper) { }, ]) { describe(clientClassConfig.clientClass.name, () => { - it('is able to publish encrypted messages', async () => { - await testIsAbleToPublishEncryptedMessages(clientClassConfig); + it('is able to publish encrypted messages', async function () { + await testIsAbleToPublishEncryptedMessages(this.helper, clientClassConfig); }); }); } @@ -504,16 +523,17 @@ function registerAblyModularTests(Helper) { describe('with useBinaryProtocol client option', () => { describe('without MsgPack', () => { describe('BaseRest', () => { - it('uses JSON', async () => { + it('uses JSON', async function () { const client = new BaseRest( - helper.ablyClientOptions({ useBinaryProtocol: true, plugins: { FetchRequest } }), + this.helper.ablyClientOptions({ useBinaryProtocol: true, plugins: { FetchRequest } }), ); await testRestUsesContentType(client, 'application/json'); }); }); describe('BaseRealtime', () => { - it('uses JSON', async () => { + it('uses JSON', async function () { + const helper = this.helper; const client = new BaseRealtime( helper.ablyClientOptions({ useBinaryProtocol: true, @@ -525,18 +545,22 @@ function registerAblyModularTests(Helper) { }), ); - await monitorConnectionThenCloseAndFinish(async () => { - await testRealtimeUsesFormat(client, 'json'); - }, client); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + await testRealtimeUsesFormat(client, 'json'); + }, + client, + ); }); }); }); describe('with MsgPack', () => { describe('BaseRest', () => { - it('uses MessagePack', async () => { + it('uses MessagePack', async function () { const client = new BaseRest( - helper.ablyClientOptions({ + this.helper.ablyClientOptions({ useBinaryProtocol: true, plugins: { FetchRequest, @@ -549,7 +573,8 @@ function registerAblyModularTests(Helper) { }); describe('BaseRealtime', () => { - it('uses MessagePack', async () => { + it('uses MessagePack', async function () { + const helper = this.helper; const client = new BaseRealtime( helper.ablyClientOptions({ useBinaryProtocol: true, @@ -562,9 +587,13 @@ function registerAblyModularTests(Helper) { }), ); - await monitorConnectionThenCloseAndFinish(async () => { - await testRealtimeUsesFormat(client, 'msgpack'); - }, client); + await monitorConnectionThenCloseAndFinish( + helper, + async () => { + await testRealtimeUsesFormat(client, 'msgpack'); + }, + client, + ); }); }); }); @@ -573,55 +602,70 @@ function registerAblyModularTests(Helper) { describe('RealtimePresence', () => { describe('BaseRealtime without RealtimePresence', () => { - 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.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, + ); }); - 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.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.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, + ); }); }); describe('BaseRealtime with RealtimePresence', () => { - it('offers realtime presence functionality', async () => { + it('offers realtime presence functionality', async function () { + const helper = this.helper; const rxClient = new BaseRealtime( helper.ablyClientOptions({ plugins: { @@ -633,33 +677,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.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, + ); }); }); }); @@ -710,8 +762,8 @@ function registerAblyModularTests(Helper) { describe('Transports', () => { describe('BaseRealtime', () => { describe('without a transport plugin', () => { - 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.helper.ablyClientOptions({ plugins: { FetchRequest } }))).to.throw( 'no requested transports available', ); }); @@ -722,7 +774,8 @@ function registerAblyModularTests(Helper) { { pluginsKey: 'XHRPolling', transportPlugin: XHRPolling, transportName: 'xhr_polling' }, ]) { describe(`with the ${scenario.pluginsKey} plugin`, () => { - it(`is able to use the ${scenario.transportName} transport`, async () => { + it(`is able to use the ${scenario.transportName} transport`, async function () { + const helper = this.helper; const realtime = new BaseRealtime( helper.ablyClientOptions({ autoConnect: false, @@ -734,22 +787,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, + ); }); }); } @@ -758,7 +815,7 @@ function registerAblyModularTests(Helper) { describe('HTTP request implementations', () => { describe('with multiple HTTP request implementations', () => { - it('prefers XHR', async () => { + it('prefers XHR', async function () { let usedXHR = false; const XHRRequestSpy = class XHRRequestSpy extends XHRRequest { @@ -768,7 +825,9 @@ function registerAblyModularTests(Helper) { } }; - const rest = new BaseRest(helper.ablyClientOptions({ plugins: { FetchRequest, XHRRequest: XHRRequestSpy } })); + const rest = new BaseRest( + this.helper.ablyClientOptions({ plugins: { FetchRequest, XHRRequest: XHRRequestSpy } }), + ); await rest.time(); expect(usedXHR).to.be.true; @@ -779,47 +838,58 @@ function registerAblyModularTests(Helper) { describe('MessageInteractions', () => { describe('BaseRealtime', () => { describe('without MessageInteractions', () => { - 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.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, + ); }); - 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.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, + ); }); }); describe('with MessageInteractions', () => { - 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.helper; const realtime = new BaseRealtime( helper.ablyClientOptions({ plugins: { @@ -830,52 +900,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/simple.test.js b/test/browser/simple.test.js index 6656a5824..aba454245 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; @@ -135,8 +134,9 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { it('simpleInitBase0', function (done) { try { - var timeout, - ably = realtimeConnection(); + var helper = this.helper, + timeout, + ably = realtimeConnection(helper); ably.connection.on('connected', function () { clearTimeout(timeout); @@ -163,61 +163,61 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { var wsTransport = 'web_socket'; if (isTransportAvailable(wsTransport)) { it('wsbase0', function (done) { - connectionWithTransport(done, wsTransport); + connectionWithTransport(done, this.helper, wsTransport); }); /* * Publish and subscribe, json transport */ it('wspublish0', function (done) { - publishWithTransport(done, wsTransport); + publishWithTransport(done, this.helper, wsTransport); }); /* * Check heartbeat */ it('wsheartbeat0', function (done) { - heartbeatWithTransport(done, wsTransport); + heartbeatWithTransport(done, this.helper, wsTransport); }); } var xhrPollingTransport = 'xhr_polling'; if (isTransportAvailable(xhrPollingTransport)) { it('xhrpollingbase0', function (done) { - connectionWithTransport(done, xhrPollingTransport); + connectionWithTransport(done, this.helper, xhrPollingTransport); }); /* * Publish and subscribe, json transport */ it('xhrpollingpublish0', function (done) { - publishWithTransport(done, xhrPollingTransport); + publishWithTransport(done, this.helper, xhrPollingTransport); }); /* * Check heartbeat */ it('xhrpollingheartbeat0', function (done) { - heartbeatWithTransport(done, xhrPollingTransport); + heartbeatWithTransport(done, this.helper, xhrPollingTransport); }); } it('auto_transport_base0', function (done) { - connectionWithTransport(done); + connectionWithTransport(done, this.helper); }); /* * Publish and subscribe */ it('auto_transport_publish0', function (done) { - publishWithTransport(done); + publishWithTransport(done, this.helper); }); /* * Check heartbeat */ it('auto_transport_heartbeat0', function (done) { - heartbeatWithTransport(done); + heartbeatWithTransport(done, this.helper); }); }); }); diff --git a/test/common/modules/shared_helper.js b/test/common/modules/shared_helper.js index e0d0906eb..c0169a79e 100644 --- a/test/common/modules/shared_helper.js +++ b/test/common/modules/shared_helper.js @@ -43,6 +43,22 @@ define([ unroutableAddress = unroutableAddress; flushTestLogs = globals.flushLogs; + constructor(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) { + return new this(`${thisInDescribe.title} (${label})`); + } + displayError(err) { if (typeof err == 'string' || err == null) return err; diff --git a/test/realtime/auth.test.js b/test/realtime/auth.test.js index 902d85276..cafca8245 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); @@ -59,7 +58,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Base token generation case */ it('authbase0', function (done) { - var realtime = helper.AblyRealtime({ queryTime: true }); + var helper = this.helper, + realtime = helper.AblyRealtime({ queryTime: true }); Helper.whenPromiseSettles(realtime.auth.requestToken(), function (err, tokenDetails) { if (err) { helper.closeAndFinish(done, realtime, err); @@ -82,7 +82,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Use authUrl for authentication with JSON TokenDetails response */ it('auth_useAuthUrl_json', function (done) { - var realtime, + var helper = this.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { @@ -107,7 +108,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Use authUrl for authentication with JSON TokenDetails response, with authMethod=POST */ it('auth_useAuthUrl_post_json', function (done) { - var realtime, + var helper = this.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { @@ -132,7 +134,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Use authUrl for authentication with plain text token response */ it('auth_useAuthUrl_plainText', function (done) { - var realtime, + var helper = this.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { @@ -157,7 +160,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Use authCallback for authentication with tokenRequest response */ it('auth_useAuthCallback_tokenRequestResponse', function (done) { - var realtime, + var helper = this.helper, + realtime, rest = helper.AblyRest(); var authCallback = function (tokenParams, callback) { Helper.whenPromiseSettles(rest.auth.createTokenRequest(tokenParams, null), function (err, tokenRequest) { @@ -194,7 +198,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * to the auth callback */ it('auth_useAuthCallback_tokenDetailsResponse', function (done) { - var realtime, + var helper = this.helper, + realtime, rest = helper.AblyRest(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { @@ -231,7 +236,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Use authCallback for authentication with token string response */ it('auth_useAuthCallback_tokenStringResponse', function (done) { - var realtime, + var helper = this.helper, + realtime, rest = helper.AblyRest(); var authCallback = function (tokenParams, callback) { Helper.whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { @@ -269,7 +275,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * take precedence */ it('auth_useAuthUrl_mixed_authParams_qsParams', function (done) { - var realtime, + var helper = this.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.createTokenRequest(null, null), function (err, tokenRequest) { if (err) { @@ -305,7 +312,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * and check that the connection inherits the clientId from the tokenDetails */ it('auth_clientid_inheritance', function (done) { - var rest = helper.AblyRest(), + var helper = this.helper, + rest = helper.AblyRest(), testClientId = 'testClientId'; var authCallback = function (tokenParams, callback) { Helper.whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { @@ -343,7 +351,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * (RSA15a, RSA15c) */ it('auth_clientid_inheritance2', function (done) { - var clientRealtime, + var helper = this.helper, + clientRealtime, testClientId = 'test client id'; var rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { @@ -369,7 +378,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * token string and a different clientId, should succeed (RSA15b) */ it('auth_clientid_inheritance3', function (done) { - var realtime, + var helper = this.helper, + realtime, testClientId = 'test client id'; var rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ clientId: '*' }), function (err, tokenDetails) { @@ -397,7 +407,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * tokenDetails and a clientId, should succeed (RSA15b) */ it('auth_clientid_inheritance4', function (done) { - var realtime, + var helper = this.helper, + realtime, testClientId = 'test client id'; var rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ clientId: '*' }), function (err, tokenDetails) { @@ -425,7 +436,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * and check that the connection inherits the clientId from the connectionDetails */ it('auth_clientid_inheritance5', function (done) { - var clientRealtime, + var helper = this.helper, + clientRealtime, testClientId = 'test client id'; var rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { @@ -450,9 +462,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.helper; + var realtime = helper.AblyRealtime(createRealtimeOptions(helper)); realtime.connection.on(function (stateChange) { if (stateChange.previous !== 'initialized') { try { @@ -481,44 +494,44 @@ 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')); }, - }), + })), ); it( 'authCallback_timeout', - authCallback_failures({ + authCallback_failures(() => ({ authCallback: function () { /* (^._.^)ノ */ }, realtimeRequestTimeout: 100, - }), + })), ); it( 'authCallback_nothing', - authCallback_failures({ + authCallback_failures(() => ({ authCallback: function (tokenParams, callback) { callback(); }, - }), + })), ); it( 'authCallback_malformed', - authCallback_failures({ + authCallback_failures(() => ({ authCallback: function (tokenParams, callback) { callback(null, { horse: 'ebooks' }); }, - }), + })), ); 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++) { @@ -526,62 +539,62 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async } callback(null, token); }, - }), + })), ); it( 'authCallback_empty_string', - authCallback_failures({ + authCallback_failures(() => ({ authCallback: function (tokenParams, callback) { callback(null, ''); }, - }), + })), ); it( 'authUrl_timeout', - authCallback_failures({ - authUrl: helper.unroutableAddress, + authCallback_failures((helper) => ({ + authUrl: this.helper.unroutableAddress, realtimeRequestTimeout: 100, - }), + })), ); it( 'authUrl_404', - authCallback_failures({ + authCallback_failures(() => ({ authUrl: 'http://example.com/404', - }), + })), ); it( 'authUrl_wrong_content_type', - authCallback_failures({ + authCallback_failures(() => ({ authUrl: 'http://example.com/', - }), + })), ); it( 'authUrl_401', - authCallback_failures({ + authCallback_failures(() => ({ authUrl: echoServer + '/respondwith?status=401', - }), + })), ); it( 'authUrl_double_encoded', - authCallback_failures({ + authCallback_failures(() => ({ authUrl: echoServer + '/?type=json&body=' + encodeURIComponent(JSON.stringify(JSON.stringify({ keyName: 'foo.bar' }))), - }), + })), ); /* 403 should cause the connection to go to failed, unlike the others */ it( 'authUrl_403', authCallback_failures( - { + () => ({ authUrl: echoServer + '/respondwith?status=403', - }, + }), true, ), ); /* expectFailed: */ @@ -590,18 +603,19 @@ 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, ), ); it('authUrl_403_previously_active', function (done) { - var realtime, + var helper = this.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { @@ -643,7 +657,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.helper, + clientRealtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ ttl: 5000 }, null), function (err, tokenDetails) { @@ -680,7 +695,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * and all subsequent requests use the time offset */ it('auth_query_time_once', function (done) { - var rest = helper.AblyRest({ queryTime: true }), + var helper = this.helper, + rest = helper.AblyRest({ queryTime: true }), timeRequestCount = 0, originalTime = rest.time; @@ -737,7 +753,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.helper, + realtime, rest = helper.AblyRest(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { @@ -780,7 +797,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.helper, + realtime, rest = helper.AblyRest(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { @@ -822,7 +840,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.helper, + realtime, rest = helper.AblyRest(); var clientId = 'test clientid'; Helper.whenPromiseSettles( @@ -865,7 +884,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.helper, + realtime, rest = helper.AblyRest(); var clientId = 'test clientid'; Helper.whenPromiseSettles( @@ -909,7 +929,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.helper, + realtime, rest = helper.AblyRest(); var firstTime = true; var authCallback = function (tokenParams, callback) { @@ -962,12 +983,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* RSA10j */ it('authorize_updates_stored_details', function (done) { - var realtime = helper.AblyRealtime({ - autoConnect: false, - defaultTokenParams: { version: 1 }, - token: '1', - authUrl: '1', - }); + var helper = this.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'); @@ -993,7 +1015,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Inject a fake AUTH message from realtime, check that we reauth and send our own in reply */ it('mocked_reauth', function (done) { - var rest = helper.AblyRest(), + var helper = this.helper, + rest = helper.AblyRest(), authCallback = function (tokenParams, callback) { // Request a token (should happen twice) Helper.whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { @@ -1032,6 +1055,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * has the requested clientId. */ it('auth_jwt_with_clientid', function (done) { + const helper = this.helper; var currentKey = helper.getTestApp().keys[0]; var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var clientId = 'testJWTClientId'; @@ -1065,6 +1089,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * has the requested clientId. Token will be returned with content-type application/jwt. */ it('auth_jwt_with_clientid_application_jwt', function (done) { + const helper = this.helper; var currentKey = helper.getTestApp().keys[0]; var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret, returnType: 'jwt' }; var clientId = 'testJWTClientId'; @@ -1098,6 +1123,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * to a channel fails. */ it('auth_jwt_with_subscribe_only_capability', function (done) { + const helper = this.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) { @@ -1125,6 +1151,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * to a channel succeeds. */ it('auth_jwt_with_publish_capability', function (done) { + const helper = this.helper; var currentKey = helper.getTestApp().keys[0]; var params = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var authCallback = function (tokenParams, callback) { @@ -1154,6 +1181,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * and receives the expected reason in the state change. */ it('auth_jwt_with_token_that_expires', function (done) { + const helper = this.helper; var currentKey = helper.getTestApp().keys[0]; var params = { keyName: currentKey.keyName, keySecret: currentKey.keySecret, expiresIn: 5 }; var authCallback = function (tokenParams, callback) { @@ -1179,6 +1207,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * without going through a disconnected state. */ it('auth_jwt_with_token_that_renews', function (done) { + const helper = this.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. @@ -1207,6 +1236,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * verify it can make authenticated calls. */ it('init_client_with_simple_jwt_token', function (done) { + const helper = this.helper; var currentKey = helper.getTestApp().keys[0]; var params = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; getJWT(params, function (err, token) { @@ -1229,7 +1259,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* RTN14b */ it('reauth_consistently_expired_token', function (done) { - var realtime, + var helper = this.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken({ ttl: 1 }), function (err, token) { if (err) { @@ -1262,7 +1293,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* 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.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(), function (err, token) { if (err) { @@ -1290,7 +1322,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* RSA4b1 second case */ it('expired_token_autoremove_when_have_servertime', function (done) { - var realtime, + var helper = this.helper, + realtime, rest = helper.AblyRest(); Helper.whenPromiseSettles(rest.auth.requestToken(), function (err, token) { if (err) { @@ -1325,6 +1358,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Check that only the last authorize matters */ it('multiple_concurrent_authorize', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime({ useTokenAuth: true, defaultTokenParams: { capability: { wrong: ['*'] } }, @@ -1372,6 +1406,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async Helper.testOnAllTransports('authorize_immediately_after_init', function (realtimeOpts) { return function (done) { + const helper = this.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 36be703c3..48a6e358c 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); @@ -168,6 +167,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelinit0', function (realtimeOpts) { return function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { @@ -201,6 +201,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattach0', function (realtimeOpts) { return function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { @@ -224,6 +225,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattach2', function (realtimeOpts) { return function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); var channel2 = realtime.channels.get('channelattach2'); @@ -248,6 +250,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async 'channelattach3', function (realtimeOpts) { return function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { @@ -283,6 +286,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattachempty', function (realtimeOpts) { return function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -315,6 +319,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattachinvalid', function (realtimeOpts) { return function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -353,6 +358,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('publish_no_attach', function (realtimeOpts) { return function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -380,6 +386,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattach_publish_invalid', function (realtimeOpts) { return function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -409,6 +416,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('channelattach_invalid_twice', function (realtimeOpts) { return function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -445,6 +453,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Attach then later call whenState which fires immediately */ it('channelattachWhenState', function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(), channel = realtime.channels.get('channelattachWhenState'); @@ -464,6 +473,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Attach and call whenState before attach which fires later */ it('channelattachOnceOrIfBefore', function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(), channel = realtime.channels.get('channelattachOnceOrIf'), @@ -488,6 +498,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async Helper.testOnAllTransports('attachWithChannelParamsBasicChannelsGet', function (realtimeOpts) { return function (done) { + const helper = this.helper; var testName = 'attachWithChannelParamsBasicChannelsGet'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -541,6 +552,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async Helper.testOnAllTransports('attachWithChannelParamsBasicSetOptions', function (realtimeOpts) { return function (done) { + const helper = this.helper; var testName = 'attachWithChannelParamsBasicSetOptions'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -590,6 +602,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async Helper.testOnAllTransports('subscribeAfterSetOptions', function (realtimeOpts) { return function (done) { + const helper = this.helper; var testName = 'subscribeAfterSetOptions'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -619,6 +632,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('channelGetShouldThrowWhenWouldCauseReattach', function (done) { + const helper = this.helper; var testName = 'channelGetShouldThrowWhenWouldCauseReattach'; try { var realtime = helper.AblyRealtime(); @@ -662,6 +676,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async Helper.testOnAllTransports('setOptionsCallbackBehaviour', function (realtimeOpts) { return function (done) { + const helper = this.helper; var testName = 'setOptionsCallbackBehaviour'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -737,6 +752,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Verify modes is ignored when params.modes is present */ Helper.testOnAllTransports('attachWithChannelParamsModesAndChannelModes', function (realtimeOpts) { return function (done) { + const helper = this.helper; var testName = 'attachWithChannelParamsModesAndChannelModes'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -791,6 +807,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async Helper.testOnAllTransports('attachWithChannelModes', function (realtimeOpts) { return function (done) { + const helper = this.helper; var testName = 'attachWithChannelModes'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -840,6 +857,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async Helper.testOnAllTransports('attachWithChannelParamsDeltaAndModes', function (realtimeOpts) { return function (done) { + const helper = this.helper; var testName = 'attachWithChannelParamsDeltaAndModes'; try { var realtime = helper.AblyRealtime(realtimeOpts); @@ -890,6 +908,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('attachWithInvalidChannelParams', function (done) { + const helper = this.helper; var testName = 'attachWithInvalidChannelParams'; var defaultChannelModes = 'presence,publish,subscribe,presence_subscribe'; try { @@ -999,6 +1018,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ it('channelsubscribe0', function (done) { try { + const helper = this.helper; var realtime = helper.AblyRealtime({ useBinaryProtocol: true }); realtime.connection.on('connected', function () { var channel6 = realtime.channels.get('channelsubscribe0'); @@ -1032,6 +1052,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Subscribe, then unsubscribe listeners by event, by listener, and then all events & listener */ it('channelsubscribe1', function (done) { + const helper = this.helper; var messagesReceived = 0; try { @@ -1110,7 +1131,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * immediate reattach. If that fails, it should go into suspended */ it('server_sent_detached', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channelName = 'server_sent_detached', channel = realtime.channels.get(channelName); @@ -1161,7 +1183,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * result in the channel becoming suspended */ it('server_sent_detached_while_attaching', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channelName = 'server_sent_detached_while_attaching', channel = realtime.channels.get(channelName); @@ -1201,7 +1224,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * A server-sent ERROR, with channel field, should fail the channel */ it('server_sent_error', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channelName = 'server_sent_error', channel = realtime.channels.get(channelName); @@ -1238,7 +1262,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * should emit an UPDATE event on the channel */ it('server_sent_attached_err', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.helper, + realtime = helper.AblyRealtime(), channelName = 'server_sent_attached_err', channel = realtime.channels.get(channelName); @@ -1282,7 +1307,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Check that queueMessages: false disables queuing for connection queue state */ it('publish_no_queueing', function (done) { - var realtime = helper.AblyRealtime({ queueMessages: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ queueMessages: false }), channel = realtime.channels.get('publish_no_queueing'); /* try a publish while not yet connected */ @@ -1301,7 +1327,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.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport], realtimeRequestTimeout: 2000, channelRetryTimeout: 100, @@ -1349,7 +1376,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.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport], channelRetryTimeout: 1010, suspendedRetryTimeout: 1100, @@ -1460,6 +1488,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async // RTL5j it('detaching from suspended channel transitions channel to detached state', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); var channelName = 'detach_from_suspended'; var channel = realtime.channels.get(channelName); @@ -1481,6 +1510,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async // RTL5b it('detaching from failed channel results in error', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); var channelName = 'detach_from_failed'; var channel = realtime.channels.get(channelName); @@ -1497,6 +1527,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('rewind works on channel after reattaching', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); var channelName = 'rewind_after_detach'; var channel = realtime.channels.get(channelName); @@ -1524,6 +1555,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('attach_returns_state_change', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime(); var channelName = 'attach_returns_state_chnage'; var channel = realtime.channels.get(channelName); @@ -1560,6 +1592,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('subscribe_returns_state_change', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime(); var channelName = 'subscribe_returns_state_chnage'; var channel = realtime.channels.get(channelName); @@ -1586,6 +1619,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('rewind_has_backlog_0', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime(); var channelName = 'rewind_has_backlog_0'; var channelOpts = { params: { rewind: '1' } }; @@ -1609,6 +1643,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('rewind_has_backlog_1', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime(); var rest = helper.AblyRest(); var channelName = 'rewind_has_backlog_1'; @@ -1640,6 +1675,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('should not throw exception then run RealtimeChannels.get() with same options', function (done) { + const helper = this.helper; const realtime = helper.AblyRealtime(); const channel = realtime.channels.get('channel-with-options', { modes: ['PRESENCE'] }); channel.attach(); @@ -1653,7 +1689,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); }); - it('whenState', async () => { + it('whenState', async function () { + const helper = this.helper; const realtime = helper.AblyRealtime(); await helper.monitorConnectionAsync(async () => { diff --git a/test/realtime/connection.test.js b/test/realtime/connection.test.js index 94567eaab..82831d9eb 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); @@ -19,6 +18,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('connectionPing', function (done) { + const helper = this.helper; var realtime; try { realtime = helper.AblyRealtime(); @@ -37,6 +37,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('connectionPingWithCallback', function (done) { + const helper = this.helper; var realtime; try { realtime = helper.AblyRealtime(); @@ -62,6 +63,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('connectionAttributes', function (done) { + const helper = this.helper; var realtime; try { realtime = helper.AblyRealtime(); @@ -122,6 +124,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('unrecoverableConnection', function (done) { + const helper = this.helper; var realtime; const fakeRecoveryKey = JSON.stringify({ connectionKey: '_____!ablyjs_test_fake-key____', @@ -165,7 +168,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * without being merged with new messages) */ it('connectionQueuing', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channel = realtime.channels.get('connectionQueuing'), connectionManager = realtime.connection.connectionManager; @@ -279,7 +283,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Inject a new CONNECTED with different connectionDetails; check they're used */ it('connectionDetails', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.helper, + realtime = helper.AblyRealtime(), connectionManager = realtime.connection.connectionManager; realtime.connection.once('connected', function () { connectionManager.once('connectiondetails', function (details) { @@ -316,6 +321,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('whenState', async () => { + const helper = this.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 80783ba22..7043ee243 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); @@ -21,6 +20,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { * Connect with available http transports; internet connectivity check should work */ it('http_connectivity_check', function (done) { + const helper = this.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; @@ -47,6 +47,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { var failUrl = echoServer + '/respondwith?status=500'; it('succeeds with scheme', function (done) { + const helper = this.helper; Helper.whenPromiseSettles( helper.AblyRealtime(options(urlScheme + successUrl)).http.checkConnectivity(), function (err, res) { @@ -62,6 +63,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('fails with scheme', function (done) { + const helper = this.helper; Helper.whenPromiseSettles( helper.AblyRealtime(options(urlScheme + failUrl)).http.checkConnectivity(), function (err, res) { @@ -90,6 +92,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('fails with querystring', function (done) { + const helper = this.helper; Helper.whenPromiseSettles(helper.AblyRealtime(options(failUrl)).http.checkConnectivity(), function (err, res) { try { expect(!res, 'Connectivity check expected to return false').to.be.ok; @@ -101,6 +104,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('succeeds with plain url', function (done) { + const helper = this.helper; Helper.whenPromiseSettles( helper.AblyRealtime(options('sandbox-rest.ably.io/time')).http.checkConnectivity(), function (err, res) { @@ -115,6 +119,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('fails with plain url', function (done) { + const helper = this.helper; Helper.whenPromiseSettles( helper.AblyRealtime(options('echo.ably.io')).http.checkConnectivity(), function (err, res) { @@ -130,6 +135,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('disable_connectivity_check', function (done) { + const helper = this.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 fbe3a781f..539b4ecda 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); @@ -211,8 +210,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('encrypt_message_128', function (done) { + const helper = this.helper; testEachFixture( done, + helper, 'crypto-data-128.json', 'encrypt_message_128', 2, @@ -221,15 +222,17 @@ 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); }); }, ); }); it('encrypt_message_256', function (done) { + const helper = this.helper; testEachFixture( done, + helper, 'crypto-data-256.json', 'encrypt_message_256', 2, @@ -238,15 +241,17 @@ 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); }); }, ); }); it('decrypt_message_128', function (done) { + const helper = this.helper; testEachFixture( done, + helper, 'crypto-data-128.json', 'decrypt_message_128', 2, @@ -255,14 +260,16 @@ 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); }, ); }); it('decrypt_message_256', function (done) { + const helper = this.helper; testEachFixture( done, + helper, 'crypto-data-256.json', 'decrypt_message_256', 2, @@ -271,7 +278,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); }, ); }); @@ -282,6 +289,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } + const helper = this.helper; + helper.loadTestData(helper.testResourcesPath + 'crypto-data-256.json', async function (err, testData) { if (err) { done(err); @@ -294,7 +303,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(); }); @@ -303,8 +312,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Tests require encryption and binary transport */ if (typeof ArrayBuffer !== 'undefined') { it('msgpack_128', function (done) { + const helper = this.helper; testEachFixture( done, + helper, 'crypto-data-128.json', 'msgpack_128', 2, @@ -337,8 +348,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('msgpack_256', function (done) { + const helper = this.helper; testEachFixture( done, + helper, 'crypto-data-256.json', 'msgpack_256', 2, @@ -371,7 +384,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; @@ -419,17 +432,17 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('single_send_128', function (realtimeOpts) { return function (done) { - single_send(done, realtimeOpts, 128); + single_send(done, this.helper, realtimeOpts, 128); }; }); Helper.testOnAllTransports('single_send_256', function (realtimeOpts) { return function (done) { - single_send(done, realtimeOpts, 256); + single_send(done, this.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; @@ -486,30 +499,30 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async } it('multiple_send_binary_2_200', function (done) { - _multiple_send(done, false, 2, 200); + _multiple_send(done, this.helper, false, 2, 200); }); it('multiple_send_text_2_200', function (done) { - _multiple_send(done, true, 2, 200); + _multiple_send(done, this.helper, true, 2, 200); }); it('multiple_send_binary_20_100', function (done) { - _multiple_send(done, false, 20, 100); + _multiple_send(done, this.helper, false, 20, 100); }); it('multiple_send_text_20_100', function (done) { - _multiple_send(done, true, 20, 100); + _multiple_send(done, this.helper, true, 20, 100); }); it('multiple_send_binary_10_10', function (done) { - _multiple_send(done, false, 10, 10); + _multiple_send(done, this.helper, false, 10, 10); }); it('multiple_send_text_10_10', function (done) { - _multiple_send(done, true, 10, 10); + _multiple_send(done, this.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; @@ -573,7 +586,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * the default cipher params and verify correct receipt. */ it('single_send_binary_text', function (done) { - _single_send_separate_realtimes(done, { useBinaryProtocol: true }, { useBinaryProtocol: false }); + _single_send_separate_realtimes(done, this.helper, { useBinaryProtocol: true }, { useBinaryProtocol: false }); }); /** @@ -582,7 +595,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * the default cipher params and verify correct receipt. */ it('single_send_text_binary', function (done) { - _single_send_separate_realtimes(done, { useBinaryProtocol: false }, { useBinaryProtocol: true }); + _single_send_separate_realtimes(done, this.helper, { useBinaryProtocol: false }, { useBinaryProtocol: true }); }); it('publish_immediately', function (done) { @@ -591,7 +604,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } - var txRealtime = helper.AblyRealtime(), + var helper = this.helper, + txRealtime = helper.AblyRealtime(), rxRealtime = helper.AblyRealtime(), channelName = 'publish_immediately', messageText = 'Test message'; @@ -632,6 +646,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } + const helper = this.helper; var txRealtime = helper.AblyRealtime(); var rxRealtime = helper.AblyRealtime(); var channelName = 'single_send_key_mismatch', @@ -698,6 +713,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } + const helper = this.helper; var txRealtime = helper.AblyRealtime(); var rxRealtime = helper.AblyRealtime(); var channelName = 'single_send_unencrypted', @@ -741,6 +757,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } + const helper = this.helper; var txRealtime = helper.AblyRealtime(); var rxRealtime = helper.AblyRealtime(); var channelName = 'single_send_encrypted_unhandled', @@ -785,6 +802,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async return; } + const helper = this.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 1ecc6f094..b1d000ca4 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); @@ -39,6 +38,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, v }); it('deltaPlugin', function (done) { + const helper = this.helper; var testName = 'deltaPlugin'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); @@ -89,6 +89,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, v }); it('unusedPlugin', function (done) { + const helper = this.helper; var testName = 'unusedPlugin'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); @@ -129,6 +130,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, v }); it('lastMessageNotFoundRecovery', function (done) { + const helper = this.helper; var testName = 'lastMessageNotFoundRecovery'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); @@ -192,6 +194,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, v }); it('deltaDecodeFailureRecovery', function (done) { + const helper = this.helper; var testName = 'deltaDecodeFailureRecovery'; try { var failingTestVcdiffDecoder = { @@ -244,6 +247,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (Helper, v /* Check that channel becomes failed if we get deltas when we don't have a vcdiff plugin */ it('noPlugin', function (done) { + const helper = this.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 c18760307..84f66e362 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); @@ -28,7 +27,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * realtime, and check everything decodes correctly */ it('message_decoding', function (done) { - helper.loadTestData(encodingFixturesPath(), function (err, testData) { + const helper = this.helper; + helper.loadTestData(encodingFixturesPath(helper), function (err, testData) { if (err) { done(err); return; @@ -129,7 +129,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * manually, and check everything was encoded correctly */ it('message_encoding', function (done) { - helper.loadTestData(encodingFixturesPath(), function (err, testData) { + const helper = this.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 bec7608b9..6b3e4014d 100644 --- a/test/realtime/event_emitter.test.js +++ b/test/realtime/event_emitter.test.js @@ -1,8 +1,6 @@ 'use strict'; define(['shared_helper', 'chai'], function (Helper, chai) { - const helper = new Helper(); - var expect = chai.expect; describe('realtime/event_emitter', function () { @@ -22,6 +20,7 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * channel, detaching, and disconnecting are received once each */ it('attachdetach0', function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(), index, @@ -69,7 +68,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('emitCallsAllCallbacksIgnoringExceptions', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = false, eventEmitter = realtime.connection; @@ -94,7 +94,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('onceCalledOnlyOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), onCallbackCalled = 0, onceCallbackCalled = 0, eventEmitter = realtime.connection; @@ -122,7 +123,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('onceCallbackDoesNotImpactOnCallback', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -148,7 +150,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('offRemovesAllMatchingListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -177,7 +180,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('offRemovesAllListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -206,7 +210,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('offRemovesAllMatchingEventListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -235,7 +240,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('offRemovesAllMatchingEvents', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -271,7 +277,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { * for each previously registered event name */ it('offRemovesEmptyEventNameListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection; var callback = function () {}; @@ -299,7 +306,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('arrayOfEvents', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -338,7 +346,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('arrayOfEventsWithOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -365,7 +374,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /* check that listeners added in a listener cb are not called during that * emit instance */ it('listenerAddedInListenerCb', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection, firstCbCalled = false, secondCbCalled = false; @@ -392,7 +402,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { /* check that listeners removed in a listener cb are still called in that * emit instance (but only once) */ it('listenerRemovedInListenerCb', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection, onCbCalledTimes = 0, onceCbCalledTimes = 0, @@ -436,6 +447,7 @@ define(['shared_helper', 'chai'], function (Helper, chai) { describe('event_emitter_promise', function () { it('whenState', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime(); var eventEmitter = realtime.connection; @@ -450,6 +462,7 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('once', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime(); var eventEmitter = realtime.connection; @@ -464,7 +477,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('anyEventsWithOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection; const p = eventEmitter.once(); @@ -477,7 +491,8 @@ define(['shared_helper', 'chai'], function (Helper, chai) { }); it('arrayOfEventsWithOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.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 d7084a272..f04ccca26 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); @@ -23,6 +22,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Connect with invalid credentials on various transports; connection state should be 'failed' */ it('invalid_cred_failure', function (done) { + const helper = this.helper; try { var failure_test = function (transports) { return function (cb) { @@ -72,6 +72,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * should be 'disconnected' */ it('break_transport', function (done) { + const helper = this.helper; try { var break_test = function (transports) { return function (cb) { @@ -110,6 +111,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * the connecting/disconnecting/suspended cycle works as expected */ it('no_connection_lifecycle', function (done) { + const helper = this.helper; try { var lifecycleTest = function (transports) { return function (cb) { @@ -188,8 +190,9 @@ 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) { it('disconnected_backoff_' + transport, function (done) { + const helper = this.helper; var disconnectedRetryTimeout = 150; var realtime = helper.AblyRealtime({ disconnectedRetryTimeout: disconnectedRetryTimeout, @@ -231,6 +234,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Check operations on a failed channel give the right errors */ it('failed_channel', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime(); var failChan; var channelFailedCode = 90001; @@ -337,7 +341,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('attach_timeout', function (done) { - var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000, channelRetryTimeout: 1000 }), + var helper = this.helper, + realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000, channelRetryTimeout: 1000 }), channel = realtime.channels.get('failed_attach'), originalProcessMessage = channel.processMessage.bind(channel); @@ -370,8 +375,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); }); - helper.availableTransports.forEach(function (transport) { + Helper.forTestDefinition(this, 'channel_backoff_').availableTransports.forEach(function (transport) { it('channel_backoff_' + transport, function (done) { + const helper = this.helper; var channelRetryTimeout = 150; var realtime = helper.AblyRealtime({ channelRetryTimeout: channelRetryTimeout, @@ -440,7 +446,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.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channel = realtime.channels.get('nack_on_connection_failure'); async.series( @@ -477,7 +484,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async } }); Ably.Realtime.Platform.Config.nextTick(function () { - failureFn(realtime); + failureFn(realtime, helper); }); }, ], @@ -491,7 +498,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', @@ -525,7 +532,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async ); it('idle_transport_timeout', function (done) { - var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000 }), + var helper = this.helper, + realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000 }), originalOnProtocolMessage; realtime.connection.connectionManager.on('transport.pending', function (transport) { @@ -563,7 +571,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.helper, + realtime = helper.AblyRealtime(helper.Utils.mixin({ fallbackHosts: ['echo.ably.io'] }, realtimeOpts)), connection = realtime.connection, connectionManager = connection.connectionManager; @@ -598,6 +607,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async // RTL 17 it('no_messages_if_not_attached', function (done) { + const helper = this.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 c5f6c1935..fb97ad44f 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); @@ -46,6 +45,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { }); it('history_until_attach', function (done) { + const helper = this.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 9d06ead16..b655a88ab 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,35 +18,39 @@ 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 - */ - 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 + */ + it('initbase0', function (done) { + const helper = this.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 */ it('init_key_string', function (done) { + const helper = this.helper; var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; @@ -68,6 +71,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* init with token string */ it('init_token_string', function (done) { + const helper = this.helper; try { /* first generate a token ... */ var rest = helper.AblyRest(); @@ -97,6 +101,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* init with key string and useTokenAuth: true */ it('init_key_with_usetokenauth', function (done) { + const helper = this.helper; var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; @@ -122,6 +127,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* init with key string, useTokenAuth: true, and some defaultTokenParams to * request a wildcard clientId */ it('init_usetokenauth_defaulttokenparams_wildcard', function (done) { + const helper = this.helper; var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; @@ -150,6 +156,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* init with using defaultTokenParams to set a non-wildcard clientId should set auth.clientId */ it('init_defaulttokenparams_nonwildcard', function (done) { + const helper = this.helper; var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; @@ -176,6 +183,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* init when specifying clientId both in defaultTokenParams and in clientOptions: the latter takes precedence */ it('init_conflicting_clientids', function (done) { + const helper = this.helper; var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; @@ -202,6 +210,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* init with useTokenAuth: false with a clientId (should fail) */ it('init_with_usetokenauth_false_and_a_clientid', function (done) { + const helper = this.helper; try { var keyStr = helper.getTestApp().keys[0].keyStr; expect(function () { @@ -215,6 +224,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* check default httpHost selection */ it('init_defaulthost', function (done) { + const helper = this.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 @@ -231,6 +241,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* check changing the default timeouts */ it('init_timeouts', function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime({ key: 'not_a.real:key', @@ -269,6 +280,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* check changing the default fallback hosts and changing httpMaxRetryCount */ it('init_fallbacks', function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime({ key: 'not_a.real:key', @@ -316,6 +328,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* Check base and websocket transports (nodejs only; browser tests in their own section) */ if (!isBrowser) { it('node_transports', function (done) { + const helper = this.helper; var realtime; try { realtime = helper.AblyRealtime({ transports: helper.availableTransports }); @@ -331,6 +344,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { /* Check that the connectionKey in ConnectionDetails updates the client connectionKey, and clientId in ConnectionDetails updates the client clientId */ it('init_and_connection_details', function (done) { + const helper = this.helper; try { var keyStr = helper.getTestApp().keys[0].keyStr; var realtime = helper.AblyRealtime({ key: keyStr, useTokenAuth: true }); @@ -372,6 +386,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('init_fallbacks_once_connected', function (done) { + const helper = this.helper; var realtime = helper.AblyRealtime({ httpMaxRetryCount: 3, fallbackHosts: ['a', 'b', 'c'], @@ -393,6 +408,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('init_fallbacks_once_connected_2', function (done) { + const helper = this.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 00fe3b8f6..2a0bb6c3b 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); @@ -33,6 +32,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('publishonce', function (done) { + const helper = this.helper; try { /* set up realtime */ var realtime = helper.AblyRealtime(); @@ -75,6 +75,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async */ Helper.testOnAllTransports('publishfast', function (realtimeOpts) { return function (done) { + const helper = this.helper; try { var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { @@ -138,7 +139,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.helper, + txRealtime, + rxRealtime; try { txRealtime = helper.AblyRealtime(helper.Utils.mixin(realtimeOpts, { autoConnect: false })); rxRealtime = helper.AblyRealtime(); @@ -228,7 +231,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.helper, + rtNoEcho = helper.AblyRealtime({ echoMessages: false }), rtEcho = helper.AblyRealtime({ echoMessages: true }), rtNoEchoChannel = rtNoEcho.channels.get('publishecho'), rtEchoChannel = rtEcho.channels.get('publishecho'), @@ -297,6 +301,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('publishVariations', function (done) { + const helper = this.helper; var testData = 'Some data'; var testArguments = [ [{ name: 'objectWithName' }], @@ -413,6 +418,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('publishDisallowed', function (done) { + const helper = this.helper; var testArguments = [ [{ name: 'objectAndBoolData', data: false }], ['nameAndBoolData', false], @@ -464,6 +470,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('publishEncodings', function (done) { + const helper = this.helper; var testData = 'testData'; var testArguments = [ // valid @@ -559,6 +566,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('restpublish', function (done) { + const helper = this.helper; var count = 10; var rest = helper.AblyRest(); var realtime = helper.AblyRealtime(); @@ -588,6 +596,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async Helper.testOnAllTransports('publish', function (realtimeOpts) { return function (done) { + const helper = this.helper; var count = 10; var cbCount = 10; var checkFinish = function () { @@ -620,7 +629,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Authenticate with a clientId and ensure that the clientId is not sent in the Message and is implicitly added when published */ it('implicit_client_id_0', function (done) { - var clientId = 'implicit_client_id_0', + var helper = this.helper, + clientId = 'implicit_client_id_0', realtime = helper.AblyRealtime({ clientId: clientId }); realtime.connection.once('connected', function () { @@ -658,7 +668,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Authenticate with a clientId and explicitly provide the same clientId in the Message and ensure it is published */ it('explicit_client_id_0', function (done) { - var clientId = 'explicit_client_id_0', + var helper = this.helper, + clientId = 'explicit_client_id_0', /* Use a fixed transport as intercepting transport.send */ realtime = helper.AblyRealtime({ clientId: clientId, transports: [helper.bestTransport] }); @@ -720,7 +731,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Authenticate with a clientId and explicitly provide a different invalid clientId in the Message and expect it to not be published and be rejected */ it('explicit_client_id_1', function (done) { - var clientId = 'explicit_client_id_1', + var helper = this.helper, + clientId = 'explicit_client_id_1', invalidClientId = 'invalid', rest = helper.AblyRest(); @@ -777,7 +789,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('subscribe_with_event_array', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.helper, + realtime = helper.AblyRealtime(), channel = realtime.channels.get('subscribe_with_event_array'); async.series( @@ -833,6 +846,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('subscribe_with_filter_object', function (done) { + const helper = this.helper; const realtime = helper.AblyRealtime(); const channel = realtime.channels.get('subscribe_with_filter_object'); @@ -913,6 +927,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('unsubscribe_with_filter_object', function (done) { + const helper = this.helper; const realtime = helper.AblyRealtime(); const channel = realtime.channels.get('unsubscribe_with_filter_object'); @@ -971,7 +986,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('extras_field', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.helper, + realtime = helper.AblyRealtime(), channel = realtime.channels.get('extras_field'), extras = { headers: { some: 'metadata' } }; @@ -1016,7 +1032,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* TO3l8; CD2C; RSL1i */ it('maxMessageSize', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.helper, + realtime = helper.AblyRealtime(), connectionManager = realtime.connection.connectionManager, channel = realtime.channels.get('maxMessageSize'); @@ -1050,7 +1067,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* RTL6d: publish a series of messages that exercise various bundling * constraints, check they're satisfied */ it.skip('bundling', function (done) { - var realtime = helper.AblyRealtime({ maxMessageSize: 256, autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ maxMessageSize: 256, autoConnect: false }), channelOne = realtime.channels.get('bundlingOne'), channelTwo = realtime.channels.get('bundlingTwo'); @@ -1112,7 +1130,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('idempotentRealtimePublishing', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.helper, + realtime = helper.AblyRealtime(), channel = realtime.channels.get('idempotentRealtimePublishing'); Helper.whenPromiseSettles(channel.attach(), function (err) { @@ -1146,6 +1165,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('subscribes to filtered channel', function (done) { + const helper = this.helper; + var testData = [ { name: 'filtered', diff --git a/test/realtime/presence.test.js b/test/realtime/presence.test.js index e649901a1..21a568539 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); @@ -142,6 +141,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Attach to channel, enter presence channel with data and await entered event */ it.skip('presenceAttachAndEnter', function (done) { + const helper = this.helper; var channelName = 'attachAndEnter'; var attachAndEnter = function (cb) { /* set up authenticated connection */ @@ -162,13 +162,14 @@ 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); }); /* * Enter presence channel without prior attach and await entered event */ it('presenceEnterWithoutAttach', function (done) { + const helper = this.helper; var channelName = 'enterWithoutAttach'; var enterWithoutAttach = function (cb) { var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -185,13 +186,14 @@ 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); }); /* * Enter presence channel without prior connect and await entered event */ it('presenceEnterWithoutConnect', function (done) { + const helper = this.helper; var channelName = 'enterWithoutConnect'; var enterWithoutConnect = function (cb) { var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -205,7 +207,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); }); /* @@ -213,6 +215,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * from channel immediately in 'attached' callback */ it.skip('presenceEnterDetachRace', function (done) { + const helper = this.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 @@ -221,7 +224,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; @@ -276,6 +279,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Attach to channel, enter presence channel with a callback but no data and await entered event */ it('presenceEnterWithCallback', function (done) { + const helper = this.helper; var channelName = 'enterWithCallback'; var enterWithCallback = function (cb) { /* set up authenticated connection */ @@ -296,13 +300,14 @@ 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); }); /* * Attach to channel, enter presence channel with neither callback nor data and await entered event */ it('presenceEnterWithNothing', function (done) { + const helper = this.helper; var channelName = 'enterWithNothing'; var enterWithNothing = function (cb) { var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -321,13 +326,14 @@ 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); }); /* * Attach to channel, enter presence channel with data but no callback and await entered event */ it('presenceEnterWithData', function (done) { + const helper = this.helper; var channelName = 'enterWithData'; var enterWithData = function (cb) { var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -346,7 +352,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); }); /* @@ -354,6 +360,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * has valid action string */ it('presenceMessageAction', function (done) { + const helper = this.helper; var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var channelName = 'presenceMessageAction'; var clientChannel = clientRealtime.channels.get(channelName); @@ -384,6 +391,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * PresenceMessage has extras. Then do the same for leaving presence. */ it('presenceMessageExtras', function (done) { + const helper = this.helper; var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var channelName = 'presenceEnterWithExtras'; var clientChannel = clientRealtime.channels.get(channelName); @@ -451,6 +459,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Enter presence channel (without attaching), detach, then enter again to reattach */ it('presenceEnterDetachEnter', function (done) { + const helper = this.helper; var channelName = 'enterDetachEnter'; var secondEventListener = function (channel, callback) { var presenceHandler = function (presenceMsg) { @@ -488,13 +497,14 @@ 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); }); /* * Enter invalid presence channel (without attaching), check callback was called with error */ it('presenceEnterInvalid', function (done) { + const helper = this.helper; var clientRealtime; try { clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -524,6 +534,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Attach to channel, enter+leave presence channel and await leave event */ it('presenceEnterAndLeave', function (done) { + const helper = this.helper; var channelName = 'enterAndLeave'; var enterAndLeave = function (cb) { var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -549,13 +560,14 @@ 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); }); /* * Attach to channel, enter presence channel, update data, and await update event */ it('presenceEnterUpdate', function (done) { + const helper = this.helper; var newData = 'New data'; var channelName = 'enterUpdate'; var eventListener = function (channel, callback) { @@ -597,13 +609,14 @@ 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); }); /* * Attach to channel, enter presence channel and get presence */ it('presenceEnterGet', function (done) { + const helper = this.helper; var channelName = 'enterGet'; var testData = 'some data for presenceEnterGet'; var eventListener = function (channel, callback) { @@ -645,13 +658,14 @@ 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); }); /* * Realtime presence subscribe on an unattached channel should implicitly attach */ it('presenceSubscribeUnattached', function (done) { + const helper = this.helper; var channelName = 'subscribeUnattached'; var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var clientRealtime2; @@ -680,6 +694,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Realtime presence GET on an unattached channel should attach and wait for sync */ it('presenceGetUnattached', function (done) { + const helper = this.helper; var channelName = 'getUnattached'; var testData = 'some data'; var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); @@ -721,6 +736,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Attach to channel, enter+leave presence channel and get presence */ it('presenceEnterLeaveGet', function (done) { + const helper = this.helper; var channelName = 'enterLeaveGet'; var eventListener = function (channel, callback) { var presenceHandler = function () { @@ -768,13 +784,14 @@ 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); }); /* * Attach to channel, enter+leave presence, detatch again, and get presence history */ it('presenceHistory', function (done) { + const helper = this.helper; var clientRealtime; var channelName = 'history'; var testClientData = 'Test client data (history0)'; @@ -847,6 +864,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * connection, seeing existing member in message subsequent to second attach response */ it('presenceSecondConnection', function (done) { + const helper = this.helper; var clientRealtime1, clientRealtime2; var channelName = 'secondConnection'; try { @@ -927,6 +945,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Use get to filter by clientId and connectionId */ it('presenceTwoMembers', function (done) { + const helper = this.helper; var clientRealtime1, clientRealtime2, clientChannel1, clientChannel2; var channelName = 'twoMembers'; try { @@ -1093,6 +1112,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * reconnect, then enter again to reattach */ it('presenceEnterAfterClose', function (done) { + const helper = this.helper; var channelName = 'enterAfterClose'; var secondEnterListener = function (channel, callback) { var presenceHandler = function (presenceMsg) { @@ -1128,13 +1148,14 @@ 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); }); /* * Try to enter presence channel on a closed connection and check error callback */ it('presenceEnterClosed', function (done) { + const helper = this.helper; var clientRealtime; var channelName = 'enterClosed'; try { @@ -1163,7 +1184,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Client ID is implicit in the connection so should not be sent for current client operations */ it('presenceClientIdIsImplicit', function (done) { - var clientId = 'implicitClient', + var helper = this.helper, + clientId = 'implicitClient', client = helper.AblyRealtime({ clientId: clientId }); var channel = client.channels.get('presenceClientIdIsImplicit'), @@ -1205,7 +1227,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Check that encodable presence messages are encoded correctly */ it('presenceEncoding', function (done) { - var data = { foo: 'bar' }, + var helper = this.helper, + data = { foo: 'bar' }, encodedData = JSON.stringify(data), options = { clientId: testClientId, @@ -1268,6 +1291,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * and check that can enter presence with the clientId inherited from tokenDetails */ it('presence_enter_inherited_clientid', function (done) { + const helper = this.helper; var channelName = 'enter_inherited_clientid'; var authCallback = function (tokenParams, callback) { @@ -1297,7 +1321,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); }); /* @@ -1306,6 +1330,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * before we're connected, so before we know our clientId */ it('presence_enter_before_know_clientid', function (done) { + const helper = this.helper; var channelName = 'enter_before_know_clientid'; var enterInheritedClientId = function (cb) { @@ -1336,7 +1361,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); }); /* @@ -1344,6 +1369,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * all members are emitted and map is in the correct state */ it('presence_refresh_on_detach', function (done) { + const helper = this.helper; var channelName = 'presence_refresh_on_detach'; var realtime = helper.AblyRealtime(); var observer = helper.AblyRealtime(); @@ -1458,6 +1484,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('presence_detach_during_sync', function (done) { + const helper = this.helper; var channelName = 'presence_detach_during_sync'; var enterer = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var detacher = helper.AblyRealtime(); @@ -1514,6 +1541,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * member to be sent to realtime and, with luck, make its way into the normal * presence set */ it('presence_auto_reenter', function (done) { + const helper = this.helper; var channelName = 'presence_auto_reenter'; var realtime = helper.AblyRealtime(); var channel = realtime.channels.get(channelName); @@ -1623,7 +1651,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* RTP17e * Test failed presence auto-re-entering */ it.skip('presence_failed_auto_reenter', function (done) { - var channelName = 'presence_failed_auto_reenter', + var helper = this.helper, + channelName = 'presence_failed_auto_reenter', realtime, channel, token; @@ -1718,7 +1747,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Enter ten clients while attaching, finish the attach, check they were all entered correctly */ it('multiple_pending', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.helper, + realtime = helper.AblyRealtime(), channel = realtime.channels.get('multiple_pending'), originalAttachImpl = channel.attachImpl; @@ -1770,7 +1800,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Check that a LEAVE message is published for anyone in the local presence * set but missing from a sync */ it('leave_published_for_member_missing_from_sync', function (done) { - var realtime = helper.AblyRealtime({ transports: helper.availableTransports }), + var helper = this.helper, + realtime = helper.AblyRealtime({ transports: helper.availableTransports }), continuousClientId = 'continuous', goneClientId = 'gone', continuousRealtime = helper.AblyRealtime({ clientId: continuousClientId }), @@ -1885,7 +1916,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Check that a LEAVE message is published for anyone in the local presence * set if get an ATTACHED with no HAS_PRESENCE */ it('leave_published_for_members_on_presenceless_attached', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.helper, + realtime = helper.AblyRealtime(), channelName = 'leave_published_for_members_on_presenceless_attached', channel = realtime.channels.get(channelName), fakeClientId = 'faker'; @@ -1977,7 +2009,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * and only members that changed between ATTACHED states should result in * presence events */ it('suspended_preserves_presence', function (done) { - var mainRealtime = helper.AblyRealtime({ clientId: 'main' }), + var helper = this.helper, + mainRealtime = helper.AblyRealtime({ clientId: 'main' }), continuousRealtime = helper.AblyRealtime({ clientId: 'continuous' }), leavesRealtime = helper.AblyRealtime({ clientId: 'leaves' }), channelName = 'suspended_preserves_presence', @@ -2115,6 +2148,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * comparisons. */ it('presence_many_updates', function (done) { + const helper = this.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 4feb9fa6f..82a19ad6a 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 })); @@ -42,7 +41,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { } function connectWithToken() { - return function (state, callback) { + return function (helper, state, callback) { var realtime = helper.AblyRealtime(helper.Utils.mixin({ token: state.token }, state.realtimeOpts)); realtime.connection.once('connected', function () { callback(null, helper.Utils.mixin(state, { realtime: realtime })); @@ -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.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) { ****************/ /* RTC8a1 */ - testCase('reauthCapabilityUpgradeNewChannel', [ - getToken({ clientId: clientId, capability: { wrongchannel: ['*'] } }), - connectWithToken(), - monitorConnectionContinuity(), + testCase('reauthCapabilityUpgradeNewChannel', (helper) => [ + helper.getToken({ clientId: clientId, capability: { wrongchannel: ['*'] } }), + connectWithToken(helper), + monitorConnectionContinuity(helper), checkCantAttach('rightchannel'), - getToken({ clientId: clientId, capability: { wrongchannel: ['*'], rightchannel: ['*'] } }), + helper.getToken({ clientId: clientId, capability: { wrongchannel: ['*'], rightchannel: ['*'] } }), reauthWithToken(), attach('rightchannel'), close(), ]); /* RTC8a1 */ - testCase('reauthCapabilityDowngradeFullChannel', [ - getToken({ clientId: clientId, capability: { channel: ['*'], another: ['*'] } }), - connectWithToken(), - monitorConnectionContinuity(), + testCase('reauthCapabilityDowngradeFullChannel', (helper) => [ + helper.getToken({ clientId: clientId, capability: { channel: ['*'], another: ['*'] } }), + connectWithToken(helper), + monitorConnectionContinuity(helper), attach('channel'), - getToken({ clientId: clientId, capability: { another: ['*'] } }), + helper.getToken({ clientId: clientId, capability: { another: ['*'] } }), reauthWithToken(), waitChannelState('channel', 'failed'), checkChannelErrorCode('channel', 40160), @@ -228,26 +228,26 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { close(), ]); - testCase('reauthCapabilityUpgradeAddPublish', [ - getToken({ clientId: clientId, capability: { channel: ['subscribe'] } }), - connectWithToken(), - monitorConnectionContinuity(), + testCase('reauthCapabilityUpgradeAddPublish', (helper) => [ + helper.getToken({ clientId: clientId, capability: { channel: ['subscribe'] } }), + connectWithToken(helper), + monitorConnectionContinuity(helper), attach('channel'), checkCantPublish('channel'), - getToken({ clientId: clientId, capability: { channel: ['subscribe', 'publish'] } }), + helper.getToken({ clientId: clientId, capability: { channel: ['subscribe', 'publish'] } }), reauthWithToken(), checkAttached('channel'), checkCanPublish('channel'), close(), ]); - testCase('reauthCapabilityDowngradePublish', [ - getToken({ clientId: clientId, capability: { channel: ['subscribe', 'publish'] } }), - connectWithToken(), - monitorConnectionContinuity(), + testCase('reauthCapabilityDowngradePublish', (helper) => [ + helper.getToken({ clientId: clientId, capability: { channel: ['subscribe', 'publish'] } }), + connectWithToken(helper), + monitorConnectionContinuity(helper), attach('channel'), checkCanPublish('channel'), - getToken({ clientId: clientId, capability: { channel: ['subscribe'] } }), + helper.getToken({ 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 76f5cf577..950a4edb1 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)); @@ -137,7 +136,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.helper, 'resume_inactive' + String(Math.random()), {}, realtimeOpts); }; }); @@ -145,7 +144,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)); @@ -257,7 +256,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.helper, 'resume_active' + String(Math.random()), {}, realtimeOpts); }; }); @@ -268,7 +267,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.helper, + realtime = helper.AblyRealtime(realtimeOpts), connection = realtime.connection, attachedChannelName = 'resume_lost_continuity_attached', suspendedChannelName = 'resume_lost_continuity_suspended', @@ -334,7 +334,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.helper, + realtime = helper.AblyRealtime(mixin(realtimeOpts, { useTokenAuth: true })), badtoken, connection = realtime.connection; @@ -387,7 +388,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.helper, + realtime = helper.AblyRealtime(realtimeOpts), connection = realtime.connection; async.series( @@ -437,7 +439,8 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * TODO: enable once realtime supports this */ it('channel_resumed_flag', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var helper = this.helper, + realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), realtimeTwo, recoveryKey, connection = realtime.connection, @@ -501,7 +504,8 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * Check the library doesn't try to resume once the connectionStateTtl has expired */ it('no_resume_once_suspended', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.helper, + realtime = helper.AblyRealtime(), connection = realtime.connection, channelName = 'no_resume_once_suspended'; @@ -539,7 +543,8 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { * connection was > connectionStateTtl ago */ it('no_resume_last_activity', function (done) { - var realtime = helper.AblyRealtime(), + var helper = this.helper, + realtime = helper.AblyRealtime(), connection = realtime.connection, connectionManager = connection.connectionManager; @@ -562,6 +567,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { }); it('resume_rewind_1', function (done) { + const helper = this.helper; var testName = 'resume_rewind_1'; var testMessage = { foo: 'bar', count: 1, status: 'active' }; try { @@ -619,6 +625,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { // Tests recovering multiple channels only receives the expected messages. it('recover multiple channels', function (done) { + const helper = this.helper; const NUM_MSGS = 5; const txRest = helper.AblyRest(); diff --git a/test/realtime/sync.test.js b/test/realtime/sync.test.js index fc3a4571d..416d28a07 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); @@ -41,7 +40,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * different presence set */ it('sync_existing_set', async function () { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'syncexistingset', channel = realtime.channels.get(channelName); @@ -161,7 +161,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * middle of the sync should should discard the former, but not the latter * */ it('sync_member_arrives_in_middle', async function () { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_member_arrives_in_middle', channel = realtime.channels.get(channelName); @@ -263,7 +264,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Presence message that was in the sync arrives again as a normal message, after it's come in the sync */ it('sync_member_arrives_normally_after_came_in_sync', async function () { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_member_arrives_normally_after_came_in_sync', channel = realtime.channels.get(channelName); @@ -346,7 +348,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * Presence message that will be in the sync arrives as a normal message, before it comes in the sync */ it('sync_member_arrives_normally_before_comes_in_sync', async function () { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_member_arrives_normally_before_comes_in_sync', channel = realtime.channels.get(channelName); @@ -430,7 +433,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * index, and synthesized leaves, check that the end result is correct */ it('presence_ordering', async function () { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var helper = this.helper, + realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_ordering', channel = realtime.channels.get(channelName); @@ -584,6 +588,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async * presence enter between the syncs. Check everything was entered correctly */ it('presence_sync_interruptus', function (done) { + const helper = this.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 1e9ed3322..ae364e68c 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; - const baseTransport = (() => { + const baseTransport = ((helper) => { var memoized; return () => { @@ -52,6 +50,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); @@ -64,9 +63,9 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai afterEach(restoreWsConnectivityUrl); afterEach(restoreWebSocketConstructor); - if (helper.availableTransports.length > 1) { + if (Helper.forTestDefinition(this).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, @@ -76,7 +75,8 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai } it('websocket_is_default', function (done) { - const realtime = helper.AblyRealtime(options()); + const helper = this.helper; + const realtime = helper.AblyRealtime(options(helper)); realtime.connection.on('connected', function () { try { @@ -91,16 +91,21 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai }); it('no_ws_connectivity', function (done) { + const helper = this.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) { @@ -113,9 +118,10 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai }); it('ws_primary_host_fails', function (done) { + const helper = this.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 () { @@ -127,8 +133,11 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai }); it('no_internet_connectivity', function (done) { + const helper = this.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 () { @@ -137,6 +146,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai }); it('no_websocket_or_base_transport', function (done) { + const helper = this.helper; Config.WebSocket = FakeWebSocket; const realtime = helper.AblyRealtime({ transports: ['web_socket'], @@ -151,8 +161,9 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai if (localStorageSupported) { it('base_transport_preference', function (done) { - window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: baseTransport() })); - const realtime = helper.AblyRealtime(options()); + const helper = this.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; @@ -168,7 +179,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); @@ -179,8 +190,9 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai }); it('transport_preference_reset_while_connecting', function (done) { - window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: baseTransport() })); - const realtime = helper.AblyRealtime(options()); + const helper = this.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 () { @@ -203,8 +215,9 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (Helper, async, chai }); it('transport_preference_reset_after_connected', function (done) { - window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: baseTransport() })); - const realtime = helper.AblyRealtime(options()); + const helper = this.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 () { @@ -212,7 +225,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 00c4fe431..a32c266f0 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; // RTB1 describe('incremental backoff and jitter', function () { it('should calculate retry timeouts using incremental backoff and jitter', function () { + const helper = this.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 8be261151..cbe7fe654 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 @@ -45,6 +44,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as }); it('Generate token and init library with it', async function () { + const helper = this.helper; var tokenDetails = await rest.auth.requestToken(); expect(tokenDetails.token, 'Verify token value').to.be.ok; helper.AblyRest({ token: tokenDetails.token }); @@ -120,6 +120,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as }); it('Token generation with specified key', async function () { + const helper = this.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); @@ -131,6 +132,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as }); it('Token generation with explicit auth', async function () { + const helper = this.helper; const authHeaders = await rest.auth.getAuthHeaders(); rest.auth.authOptions.requestHeaders = authHeaders; var tokenDetails = await rest.auth.requestToken(); @@ -142,6 +144,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as }); it('Token generation with explicit auth, different key', async function () { + const helper = this.helper; const authHeaders = await rest.auth.getAuthHeaders(); var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; var testCapability = JSON.parse(helper.getTestApp().keys[1].capability); @@ -164,6 +167,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as }); it('Token generation with defaultTokenParams set and no tokenParams passed in', async function () { + const helper = this.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; @@ -172,6 +176,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as }); it('Token generation: if tokenParams passed in, defaultTokenParams should be ignored altogether, not merged', async function () { + const helper = this.helper; var rest1 = helper.AblyRest({ defaultTokenParams: { ttl: 123, clientId: 'foo' } }); var tokenDetails = await rest1.auth.requestToken({ clientId: 'bar' }, null); expect(tokenDetails.clientId).to.equal( @@ -240,6 +245,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * doesn't include ttl or capability by default */ it('createTokenRequest without authOptions', async function () { + const helper = this.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; @@ -250,6 +256,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as }); it('createTokenRequest uses the key it was initialized with if authOptions does not have a "key" key', async function () { + const helper = this.helper; var tokenRequest = await rest.auth.createTokenRequest(); expect(tokenRequest.keyName).to.equal(helper.getTestApp().keys[0].keyName); }); @@ -270,6 +277,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as */ function testJWTAuthParams(description, params) { it(description, async function () { + const helper = this.helper; var currentKey = helper.getTestApp().keys[0]; var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var authParams = helper.Utils.mixin(keys, params); @@ -298,6 +306,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as } it('JWT request with invalid key', async function () { + const helper = this.helper; var keys = { keyName: 'invalid.invalid', keySecret: 'invalidinvalid' }; var authUrl = echoServer + '/createJWT' + helper.Utils.toQueryString(keys); var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); @@ -318,6 +327,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * RSA8g */ it('Rest JWT with authCallback', async function () { + const helper = this.helper; var currentKey = helper.getTestApp().keys[0]; var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var authUrl = echoServer + '/createJWT' + helper.Utils.toQueryString(keys); @@ -337,6 +347,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as * RSA8g */ it('Rest JWT with authCallback and invalid keys', async function () { + const helper = this.helper; var keys = { keyName: 'invalid.invalid', keySecret: 'invalidinvalid' }; var authUrl = echoServer + '/createJWT' + helper.Utils.toQueryString(keys); var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); @@ -359,6 +370,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, Helper, as }); it('authCallback is only invoked once on concurrent auth', async function () { + const helper = this.helper; var authCallbackInvocations = 0; function authCallback(tokenParams, callback) { authCallbackInvocations++; diff --git a/test/rest/batch.test.js b/test/rest/batch.test.js index 9bf31dbe1..bf57b1296 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); @@ -19,6 +18,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { describe('when invoked with an array of specs', function () { it('performs a batch publish and returns an array of results', async function () { + const helper = this.helper; const testApp = helper.getTestApp(); const rest = helper.AblyRest({ promises: true, @@ -95,6 +95,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { describe('when invoked with a single spec', function () { it('performs a batch publish and returns a single result', async function () { + const helper = this.helper; const testApp = helper.getTestApp(); const rest = helper.AblyRest({ promises: true, @@ -140,6 +141,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); @@ -149,6 +151,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('performs a batch presence fetch and returns a result', async function () { + const helper = this.helper; const testApp = helper.getTestApp(); const rest = helper.AblyRest({ promises: true, @@ -201,6 +204,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); @@ -210,6 +214,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('revokes tokens matching the given specifiers', async function () { + const helper = this.helper; const testApp = helper.getTestApp(); const rest = helper.AblyRest({ promises: true, @@ -297,6 +302,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('accepts optional issuedBefore and allowReauthMargin parameters', async function () { + const helper = this.helper; const testApp = helper.getTestApp(); const rest = helper.AblyRest({ promises: true, @@ -321,6 +327,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('throws an error when using token auth', async function () { + const helper = this.helper; const rest = helper.AblyRest({ useTokenAuth: true, }); diff --git a/test/rest/capability.test.js b/test/rest/capability.test.js index fac2b1de2..5286f9753 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 633edbe49..bac64944f 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) { /* RSC15f */ it('Store working fallback', async function () { + const helper = this.helper; var rest = helper.AblyRest({ restHost: helper.unroutableHost, fallbackHosts: [goodHost], @@ -56,6 +56,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { // TO3l6 describe('Max elapsed time for host retries', function () { it('can timeout after default host', async function () { + const helper = this.helper; const httpRequestTimeout = 1000; // set httpMaxRetryDuration lower than httpRequestTimeout so it would timeout after default host attempt const httpMaxRetryDuration = Math.floor(httpRequestTimeout / 2); @@ -81,6 +82,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { }); it('can timeout after fallback host retries', async function () { + const helper = this.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 1155ca632..bc3b6d442 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(); @@ -28,6 +27,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { }); Helper.restTestOnJsonMsgpack('history_simple', async function (rest, channelName) { + const helper = this.helper; var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ @@ -54,6 +54,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { }); Helper.restTestOnJsonMsgpack('history_multiple', async function (rest, channelName) { + const helper = this.helper; var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ @@ -77,6 +78,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { }); Helper.restTestOnJsonMsgpack('history_simple_paginated_b', async function (rest, channelName) { + const helper = this.helper; var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ @@ -115,6 +117,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { }); it('history_simple_paginated_f', async function () { + const helper = this.helper; var testchannel = rest.channels.get('persisted:history_simple_paginated_f'); /* first, send a number of events to this channel */ @@ -188,6 +191,7 @@ define(['shared_helper', 'async', 'chai'], function (Helper, async, chai) { }); it('history_multiple_paginated_f', async function () { + const helper = this.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 32d8e7328..eb1da43be 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 7a0afbb1e..db0af97b4 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); @@ -19,6 +18,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('Init with key string', function () { + const helper = this.helper; var keyStr = helper.getTestApp().keys[0].keyStr; var rest = new helper.Ably.Rest(keyStr); @@ -26,6 +26,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('Init with token string', async function () { + const helper = this.helper; /* first generate a token ... */ var rest = helper.AblyRest(); var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; @@ -38,22 +39,26 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, Helper, chai) { }); it('Init with tls: false', function () { + const helper = this.helper; var rest = helper.AblyRest({ tls: false, port: 123, tlsPort: 456 }); expect(rest.baseUri('example.com')).to.equal('http://example.com:123'); }); it('Init with tls: true', function () { + const helper = this.helper; var rest = helper.AblyRest({ tls: true, port: 123, tlsPort: 456 }); expect(rest.baseUri('example.com')).to.equal('https://example.com:456'); }); /* init without any tls key should enable tls */ it('Init without any tls key should enable tls', function () { + const helper = this.helper; var rest = helper.AblyRest({ port: 123, tlsPort: 456 }); expect(rest.baseUri('example.com')).to.equal('https://example.com:456'); }); it("Init with clientId set to '*' or anything other than a string or null should error", function () { + const helper = this.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 f75833008..e77d89724 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); @@ -21,7 +20,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Authenticate with a clientId and ensure that the clientId is not sent in the Message and is implicitly added when published */ it('Should implicitly send clientId when authenticated with clientId', async function () { - var clientId = 'implicit_client_id_0', + var helper = this.helper, + clientId = 'implicit_client_id_0', rest = helper.AblyRest({ clientId: clientId, useBinaryProtocol: false }), channel = rest.channels.get('rest_implicit_client_id_0'); @@ -43,7 +43,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Authenticate with a clientId and explicitly provide the same clientId in the Message and ensure it is published */ it('Should publish clientId when provided explicitly in message', async function () { - var clientId = 'explicit_client_id_0', + var helper = this.helper, + clientId = 'explicit_client_id_0', rest = helper.AblyRest({ clientId: clientId, useBinaryProtocol: false }), channel = rest.channels.get('rest_explicit_client_id_0'); @@ -67,7 +68,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Authenticate with a clientId and explicitly provide a different invalid clientId in the Message and expect it to not be published and be rejected */ it('Should error when clientId sent in message is different than authenticated clientId', async function () { - var clientId = 'explicit_client_id_0', + var helper = this.helper, + clientId = 'explicit_client_id_0', invalidClientId = 'invalid'; var token = await helper.AblyRest().auth.requestToken({ clientId: clientId }); @@ -101,7 +103,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* TO3l8; CD2C; RSL1i */ 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.helper, + realtime = helper.AblyRest({ maxMessageSize: 64 }), channel = realtime.channels.get('maxMessageSize'); try { @@ -116,7 +119,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Check ids are correctly sent */ it('Should send correct IDs when idempotentRestPublishing set to false', async function () { - var rest = helper.AblyRest({ idempotentRestPublishing: false, useBinaryProtocol: false }), + var helper = this.helper, + rest = helper.AblyRest({ idempotentRestPublishing: false, useBinaryProtocol: false }), channel = rest.channels.get('idempotent_rest_publishing'), message = { name: 'test', id: 'idempotent-msg-id:0' }; @@ -130,7 +134,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* Check ids are added when automatic idempotent rest publishing option enabled */ 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.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 */ @@ -181,7 +186,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('Rest publish params', async function () { - var rest = helper.AblyRest(), + var helper = this.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 d9d668e3c..1d5ab4046 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 0d83ac194..9e969cd96 100644 --- a/test/rest/push.test.js +++ b/test/rest/push.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 expect = chai.expect; var testDevice = { @@ -34,12 +32,14 @@ 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 () { done(); }); }); it('Get subscriptions', async function () { + const helper = this.helper; var subscribes = []; var deletes = []; var subsByChannel = {}; @@ -71,6 +71,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('Publish', async function () { + const helper = this.helper; try { var realtime = helper.AblyRealtime(); @@ -108,6 +109,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('deviceRegistrations save', async function () { + const helper = this.helper; var rest = helper.AblyRest(); var saved = await rest.push.admin.deviceRegistrations.save(testDevice); @@ -122,6 +124,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('deviceRegistrations get and list', async function () { + const helper = this.helper; var registrations = []; var deletes = []; var devices = []; @@ -195,6 +198,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('deviceRegistrations remove removeWhere', async function () { + const helper = this.helper; var rest = helper.AblyRest(); await rest.push.admin.deviceRegistrations.save(testDevice); @@ -219,6 +223,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('channelSubscriptions save', async function () { + const helper = this.helper; var rest = helper.AblyRest({ clientId: 'testClient' }); var subscription = { clientId: 'testClient', channel: 'pushenabled:foo' }; @@ -234,6 +239,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('channelSubscriptions get', async function () { + const helper = this.helper; var subscribes = []; var deletes = []; var subsByChannel = {}; @@ -269,6 +275,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('push_channelSubscriptions_remove', async function () { + const helper = this.helper; var rest = helper.AblyRest({ clientId: 'testClient' }); var subscription = { clientId: 'testClient', channel: 'pushenabled:foo' }; @@ -277,6 +284,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async }); it('channelSubscriptions listChannels', async function () { + const helper = this.helper; var subscribes = []; var deletes = []; for (var i = 0; i < 5; i++) { diff --git a/test/rest/request.test.js b/test/rest/request.test.js index 2cf60f96f..9e49ce64e 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); @@ -69,6 +68,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async /* With a network issue, should get an actual err, not an HttpPaginatedResponse with error members */ it('request_network_error', async function () { + const helper = this.helper; rest = helper.AblyRest({ restHost: helper.unroutableAddress }); try { var res = await rest.request('get', '/time', Defaults.protocolVersion, null, null, null); @@ -169,6 +169,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, Helper, async ['put', 'patch', 'delete'].forEach(function (method) { it('check' + method, async function () { + const helper = this.helper; var restEcho = helper.AblyRest({ useBinaryProtocol: false, restHost: echoServerHost, tls: true }); var res = await restEcho.request(method, '/methods', Defaults.protocolVersion, {}, {}, {}); 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 540dccf9f..c46513dc7 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 f296d7770..9e4dce7ab 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; @@ -11,6 +9,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 b6cb68f90..ad49fbd39 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..f86acc7cf 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.helper.closeActiveClients(); }); afterEach(function () { - helper.logTestResults(this); + this.helper.logTestResults(this); }); afterEach(function () { - helper.flushTestLogs(); + this.helper.flushTestLogs(); + }); + beforeEach(function () { + this.helper = Helper.forTest(this); }); beforeEach(function () { - helper.clearTransportPreference(); + this.helper.clearTransportPreference(); }); });