From 3340ca4add0dd9aee9402a2d76eebf6b196f8aaa Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Wed, 26 Apr 2023 11:08:03 +0100 Subject: [PATCH 01/30] test: add test constructors for promise-based clients Co-authored-by: Lawrence Forooghian --- test/common/modules/client_module.js | 10 ++++++++++ test/common/modules/shared_helper.js | 2 ++ 2 files changed, 12 insertions(+) diff --git a/test/common/modules/client_module.js b/test/common/modules/client_module.js index 7f2c990ea0..df26c74cff 100644 --- a/test/common/modules/client_module.js +++ b/test/common/modules/client_module.js @@ -26,13 +26,23 @@ define(['ably', 'globals', 'test/common/modules/testapp_module'], function (Ably return new Ably.Rest(ablyClientOptions(options)); } + function ablyRestPromise(options) { + return new Ably.Rest.Promise(ablyClientOptions(options)); + } + function ablyRealtime(options) { return new Ably.Realtime(ablyClientOptions(options)); } + function ablyRealtimePromise(options) { + return new Ably.Realtime.Promise(ablyClientOptions(options)); + } + return (module.exports = { Ably: Ably, AblyRest: ablyRest, + AblyRestPromise: ablyRestPromise, AblyRealtime: ablyRealtime, + AblyRealtimePromise: ablyRealtimePromise, }); }); diff --git a/test/common/modules/shared_helper.js b/test/common/modules/shared_helper.js index 14442575cf..ef18ae9297 100644 --- a/test/common/modules/shared_helper.js +++ b/test/common/modules/shared_helper.js @@ -213,7 +213,9 @@ define([ Ably: clientModule.Ably, AblyRest: clientModule.AblyRest, + AblyRestPromise: clientModule.AblyRestPromise, AblyRealtime: clientModule.AblyRealtime, + AblyRealtimePromise: clientModule.AblyRealtimePromise, Utils: utils, loadTestData: testAppManager.loadJsonData, From 1ca52a34e6581c4644fd221cf97360b51d5a0207 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 4 May 2023 22:46:40 +0100 Subject: [PATCH 02/30] test: add restTestOnJsonMsgpackAsync Co-authored-by: Lawrence Forooghian --- test/common/modules/shared_helper.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test/common/modules/shared_helper.js b/test/common/modules/shared_helper.js index ef18ae9297..d9a6b7216e 100644 --- a/test/common/modules/shared_helper.js +++ b/test/common/modules/shared_helper.js @@ -162,6 +162,20 @@ define([ restTestOnJsonMsgpack(name, testFn, true); }; + function restTestOnJsonMsgpackAsync(name, testFn, skip) { + var itFn = skip ? it.skip : it; + itFn(name + ' with binary protocol', async function () { + await testFn(new clientModule.AblyRestPromise({ useBinaryProtocol: true }), name + '_binary'); + }); + itFn(name + ' with text protocol', async function () { + await testFn(new clientModule.AblyRestPromise({ useBinaryProtocol: false }), name + '_text'); + }); + } + + restTestOnJsonMsgpackAsync.skip = function (name, testFn) { + restTestOnJsonMsgpackAsync(name, testFn, true); + }; + function clearTransportPreference() { if (isBrowser && window.localStorage) { window.localStorage.removeItem('ably-transport-preference'); @@ -228,6 +242,7 @@ define([ becomeSuspended: becomeSuspended, testOnAllTransports: testOnAllTransports, restTestOnJsonMsgpack: restTestOnJsonMsgpack, + restTestOnJsonMsgpackAsync: restTestOnJsonMsgpackAsync, availableTransports: availableTransports, bestTransport: bestTransport, clearTransportPreference: clearTransportPreference, From 76a1e6342dba55e50312ab2e1dd1be1e4c9ee9e8 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Wed, 26 Apr 2023 15:59:19 +0100 Subject: [PATCH 03/30] test: convert rest auth tests to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/auth.test.js | 800 ++++++++++++----------------------------- 1 file changed, 235 insertions(+), 565 deletions(-) diff --git a/test/rest/auth.test.js b/test/rest/auth.test.js index c2ff774f02..e1a9825be1 100644 --- a/test/rest/auth.test.js +++ b/test/rest/auth.test.js @@ -10,437 +10,243 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as describe('rest/auth', function () { this.timeout(60 * 1000); - var getServerTime = function (callback) { - rest.time(function (err, time) { - if (err) { - callback(err); - } - callback(null, time); - }); - }; - before(function (done) { helper.setupApp(function () { - rest = helper.AblyRest({ queryTime: true }); - getServerTime(function (err, time) { - if (err) { + rest = helper.AblyRestPromise({ queryTime: true }); + rest + .time() + .then(function (time) { + currentTime = time; + expect(true, 'Obtained time').to.be.ok; + done(); + }) + .catch(function (err) { done(err); - return; - } - currentTime = time; - expect(true, 'Obtained time').to.be.ok; - done(); - }); + }); }); }); - it('Base token generation case', function (done) { - rest.auth.requestToken(function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(tokenDetails.token, 'Verify token value').to.be.ok; - expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; - expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; - expect(tokenDetails.expires).to.equal(60 * 60 * 1000 + tokenDetails.issued, 'Verify default expiry period'); - expect(JSON.parse(tokenDetails.capability)).to.deep.equal({ '*': ['*'] }, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + it('Base token generation case', async function () { + var tokenDetails = await rest.auth.requestToken(); + expect(tokenDetails.token, 'Verify token value').to.be.ok; + expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; + expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; + expect(tokenDetails.expires).to.equal(60 * 60 * 1000 + tokenDetails.issued, 'Verify default expiry period'); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal({ '*': ['*'] }, 'Verify token capability'); }); - it('Base token generation with options', function (done) { - rest.auth.requestToken(null, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(tokenDetails.token, 'Verify token value').to.be.ok; - expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; - expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; - expect(JSON.parse(tokenDetails.capability)).to.deep.equal({ '*': ['*'] }, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + it('Base token generation with options', async function () { + var tokenDetails = await rest.auth.requestToken(null); + expect(tokenDetails.token, 'Verify token value').to.be.ok; + expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; + expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; + expect(JSON.parse(tokenDetails.capability)).to.deep.equal({ '*': ['*'] }, 'Verify token capability'); }); - it('Generate token and init library with it', function (done) { - rest.auth.requestToken(function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(tokenDetails.token, 'Verify token value').to.be.ok; - helper.AblyRest({ token: tokenDetails.token }); - done(); - } catch (err) { - done(err); - } - }); + it('Generate token and init library with it', async function () { + var tokenDetails = await rest.auth.requestToken(); + expect(tokenDetails.token, 'Verify token value').to.be.ok; + helper.AblyRestPromise({ token: tokenDetails.token }); }); - it('Token generation with explicit timestamp', function (done) { - getServerTime(function (err, serverTime) { - if (err) { - done(err); - return; - } - - rest.auth.requestToken({ timestamp: serverTime }, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(tokenDetails.token).to.be.ok; - expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; - expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; - expect(JSON.parse(tokenDetails.capability)).to.deep.equal({ '*': ['*'] }, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); - }); + it('Token generation with explicit timestamp', async function () { + var serverTime = await rest.time(); + var tokenDetails = await rest.auth.requestToken({ timestamp: serverTime }); + expect(tokenDetails.token).to.be.ok; + expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; + expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; + expect(JSON.parse(tokenDetails.capability)).to.deep.equal({ '*': ['*'] }, 'Verify token capability'); }); - it('Token generation with invalid timestamp', function (done) { + it('Token generation with invalid timestamp', async function () { var badTime = utils.now() - 30 * 60 * 1000; - rest.auth.requestToken({ timestamp: badTime }, function (err, tokenDetails) { - if (err) { - try { - expect(err.statusCode).to.equal(401, 'Verify token request rejected with bad timestamp'); - done(); - } catch (err) { - done(err); - } - return; - } - done(new Error('Invalid timestamp, expected rejection')); - }); + try { + var tokenDetails = await rest.auth.requestToken({ timestamp: badTime }); + } catch (err) { + expect(err.statusCode).to.equal(401, 'Verify token request rejected with bad timestamp'); + return; + } + throw new Error('Invalid timestamp, expected rejection'); }); - it('Token generation with system timestamp', function (done) { - rest.auth.requestToken(function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(tokenDetails.token, 'Verify token value').to.be.ok; - expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; - expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; - expect(JSON.parse(tokenDetails.capability)).to.deep.equal({ '*': ['*'] }, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + it('Token generation with system timestamp', async function () { + var tokenDetails = await rest.auth.requestToken(); + expect(tokenDetails.token, 'Verify token value').to.be.ok; + expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; + expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; + expect(JSON.parse(tokenDetails.capability)).to.deep.equal({ '*': ['*'] }, 'Verify token capability'); }); - it('Token generation with duplicate nonce', function (done) { - getServerTime(function (err, serverTime) { - if (err) { - done(err); - return; - } - rest.auth.requestToken({ timestamp: serverTime, nonce: '1234567890123456' }, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - rest.auth.requestToken({ timestamp: serverTime, nonce: '1234567890123456' }, function (err, tokenDetails) { - if (err) { - try { - expect(err.statusCode).to.equal(401, 'Verify request rejected with duplicated nonce'); - done(); - } catch (err) { - done(err); - } - return; - } - done(new Error('Invalid nonce, expected rejection')); - }); - }); - }); + it('Token generation with duplicate nonce', async function () { + var serverTime = await rest.time(); + await rest.auth.requestToken({ timestamp: serverTime, nonce: '1234567890123456' }); + try { + await rest.auth.requestToken({ timestamp: serverTime, nonce: '1234567890123456' }); + } catch (err) { + expect(err.statusCode).to.equal(401, 'Verify request rejected with duplicated nonce'); + return; + } + throw new Error('Invalid nonce, expected rejection'); }); - it('Token generation with clientId', function (done) { + it('Token generation with clientId', async function () { var testClientId = 'test client id'; - rest.auth.requestToken({ clientId: testClientId }, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(tokenDetails.token, 'Verify token value').to.be.ok; - expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; - expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; - expect(tokenDetails.clientId).to.equal(testClientId, 'Verify client id'); - expect(JSON.parse(tokenDetails.capability)).to.deep.equal({ '*': ['*'] }, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + var tokenDetails = await rest.auth.requestToken({ clientId: testClientId }); + expect(tokenDetails.token, 'Verify token value').to.be.ok; + expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; + expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; + expect(tokenDetails.clientId).to.equal(testClientId, 'Verify client id'); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal({ '*': ['*'] }, 'Verify token capability'); }); - it('Token generation with empty string clientId should error', function (done) { - rest.auth.requestToken({ clientId: '' }, function (err, tokenDetails) { - if (err) { - expect(err.code).to.equal(40012); - done(); - return; - } - done(new Error('Expected token generation to error with empty string clientId')); - }); + it('Token generation with empty string clientId should error', async function () { + try { + var tokenDetails = await rest.auth.requestToken({ clientId: '' }); + } catch (err) { + expect(err.code).to.equal(40012); + return; + } + throw new Error('Expected token generation to error with empty string clientId'); }); - it('Token generation with capability that subsets key capability', function (done) { + it('Token generation with capability that subsets key capability', async function () { var testCapability = { onlythischannel: ['subscribe'] }; - rest.auth.requestToken({ capability: testCapability }, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(tokenDetails.token, 'Verify token value').to.be.ok; - expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; - expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(testCapability, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + var tokenDetails = await rest.auth.requestToken({ capability: testCapability }); + expect(tokenDetails.token, 'Verify token value').to.be.ok; + expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; + expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(testCapability, 'Verify token capability'); }); - it('Token generation with specified key', function (done) { + it('Token generation with specified key', async function () { var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; var testCapability = JSON.parse(helper.getTestApp().keys[1].capability); - rest.auth.requestToken(null, testKeyOpts, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(tokenDetails.token, 'Verify token value').to.be.ok; - expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; - expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; - expect(tokenDetails.keyName).to.equal(helper.getTestApp().keys[1].keyName, 'Verify token key'); - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(testCapability, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + var tokenDetails = await rest.auth.requestToken(null, testKeyOpts); + expect(tokenDetails.token, 'Verify token value').to.be.ok; + expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; + expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; + expect(tokenDetails.keyName).to.equal(helper.getTestApp().keys[1].keyName, 'Verify token key'); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(testCapability, 'Verify token capability'); }); - it('Token generation with explicit auth', function (done) { - rest.auth.getAuthHeaders(function (err, authHeaders) { - if (err) { - done(err); - return; - } - rest.auth.authOptions.requestHeaders = authHeaders; - rest.auth.requestToken(function (err, tokenDetails) { - delete rest.auth.authOptions.requestHeaders; + it('Token generation with explicit auth', async function () { + var authHeaders = await new Promise((resolve, reject) => { + rest.auth.getAuthHeaders(function (err, authHeaders) { if (err) { - done(err); + reject(err); return; } - try { - expect(tokenDetails.token, 'Verify token value').to.be.ok; - expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; - expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; - expect(tokenDetails.keyName).to.equal(helper.getTestApp().keys[0].keyName, 'Verify token key'); - done(); - } catch (err) { - done(err); - } + resolve(authHeaders); }); }); + rest.auth.authOptions.requestHeaders = authHeaders; + var tokenDetails = await rest.auth.requestToken(); + delete rest.auth.authOptions.requestHeaders; + expect(tokenDetails.token, 'Verify token value').to.be.ok; + expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; + expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; + expect(tokenDetails.keyName).to.equal(helper.getTestApp().keys[0].keyName, 'Verify token key'); }); - it('Token generation with explicit auth, different key', function (done) { - rest.auth.getAuthHeaders(function (err, authHeaders) { - var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; - var testCapability = JSON.parse(helper.getTestApp().keys[1].capability); - rest.auth.requestToken(null, testKeyOpts, function (err, tokenDetails) { + it('Token generation with explicit auth, different key', async function () { + var authHeaders = await new Promise((resolve, reject) => { + rest.auth.getAuthHeaders(function (err, authHeaders) { if (err) { - done(err); + reject(err); return; } - try { - expect(tokenDetails.token, 'Verify token value').to.be.ok; - expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; - expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; - expect(tokenDetails.keyName).to.equal(helper.getTestApp().keys[1].keyName, 'Verify token key'); - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(testCapability, 'Verify token capability'); - done(); - } catch (e) { - done(e); - } + resolve(authHeaders); }); }); + 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); + expect(tokenDetails.token, 'Verify token value').to.be.ok; + expect(tokenDetails.issued && tokenDetails.issued >= currentTime, 'Verify token issued').to.be.ok; + expect(tokenDetails.expires && tokenDetails.expires > tokenDetails.issued, 'Verify token expires').to.be.ok; + expect(tokenDetails.keyName).to.equal(helper.getTestApp().keys[1].keyName, 'Verify token key'); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(testCapability, 'Verify token capability'); }); - it('Token generation with invalid mac', function (done) { - rest.auth.requestToken({ mac: '12345' }, function (err, tokenDetails) { - if (err) { - try { - expect(err.statusCode).to.equal(401, 'Verify request rejected with bad mac'); - done(); - } catch (e) { - done(e); - } - return; - } - done(new Error('Invalid mac, expected rejection')); - }); + it('Token generation with invalid mac', async function () { + try { + var tokenDetails = await rest.auth.requestToken({ mac: '12345' }); + } catch (err) { + expect(err.statusCode).to.equal(401, 'Verify request rejected with bad mac'); + return; + } + throw new Error('Invalid mac, expected rejection'); }); - it('Token generation with defaultTokenParams set and no tokenParams passed in', function (done) { - var rest1 = helper.AblyRest({ defaultTokenParams: { ttl: 123, clientId: 'foo' } }); - rest1.auth.requestToken(function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(tokenDetails.token, 'Verify token value').to.be.ok; - expect(tokenDetails.clientId).to.equal('foo', 'Verify client id from defaultTokenParams used'); - expect(tokenDetails.expires - tokenDetails.issued).to.equal(123, 'Verify ttl from defaultTokenParams used'); - done(); - } catch (err) { - done(err); - } - }); + it('Token generation with defaultTokenParams set and no tokenParams passed in', async function () { + var rest1 = helper.AblyRestPromise({ defaultTokenParams: { ttl: 123, clientId: 'foo' } }); + var tokenDetails = await rest1.auth.requestToken(); + expect(tokenDetails.token, 'Verify token value').to.be.ok; + expect(tokenDetails.clientId).to.equal('foo', 'Verify client id from defaultTokenParams used'); + expect(tokenDetails.expires - tokenDetails.issued).to.equal(123, 'Verify ttl from defaultTokenParams used'); }); - it('Token generation: if tokenParams passed in, defaultTokenParams should be ignored altogether, not merged', function (done) { - var rest1 = helper.AblyRest({ defaultTokenParams: { ttl: 123, clientId: 'foo' } }); - rest1.auth.requestToken({ clientId: 'bar' }, null, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(tokenDetails.clientId).to.equal( - 'bar', - 'Verify clientId passed in is used, not the one from defaultTokenParams' - ); - expect(tokenDetails.expires - tokenDetails.issued).to.equal( - 60 * 60 * 1000, - 'Verify ttl from defaultTokenParams ignored completely, even though not overridden' - ); - done(); - } catch (err) { - done(err); - } - }); + it('Token generation: if tokenParams passed in, defaultTokenParams should be ignored altogether, not merged', async function () { + var rest1 = helper.AblyRestPromise({ defaultTokenParams: { ttl: 123, clientId: 'foo' } }); + var tokenDetails = await rest1.auth.requestToken({ clientId: 'bar' }, null); + expect(tokenDetails.clientId).to.equal( + 'bar', + 'Verify clientId passed in is used, not the one from defaultTokenParams' + ); + expect(tokenDetails.expires - tokenDetails.issued).to.equal( + 60 * 60 * 1000, + 'Verify ttl from defaultTokenParams ignored completely, even though not overridden' + ); }); /* * authorize with different args */ - it('Authorize with different args', function (done) { - async.parallel( - [ - function (cb) { - rest.auth.authorize(null, null, function (err, tokenDetails) { - expect(tokenDetails.token, 'Check token obtained').to.be.ok; - cb(err); - }); - }, - function (cb) { - rest.auth.authorize(null, function (err, tokenDetails) { - expect(tokenDetails.token, 'Check token obtained').to.be.ok; - cb(err); - }); - }, - function (cb) { - rest.auth.authorize(function (err, tokenDetails) { - expect(tokenDetails.token, 'Check token obtained').to.be.ok; - cb(err); - }); - }, - ], - function (err) { - if (err) { - done(err); - } - done(); - } - ); - }); + it('Authorize with different args', async function () { + var results = await Promise.all([ + rest.auth.authorize(), + rest.auth.authorize(null), + rest.auth.authorize(null, null), + ]); - it('Specify non-default ttl', function (done) { - rest.auth.requestToken({ ttl: 100 * 1000 }, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(tokenDetails.expires).to.equal(100 * 1000 + tokenDetails.issued, 'Verify non-default expiry period'); - done(); - } catch (err) { - done(err); - } + results.forEach((tokenDetails) => { + expect(tokenDetails.token, 'Check token obtained').to.be.ok; }); }); - it('Should error with excessive ttl', function (done) { - rest.auth.requestToken({ ttl: 365 * 24 * 60 * 60 * 1000 }, function (err, tokenDetails) { - if (err) { - try { - expect(err.statusCode).to.equal(400, 'Verify request rejected with excessive expiry'); - done(); - } catch (err) { - done(err); - } - return; - } - done(new Error('Excessive expiry, expected rejection')); - }); + it('Specify non-default ttl', async function () { + var tokenDetails = await rest.auth.requestToken({ ttl: 100 * 1000 }); + expect(tokenDetails.expires).to.equal(100 * 1000 + tokenDetails.issued, 'Verify non-default expiry period'); }); - it('Should error with negative ttl', function (done) { - rest.auth.requestToken({ ttl: -1 }, function (err, tokenDetails) { - if (err) { - try { - expect(err.statusCode).to.equal(400, 'Verify request rejected with negative expiry'); - done(); - } catch (err) { - done(err); - } - return; - } - done(new Error('Negative expiry, expected rejection')); - }); + it('Should error with excessive ttl', async function () { + try { + var tokenDetails = await rest.auth.requestToken({ ttl: 365 * 24 * 60 * 60 * 1000 }); + } catch (err) { + expect(err.statusCode).to.equal(400, 'Verify request rejected with excessive expiry'); + return; + } + throw new Error('Excessive expiry, expected rejection'); }); - it('Should error with invalid ttl', function (done) { - rest.auth.requestToken({ ttl: 'notanumber' }, function (err, tokenDetails) { - if (err) { - try { - expect(err.statusCode).to.equal(400, 'Verify request rejected with invalid expiry'); - done(); - } catch (e) { - done(e); - } - return; - } - done(new Error('Invalid expiry, expected rejection')); - }); + it('Should error with negative ttl', async function () { + try { + var tokenDetails = await rest.auth.requestToken({ ttl: -1 }); + } catch (err) { + expect(err.statusCode).to.equal(400, 'Verify request rejected with negative expiry'); + return; + } + throw new Error('Negative expiry, expected rejection'); + }); + + it('Should error with invalid ttl', async function () { + try { + var tokenDetails = await rest.auth.requestToken({ ttl: 'notanumber' }); + } catch (err) { + expect(err.statusCode).to.equal(400, 'Verify request rejected with invalid expiry'); + return; + } + throw new Error('Invalid expiry, expected rejection'); }); /* @@ -448,91 +254,28 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as * and the token request includes all the fields it should include, but * doesn't include ttl or capability by default */ - it('createTokenRequest without authOptions', function (done) { - rest.auth.createTokenRequest(null, null, function (err, tokenRequest) { - if (err) { - done(err); - return; - } - try { - expect('mac' in tokenRequest, 'check tokenRequest contains a mac').to.be.ok; - expect('nonce' in tokenRequest, 'check tokenRequest contains a nonce').to.be.ok; - expect('timestamp' in tokenRequest, 'check tokenRequest contains a timestamp').to.be.ok; - expect(!('ttl' in tokenRequest), 'check tokenRequest does not contains a ttl by default').to.be.ok; - expect( - !('capability' in tokenRequest), - 'check tokenRequest does not contains capabilities by default' - ).to.be.ok; - expect(tokenRequest.keyName).to.equal(helper.getTestApp().keys[0].keyName); - done(); - } catch (err) { - done(err); - } - }); - }); - - it('createTokenRequest without authOptions, callback as 2nd param', function (done) { - rest.auth.createTokenRequest(null, function (err, tokenRequest) { - if (err) { - done(err); - return; - } - try { - expect(tokenRequest.keyName).to.equal(helper.getTestApp().keys[0].keyName); - done(); - } catch (err) { - done(err); - } - }); + it('createTokenRequest without authOptions', async function () { + 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; + expect('timestamp' in tokenRequest, 'check tokenRequest contains a timestamp').to.be.ok; + expect(!('ttl' in tokenRequest), 'check tokenRequest does not contains a ttl by default').to.be.ok; + expect(!('capability' in tokenRequest), 'check tokenRequest does not contains capabilities by default').to.be.ok; + expect(tokenRequest.keyName).to.equal(helper.getTestApp().keys[0].keyName); }); - it('createTokenRequest without authOptions or tokenParams, callback as 1st param', function (done) { - rest.auth.createTokenRequest(function (err, tokenRequest) { - if (err) { - done(err); - return; - } - try { - expect(tokenRequest.keyName).to.equal(helper.getTestApp().keys[0].keyName); - done(); - } catch (err) { - done(err); - } - }); - }); - - it('createTokenRequest uses the key it was initialized with if authOptions does not have a "key" key', function (done) { - rest.auth.createTokenRequest(function (err, tokenRequest) { - if (err) { - done(err); - return; - } - try { - expect(tokenRequest.keyName).to.equal(helper.getTestApp().keys[0].keyName); - done(); - } catch (err) { - done(err); - } - }); + it('createTokenRequest uses the key it was initialized with if authOptions does not have a "key" key', async function () { + var tokenRequest = await rest.auth.createTokenRequest(); + expect(tokenRequest.keyName).to.equal(helper.getTestApp().keys[0].keyName); }); - it('createTokenRequest should serialise capability object as JSON', function (done) { + it('createTokenRequest should serialise capability object as JSON', async function () { var capability = { '*': ['*'] }; - rest.auth.createTokenRequest({ capability: capability }, null, function (err, tokenRequest) { - if (err) { - done(err); - return; - } - try { - expect(JSON.parse(tokenRequest.capability)).to.deep.equal( - capability, - 'Verify createTokenRequest has JSON-stringified capability' - ); - done(); - } catch (err) { - done(err); - } - }); + var tokenRequest = await rest.auth.createTokenRequest({ capability: capability }, null); + expect(JSON.parse(tokenRequest.capability)).to.deep.equal( + capability, + 'Verify createTokenRequest has JSON-stringified capability' + ); }); /** @@ -541,27 +284,16 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as * @param {object} params The authParams to be tested */ function testJWTAuthParams(description, params) { - it(description, function (done) { + it(description, async function () { var currentKey = helper.getTestApp().keys[0]; var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var authParams = utils.mixin(keys, params); var authUrl = echoServer + '/createJWT' + utils.toQueryString(authParams); - var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); + var restJWTRequester = helper.AblyRestPromise({ authUrl: authUrl }); - restJWTRequester.auth.requestToken(function (err, tokenDetails) { - if (err) { - done(err); - return; - } - var restClient = helper.AblyRest({ token: tokenDetails.token }); - restClient.stats(function (err, stats) { - if (err) { - done(err); - return; - } - done(); - }); - }); + var tokenDetails = await restJWTRequester.auth.requestToken(); + var restClient = helper.AblyRestPromise({ token: tokenDetails.token }); + await restClient.stats(); }); } @@ -580,147 +312,85 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as }); } - it('JWT request with invalid key', function (done) { + it('JWT request with invalid key', async function () { var keys = { keyName: 'invalid.invalid', keySecret: 'invalidinvalid' }; var authUrl = echoServer + '/createJWT' + utils.toQueryString(keys); - var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); - - restJWTRequester.auth.requestToken(function (err, tokenDetails) { - if (err) { - done(err); - return; - } - var restClient = helper.AblyRest({ token: tokenDetails.token }); - restClient.stats(function (err, stats) { - try { - expect(err.code).to.equal(40400, 'Verify token is invalid because app id does not exist'); - expect(err.statusCode).to.equal(404, 'Verify token is invalid because app id does not exist'); - done(); - return; - } catch (err) { - done(err); - } - }); - }); + var restJWTRequester = helper.AblyRestPromise({ authUrl: authUrl }); + + var tokenDetails = await restJWTRequester.auth.requestToken(); + var restClient = helper.AblyRestPromise({ token: tokenDetails.token }); + try { + var stats = await restClient.stats(); + } catch (err) { + expect(err.code).to.equal(40400, 'Verify token is invalid because app id does not exist'); + expect(err.statusCode).to.equal(404, 'Verify token is invalid because app id does not exist'); + return; + } + throw new Error('Expected restClient.stats() to throw token error'); }); /* * RSA8g */ - it('Rest JWT with authCallback', function (done) { + it('Rest JWT with authCallback', async function () { var currentKey = helper.getTestApp().keys[0]; var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var authUrl = echoServer + '/createJWT' + utils.toQueryString(keys); - var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); + var restJWTRequester = helper.AblyRestPromise({ authUrl: authUrl }); var authCallback = function (tokenParams, callback) { - restJWTRequester.auth.requestToken(function (err, tokenDetails) { - if (err) { - done(err); - return; - } + restJWTRequester.auth.requestToken().then(function (tokenDetails) { callback(null, tokenDetails.token); }); }; - var restClient = helper.AblyRest({ authCallback: authCallback }); - restClient.stats(function (err, stats) { - if (err) { - done(err); - return; - } - try { - expect(err).to.equal(null, 'Verify that the error is null'); - done(); - } catch (err) { - done(err); - } - }); + var restClient = helper.AblyRestPromise({ authCallback: authCallback }); + var stats = await restClient.stats(); }); /* * RSA8g */ - it('Rest JWT with authCallback and invalid keys', function (done) { + it('Rest JWT with authCallback and invalid keys', async function () { var keys = { keyName: 'invalid.invalid', keySecret: 'invalidinvalid' }; var authUrl = echoServer + '/createJWT' + utils.toQueryString(keys); - var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); + var restJWTRequester = helper.AblyRestPromise({ authUrl: authUrl }); var authCallback = function (tokenParams, callback) { - restJWTRequester.auth.requestToken(function (err, tokenDetails) { - if (err) { - done(err); - return; - } + restJWTRequester.auth.requestToken().then(function (tokenDetails) { callback(null, tokenDetails.token); }); }; - var restClient = helper.AblyRest({ authCallback: authCallback }); - restClient.stats(function (err, stats) { - try { - expect(err.code).to.equal(40400, 'Verify code is 40400'); - expect(err.statusCode).to.equal(404, 'Verify token is invalid because app id does not exist'); - done(); - } catch (err) { - done(err); - } - }); + var restClient = helper.AblyRestPromise({ authCallback: authCallback }); + try { + await restClient.stats(); + } catch (err) { + expect(err.code).to.equal(40400, 'Verify code is 40400'); + expect(err.statusCode).to.equal(404, 'Verify token is invalid because app id does not exist'); + return; + } + throw new Error('Expected restClient.stats() to throw token error'); }); - it('authCallback is only invoked once on concurrent auth', function (done) { + it('authCallback is only invoked once on concurrent auth', async function () { var authCallbackInvocations = 0; function authCallback(tokenParams, callback) { authCallbackInvocations++; - rest.auth.createTokenRequest(tokenParams, callback); + rest.auth.createTokenRequest(tokenParams).then(function (tokenRequest) { + callback(null, tokenRequest); + }); } /* Example client-side using the token */ - var restClient = helper.AblyRest({ authCallback: authCallback }); + var restClient = helper.AblyRestPromise({ authCallback: authCallback }); var channel = restClient.channels.get('auth_concurrent'); - async.parallel([channel.history.bind(channel), channel.history.bind(channel)], function (err) { - try { - expect(!err, err && helper.displayError(err)).to.be.ok; - expect(authCallbackInvocations).to.equal( - 1, - 'Check authCallback only invoked once -- was: ' + authCallbackInvocations - ); - done(); - } catch (err) { - done(err); - } - }); + await Promise.all([channel.history(), channel.history()]); + expect(authCallbackInvocations).to.equal( + 1, + 'Check authCallback only invoked once -- was: ' + authCallbackInvocations + ); }); - - if (typeof Promise !== 'undefined') { - it('Promise based auth', function (done) { - var rest = helper.AblyRest({ internal: { promises: true } }); - - var promise1 = rest.auth.requestToken(); - var promise2 = rest.auth.requestToken({ ttl: 200 }); - var promise3 = rest.auth.requestToken({ ttl: 200 }, { key: helper.getTestApp().keys[1].keyStr }); - var promise4 = rest.auth.createTokenRequest(); - var promise5 = rest.auth.createTokenRequest({ ttl: 200 }); - var promise6 = rest.auth.requestToken({ ttl: 200 }, { key: 'bad' })['catch'](function (err) { - expect(true, 'Token attempt with bad key was rejected').to.be.ok; - }); - - Promise.all([promise1, promise2, promise3, promise4, promise5, promise6]) - .then(function (results) { - try { - for (var i = 0; i < 5; i++) { - expect(results[i].token || results[i].nonce).to.be.ok; - } - done(); - } catch (err) { - done(err); - } - }) - ['catch'](function (err) { - done(err); - }); - }); - } }); }); From af38ec87800dc02e6a15a3c584d7297ddfc8138c Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Wed, 26 Apr 2023 16:39:21 +0100 Subject: [PATCH 04/30] test: convert rest capability tests to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/capability.test.js | 274 ++++++++++------------------------- 1 file changed, 78 insertions(+), 196 deletions(-) diff --git a/test/rest/capability.test.js b/test/rest/capability.test.js index 60e4172e73..0c88b94bfc 100644 --- a/test/rest/capability.test.js +++ b/test/rest/capability.test.js @@ -19,266 +19,148 @@ define(['shared_helper', 'chai'], function (helper, chai) { this.timeout(60 * 1000); before(function (done) { - helper.setupApp(function (err) { - if (err) { - done(err); - return; - } - - rest = helper.AblyRest(); + helper.setupApp(function () { + rest = helper.AblyRestPromise({ queryTime: true }); testApp = helper.getTestApp(); - rest.time(function (err, time) { - if (err) { + rest + .time() + .then(function (time) { + currentTime = time; + expect(true, 'Obtained time').to.be.ok; + done(); + }) + .catch(function (err) { done(err); - return; - } - currentTime = time; - done(); - }); + }); }); }); - it('Blanket intersection with specified key', function (done) { + it('Blanket intersection with specified key', async function () { var testKeyOpts = { key: testApp.keys[1].keyStr }; var testCapability = JSON.parse(testApp.keys[1].capability); - rest.auth.requestToken(null, testKeyOpts, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(testCapability, 'Verify token capability'); - done(); - } catch (e) { - done(e); - } - }); + var tokenDetails = await rest.auth.requestToken(null, testKeyOpts); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(testCapability, 'Verify token capability'); }); - it('Equal intersection with specified key', function (done) { + it('Equal intersection with specified key', async function () { var testKeyOpts = { key: testApp.keys[1].keyStr }; var testCapability = JSON.parse(testApp.keys[1].capability); - rest.auth.requestToken({ capability: testCapability }, testKeyOpts, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(testCapability, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + var tokenDetails = await rest.auth.requestToken({ capability: testCapability }, testKeyOpts); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(testCapability, 'Verify token capability'); }); - it('Empty ops intersection', function (done) { + it('Empty ops intersection', async function () { var testKeyOpts = { key: testApp.keys[1].keyStr }; var testCapability = { 'canpublish:test': ['subscribe'] }; - rest.auth.requestToken({ capability: testCapability }, testKeyOpts, function (err, tokenDetails) { - if (err) { - try { - expect(err.statusCode).to.equal(401, 'Verify request rejected with insufficient capability'); - done(); - } catch (err) { - done(err); - } - return; - } - done(new Error('Invalid capability, expected rejection')); - }); + try { + var tokenDetails = await rest.auth.requestToken({ capability: testCapability }, testKeyOpts); + } catch (err) { + expect(err.statusCode).to.equal(401, 'Verify request rejected with insufficient capability'); + return; + } + expect.fail('Invalid capability, expected rejection'); }); - it('Empty paths intersection', function (done) { + it('Empty paths intersection', async function () { var testKeyOpts = { key: testApp.keys[2].keyStr }; var testCapability = { channelx: ['publish'] }; - rest.auth.requestToken({ capability: testCapability }, testKeyOpts, function (err, tokenDetails) { - if (err) { - try { - expect(err.statusCode).to.equal(401, 'Verify request rejected with insufficient capability'); - done(); - } catch (err) { - done(err); - } - return; - } - done('Invalid capability, expected rejection'); - }); + try { + var tokenDetails = await rest.auth.requestToken({ capability: testCapability }, testKeyOpts); + } catch (err) { + expect(err.statusCode).to.equal(401, 'Verify request rejected with insufficient capability'); + return; + } + expect.fail('Invalid capability, expected rejection'); }); - it('Ops intersection non-empty', function (done) { + it('Ops intersection non-empty', async function () { var testKeyOpts = { key: testApp.keys[2].keyStr }; var testCapability = { channel2: ['presence', 'subscribe'] }; var expectedIntersection = { channel2: ['subscribe'] }; - rest.auth.requestToken({ capability: testCapability }, testKeyOpts, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + var tokenDetails = await rest.auth.requestToken({ capability: testCapability }, testKeyOpts); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); }); - it('Paths intersection non-empty', function (done) { + it('Paths intersection non-empty', async function () { var testKeyOpts = { key: testApp.keys[2].keyStr }; var testCapability = { channel2: ['presence', 'subscribe'], channelx: ['presence', 'subscribe'], }; var expectedIntersection = { channel2: ['subscribe'] }; - rest.auth.requestToken({ capability: testCapability }, testKeyOpts, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + var tokenDetails = await rest.auth.requestToken({ capability: testCapability }, testKeyOpts); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); }); - it('Wildcard token with publish and subscribe key', function (done) { + it('Wildcard token with publish and subscribe key', async function () { var testKeyOpts = { key: testApp.keys[2].keyStr }; var testCapability = { channel2: ['*'] }; var expectedIntersection = { channel2: ['publish', 'subscribe'] }; - rest.auth.requestToken({ capability: testCapability }, testKeyOpts, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + var tokenDetails = await rest.auth.requestToken({ capability: testCapability }, testKeyOpts); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); }); - it('Publish and subscribe token with wildcard key', function (done) { + it('Publish and subscribe token with wildcard key', async function () { var testKeyOpts = { key: testApp.keys[2].keyStr }; var testCapability = { channel6: ['publish', 'subscribe'] }; var expectedIntersection = { channel6: ['publish', 'subscribe'] }; - rest.auth.requestToken({ capability: testCapability }, testKeyOpts, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + var tokenDetails = await rest.auth.requestToken({ capability: testCapability }, testKeyOpts); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); }); - it('Resources wildcard matching 1', function (done) { + it('Resources wildcard matching 1', async function () { var testKeyOpts = { key: testApp.keys[3].keyStr }; var testCapability = { cansubscribe: ['subscribe'] }; var expectedIntersection = testCapability; - rest.auth.requestToken({ capability: testCapability }, testKeyOpts, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + var tokenDetails = await rest.auth.requestToken({ capability: testCapability }, testKeyOpts); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); }); - it('Resources wildcard matching 2', function (done) { + it('Resources wildcard matching 2', async function () { var testKeyOpts = { key: testApp.keys[1].keyStr }; var testCapability = { 'canpublish:check': ['publish'] }; var expectedIntersection = testCapability; - rest.auth.requestToken({ capability: testCapability }, testKeyOpts, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + var tokenDetails = await rest.auth.requestToken({ capability: testCapability }, testKeyOpts); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); }); - it('Resources wildcard matching 3', function (done) { + it('Resources wildcard matching 3', async function () { var testKeyOpts = { key: testApp.keys[3].keyStr }; var testCapability = { 'cansubscribe:*': ['subscribe'] }; var expectedIntersection = testCapability; - rest.auth.requestToken({ capability: testCapability }, testKeyOpts, function (err, tokenDetails) { - if (err) { - done(err); - return; - } - try { - expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); - done(); - } catch (err) { - done(err); - } - }); + var tokenDetails = await rest.auth.requestToken({ capability: testCapability }, testKeyOpts); + expect(JSON.parse(tokenDetails.capability)).to.deep.equal(expectedIntersection, 'Verify token capability'); }); /* Invalid capabilities */ - it('Invalid capabilities 1', function (done) { - rest.auth.requestToken({ capability: invalid0 }, function (err, tokenDetails) { - if (err) { - try { - expect(err.statusCode).to.equal(400, 'Verify request rejected with bad capability'); - done(); - } catch (err) { - done(err); - } - return; - } - done(new Error('Invalid capability, expected rejection')); - }); + it('Invalid capabilities 1', async function () { + try { + var tokenDetails = await rest.auth.requestToken({ capability: invalid0 }); + } catch (err) { + expect(err.statusCode).to.equal(400, 'Verify request rejected with bad capability'); + return; + } + expect.fail('Invalid capability, expected rejection'); }); - it('Invalid capabilities 2', function (done) { - rest.auth.requestToken({ capability: invalid1 }, function (err, tokenDetails) { - if (err) { - try { - expect(err.statusCode).to.equal(400, 'Verify request rejected with bad capability'); - done(); - } catch (err) { - done(err); - } - return; - } - done(new Error('Invalid capability, expected rejection')); - }); + it('Invalid capabilities 2', async function () { + try { + var tokenDetails = await rest.auth.requestToken({ capability: invalid1 }); + } catch (err) { + expect(err.statusCode).to.equal(400, 'Verify request rejected with bad capability'); + return; + } + expect.fail('Invalid capability, expected rejection'); }); - it('Invalid capabilities 3', function (done) { - rest.auth.requestToken({ capability: invalid2 }, function (err, tokenDetails) { - if (err) { - try { - expect(err.statusCode).to.equal(400, 'Verify request rejected with bad capability'); - done(); - } catch (err) { - done(err); - } - return; - } - done(new Error('Invalid capability, expected rejection')); - }); + it('Invalid capabilities 3', async function () { + try { + var tokenDetails = await rest.auth.requestToken({ capability: invalid2 }); + } catch (err) { + expect(err.statusCode).to.equal(400, 'Verify request rejected with bad capability'); + return; + } + expect.fail('Invalid capability, expected rejection'); }); }); }); From a1fb8ddfdec16cc934ac7d770d8d95e54dee1532 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Wed, 26 Apr 2023 16:59:08 +0100 Subject: [PATCH 05/30] test: convert rest fallbacks tests to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/fallbacks.test.js | 82 +++++++++++-------------------------- 1 file changed, 25 insertions(+), 57 deletions(-) diff --git a/test/rest/fallbacks.test.js b/test/rest/fallbacks.test.js index 65e024e759..df716ecede 100644 --- a/test/rest/fallbacks.test.js +++ b/test/rest/fallbacks.test.js @@ -14,75 +14,43 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { done(err); return; } - goodHost = helper.AblyRest().options.restHost; + goodHost = helper.AblyRestPromise().options.restHost; done(); }); }); /* RSC15f */ - it('Store working fallback', function (done) { - var rest = helper.AblyRest({ + it('Store working fallback', async function () { + var rest = helper.AblyRestPromise({ restHost: helper.unroutableHost, fallbackHosts: [goodHost], httpRequestTimeout: 3000, logLevel: 4, }); var validUntil; - async.series( - [ - function (cb) { - rest.time(function (err, serverTime) { - if (err) { - return cb(err); - } - expect(serverTime, 'Check serverTime returned').to.be.ok; - var currentFallback = rest._currentFallback; - expect(currentFallback, 'Check current fallback stored').to.be.ok; - expect(currentFallback && currentFallback.host).to.equal(goodHost, 'Check good host set'); - validUntil = currentFallback.validUntil; - cb(); - }); - }, - /* now try again, check that this time it uses the remembered good endpoint straight away */ - function (cb) { - rest.time(function (err, serverTime) { - if (err) { - return cb(err); - } - expect(serverTime, 'Check serverTime returned').to.be.ok; - var currentFallback = rest._currentFallback; - expect(currentFallback.validUntil).to.equal( - validUntil, - 'Check validUntil is the same (implying currentFallback has not been re-set)' - ); - cb(); - }); - }, - /* set the validUntil to the past and check that the stored fallback is forgotten */ - function (cb) { - var now = utils.now(); - rest._currentFallback.validUntil = now - 1000; - rest.time(function (err, serverTime) { - if (err) { - return cb(err); - } - expect(serverTime, 'Check serverTime returned').to.be.ok; - var currentFallback = rest._currentFallback; - expect(currentFallback, 'Check current fallback re-stored').to.be.ok; - expect(currentFallback && currentFallback.host).to.equal(goodHost, 'Check good host set again'); - expect(currentFallback.validUntil > now, 'Check validUntil has been re-set').to.be.ok; - cb(); - }); - }, - ], - function (err) { - if (err) { - done(err); - return; - } - done(); - } + var serverTime = await rest.time(); + expect(serverTime, 'Check serverTime returned').to.be.ok; + var currentFallback = rest._currentFallback; + expect(currentFallback, 'Check current fallback stored').to.be.ok; + expect(currentFallback && currentFallback.host).to.equal(goodHost, 'Check good host set'); + validUntil = currentFallback.validUntil; + /* now try again, check that this time it uses the remembered good endpoint straight away */ + var serverTime = await rest.time(); + expect(serverTime, 'Check serverTime returned').to.be.ok; + var currentFallback = rest._currentFallback; + expect(currentFallback.validUntil).to.equal( + validUntil, + 'Check validUntil is the same (implying currentFallback has not been re-set)' ); + /* set the validUntil to the past and check that the stored fallback is forgotten */ + var now = utils.now(); + rest._currentFallback.validUntil = now - 1000; + var serverTime = await rest.time(); + expect(serverTime, 'Check serverTime returned').to.be.ok; + var currentFallback = rest._currentFallback; + expect(currentFallback, 'Check current fallback re-stored').to.be.ok; + expect(currentFallback && currentFallback.host).to.equal(goodHost, 'Check good host set again'); + expect(currentFallback.validUntil > now, 'Check validUntil has been re-set').to.be.ok; }); }); }); From 6d0d329b0e2d312b25a6b7c974ae5e901af7d918 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Wed, 26 Apr 2023 18:00:40 +0100 Subject: [PATCH 06/30] test: convert rest history tests to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/history.test.js | 543 ++++++++++++-------------------------- 1 file changed, 168 insertions(+), 375 deletions(-) diff --git a/test/rest/history.test.js b/test/rest/history.test.js index 249c2be72c..8946788e64 100644 --- a/test/rest/history.test.js +++ b/test/rest/history.test.js @@ -4,7 +4,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { var rest; var expect = chai.expect; var exports = {}; - var restTestOnJsonMsgpack = helper.restTestOnJsonMsgpack; + var restTestOnJsonMsgpackAsync = helper.restTestOnJsonMsgpackAsync; var utils = helper.Utils; var testMessages = [ { name: 'event0', data: 'some data' }, @@ -15,433 +15,226 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { { name: 'event5', data: { one: 1, two: 2, three: 3 } }, { name: 'event6', data: { foo: 'bar' } }, ]; + var reversedMessages = testMessages.map((_, i) => testMessages[testMessages.length - 1 - i]); describe('rest/history', function () { this.timeout(60 * 1000); before(function (done) { helper.setupApp(function () { - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); done(); }); }); - restTestOnJsonMsgpack('history_simple', function (done, rest, channelName) { + restTestOnJsonMsgpackAsync('history_simple', async function (rest, channelName) { var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ - - var publishTasks = utils.arrMap(testMessages, function (event) { - return function (publishCb) { - testchannel.publish(event.name, event.data, publishCb); - }; - }); - - publishTasks.push(function (waitCb) { - setTimeout(function () { - waitCb(null); - }, 1000); + await Promise.all([ + new Promise((resolve) => setTimeout(resolve, 1000)), + ...testMessages.map((event) => testchannel.publish(event.name, event.data)), + ]); + + /* so now the messages are there; try querying the timeline */ + var resultPage = await testchannel.history(); + /* verify all messages are received */ + var messages = resultPage.items; + expect(messages.length).to.equal(testMessages.length, 'Verify correct number of messages found'); + + /* verify message ids are unique */ + var ids = {}; + utils.arrForEach(messages, function (msg) { + ids[msg.id] = msg; }); - try { - async.parallel(publishTasks, function (err) { - if (err) { - done(err); - return; - } - - /* so now the messages are there; try querying the timeline */ - testchannel.history(function (err, resultPage) { - if (err) { - done(err); - return; - } - /* verify all messages are received */ - var messages = resultPage.items; - expect(messages.length).to.equal(testMessages.length, 'Verify correct number of messages found'); - - /* verify message ids are unique */ - var ids = {}; - utils.arrForEach(messages, function (msg) { - ids[msg.id] = msg; - }); - expect(utils.keysArray(ids).length).to.equal( - testMessages.length, - 'Verify correct number of distinct message ids found' - ); - done(); - }); - }); - } catch (err) { - done(err); - } + expect(utils.keysArray(ids).length).to.equal( + testMessages.length, + 'Verify correct number of distinct message ids found' + ); }); - restTestOnJsonMsgpack('history_multiple', function (done, rest, channelName) { + restTestOnJsonMsgpackAsync('history_multiple', async function (rest, channelName) { var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ - var publishTasks = [ - function (publishCb) { - testchannel.publish(testMessages, publishCb); - }, - ]; - - publishTasks.push(function (waitCb) { - setTimeout(function () { - waitCb(null); - }, 1000); + await Promise.all([new Promise((resolve) => setTimeout(resolve, 1000)), testchannel.publish(testMessages)]); + + /* so now the messages are there; try querying the timeline */ + var resultPage = await testchannel.history(); + /* verify all messages are received */ + var messages = resultPage.items; + expect(messages.length).to.equal(testMessages.length, 'Verify correct number of messages found'); + + /* verify message ids are unique */ + var ids = {}; + utils.arrForEach(messages, function (msg) { + ids[msg.id] = msg; }); - try { - async.parallel(publishTasks, function (err) { - if (err) { - done(err); - return; - } - - /* so now the messages are there; try querying the timeline */ - testchannel.history(function (err, resultPage) { - if (err) { - done(err); - return; - } - /* verify all messages are received */ - var messages = resultPage.items; - expect(messages.length).to.equal(testMessages.length, 'Verify correct number of messages found'); - - /* verify message ids are unique */ - var ids = {}; - utils.arrForEach(messages, function (msg) { - ids[msg.id] = msg; - }); - expect(utils.keysArray(ids).length).to.equal( - testMessages.length, - 'Verify correct number of distinct message ids found' - ); - done(); - }); - }); - } catch (err) { - done(err); - } + expect(utils.keysArray(ids).length).to.equal( + testMessages.length, + 'Verify correct number of distinct message ids found' + ); }); - restTestOnJsonMsgpack('history_simple_paginated_b', function (done, rest, channelName) { + restTestOnJsonMsgpackAsync('history_simple_paginated_b', async function (rest, channelName) { var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ - var publishTasks = utils.arrMap(testMessages, function (event) { - return function (publishCb) { - testchannel.publish(event.name, event.data, publishCb); - }; - }); + for (var message of testMessages) { + await testchannel.publish(message.name, message.data); + } - publishTasks.push(function (waitCb) { - setTimeout(function () { - waitCb(null); - }, 1000); - }); - try { - async.series(publishTasks, function (err) { - if (err) { - done(err); - return; - } - - /* so now the messages are there; try querying the timeline to get messages one at a time */ - var ids = {}, - totalMessagesExpected = testMessages.length, - nextPage = function (cb) { - testchannel.history({ limit: 1, direction: 'backwards' }, cb); - }; - - testMessages.reverse(); - async.mapSeries( - testMessages, - function (expectedMessage, cb) { - nextPage(function (err, resultPage) { - if (err) { - cb(err); - return; - } - /* verify expected number of messages in this page */ - expect(resultPage.items.length).to.equal(1, 'Verify a single message received'); - var resultMessage = resultPage.items[0]; - ids[resultMessage.id] = resultMessage; - - /* verify expected message */ - expect(expectedMessage.name).to.equal(resultMessage.name, 'Verify expected name value present'); - expect(expectedMessage.data).to.deep.equal(resultMessage.data, 'Verify expected data value present'); - - if (--totalMessagesExpected > 0) { - expect(resultPage.hasNext(), 'Verify next link is present').to.be.ok; - expect(!resultPage.isLast(), 'Verify not last page').to.be.ok; - nextPage = resultPage.next; - } - cb(); - }); - }, - function (err) { - if (err) { - done(err); - return; - } - /* verify message ids are unique */ - expect(utils.keysArray(ids).length).to.equal( - testMessages.length, - 'Verify correct number of distinct message ids found' - ); - done(); - } - ); - }); - } catch (err) { - done(err); + await new Promise((resolve) => setTimeout(resolve, 1000)); + + /* so now the messages are there; try querying the timeline to get messages one at a time */ + var ids = {}, + totalMessagesExpected = testMessages.length; + + var resultPage = await testchannel.history({ limit: 1, direction: 'backwards' }); + for (var expectedMessage of reversedMessages) { + /* verify expected number of messages in this page */ + expect(resultPage.items.length).to.equal(1, 'Verify a single message received'); + var resultMessage = resultPage.items[0]; + ids[resultMessage.id] = resultMessage; + + /* verify expected message */ + expect(expectedMessage.name).to.equal(resultMessage.name, 'Verify expected name value present'); + expect(expectedMessage.data).to.deep.equal(resultMessage.data, 'Verify expected data value present'); + + if (--totalMessagesExpected > 0) { + expect(resultPage.hasNext(), 'Verify next link is present').to.be.ok; + expect(!resultPage.isLast(), 'Verify not last page').to.be.ok; + resultPage = await resultPage.next(); + } } + /* verify message ids are unique */ + expect(utils.keysArray(ids).length).to.equal( + testMessages.length, + 'Verify correct number of distinct message ids found' + ); }); - it('history_simple_paginated_f', function (done) { + it('history_simple_paginated_f', async function () { var testchannel = rest.channels.get('persisted:history_simple_paginated_f'); /* first, send a number of events to this channel */ - var publishTasks = utils.arrMap(testMessages, function (event) { - return function (publishCb) { - testchannel.publish(event.name, event.data, publishCb); - }; - }); + for (var message of testMessages) { + await testchannel.publish(message.name, message.data); + } - publishTasks.push(function (waitCb) { - setTimeout(function () { - waitCb(null); - }, 1000); + await new Promise(function (resolve) { + setTimeout(resolve, 1000); }); - try { - async.series(publishTasks, function (err) { - if (err) { - done(err); - return; - } - - /* so now the messages are there; try querying the timeline to get messages one at a time */ - var ids = {}, - totalMessagesExpected = testMessages.length, - nextPage = function (cb) { - testchannel.history({ limit: 1, direction: 'forwards' }, cb); - }; - - async.mapSeries( - testMessages, - function (expectedMessage, cb) { - nextPage(function (err, resultPage) { - if (err) { - cb(err); - return; - } - /* verify expected number of messages in this page */ - expect(resultPage.items.length).to.equal(1, 'Verify a single message received'); - var resultMessage = resultPage.items[0]; - ids[resultMessage.id] = resultMessage; - - /* verify expected message */ - expect(expectedMessage.name).to.equal(resultMessage.name, 'Verify expected name value present'); - expect(expectedMessage.data).to.deep.equal(resultMessage.data, 'Verify expected data value present'); - - if (--totalMessagesExpected > 0) { - expect(resultPage.hasNext(), 'Verify next link is present').to.be.ok; - nextPage = resultPage.next; - } - cb(); - }); - }, - function (err) { - if (err) { - done(err); - return; - } - /* verify message ids are unique */ - expect(utils.keysArray(ids).length).to.equal( - testMessages.length, - 'Verify correct number of distinct message ids found' - ); - done(); - } - ); - }); - } catch (err) { - done(err); + + var ids = {}, + totalMessagesExpected = testMessages.length; + + var resultPage = await testchannel.history({ limit: 1, direction: 'forwards' }); + for (var expectedMessage of testMessages) { + /* verify expected number of messages in this page */ + expect(resultPage.items.length).to.equal(1, 'Verify a single message received'); + var resultMessage = resultPage.items[0]; + ids[resultMessage.id] = resultMessage; + + /* verify expected message */ + expect(expectedMessage.name).to.equal(resultMessage.name, 'Verify expected name value present'); + expect(expectedMessage.data).to.deep.equal(resultMessage.data, 'Verify expected data value present'); + + if (--totalMessagesExpected > 0) { + expect(resultPage.hasNext(), 'Verify next link is present').to.be.ok; + resultPage = await resultPage.next(); + } } + + /* verify message ids are unique */ + expect(utils.keysArray(ids).length).to.equal( + testMessages.length, + 'Verify correct number of distinct message ids found' + ); }); - it('history_multiple_paginated_b', function (done) { + it('history_multiple_paginated_b', async function () { var testchannel = rest.channels.get('persisted:history_multiple_paginated_b'); /* first, send a number of events to this channel */ - var publishTasks = [ - function (publishCb) { - testchannel.publish(testMessages, publishCb); - }, - ]; - - publishTasks.push(function (waitCb) { - setTimeout(function () { - waitCb(null); - }, 1000); + for (var message of testMessages) { + await testchannel.publish(message.name, message.data); + } + + await new Promise(function (resolve) { + setTimeout(resolve, 1000); }); - try { - async.series(publishTasks, function (err) { - if (err) { - done(err); - return; - } - - /* so now the messages are there; try querying the timeline to get messages one at a time */ - var ids = {}, - totalMessagesExpected = testMessages.length, - nextPage = function (cb) { - testchannel.history({ limit: 1, direction: 'backwards' }, cb); - }; - - testMessages.reverse(); - async.mapSeries( - testMessages, - function (expectedMessage, cb) { - nextPage(function (err, resultPage) { - if (err) { - cb(err); - return; - } - /* verify expected number of messages in this page */ - expect(resultPage.items.length).to.equal(1, 'Verify a single message received'); - var resultMessage = resultPage.items[0]; - ids[resultMessage.id] = resultMessage; - - /* verify expected message */ - expect(expectedMessage.name).to.equal(resultMessage.name, 'Verify expected name value present'); - expect(expectedMessage.data).to.deep.equal(resultMessage.data, 'Verify expected data value present'); - - if (--totalMessagesExpected > 0) { - expect(resultPage.hasNext(), 'Verify next link is present').to.be.ok; - nextPage = resultPage.next; - } - cb(); - }); - }, - function (err) { - if (err) { - done(err); - return; - } - /* verify message ids are unique */ - expect(utils.keysArray(ids).length).to.equal( - testMessages.length, - 'Verify correct number of distinct message ids found' - ); - done(); - } - ); - }); - } catch (err) { - done(err); + + /* so now the messages are there; try querying the timeline to get messages one at a time */ + var ids = {}, + totalMessagesExpected = testMessages.length; + + var resultPage = await testchannel.history({ limit: 1, direction: 'backwards' }); + for (var expectedMessage of reversedMessages) { + /* verify expected number of messages in this page */ + expect(resultPage.items.length).to.equal(1, 'Verify a single message received'); + var resultMessage = resultPage.items[0]; + ids[resultMessage.id] = resultMessage; + + /* verify expected message */ + expect(expectedMessage.name).to.equal(resultMessage.name, 'Verify expected name value present'); + expect(expectedMessage.data).to.deep.equal(resultMessage.data, 'Verify expected data value present'); + + if (--totalMessagesExpected > 0) { + expect(resultPage.hasNext(), 'Verify next link is present').to.be.ok; + resultPage = await resultPage.next(); + } } }); - it('history_multiple_paginated_f', function (done) { + it('history_multiple_paginated_f', async function () { var testchannel = rest.channels.get('persisted:history_multiple_paginated_f'); /* first, send a number of events to this channel */ - var publishTasks = [ - function (publishCb) { - testchannel.publish(testMessages, publishCb); - }, - ]; - - publishTasks.push(function (waitCb) { - setTimeout(function () { - waitCb(null); - }, 1000); + await testchannel.publish(testMessages); + + await new Promise(function (resolve) { + setTimeout(resolve, 1000); }); - try { - async.series(publishTasks, function (err) { - if (err) { - done(err); - return; - } - - /* so now the messages are there; try querying the timeline to get messages one at a time */ - var ids = {}, - totalMessagesExpected = testMessages.length, - nextPage = function (cb) { - testchannel.history({ limit: 1, direction: 'forwards' }, cb); - }; - - async.mapSeries( - testMessages, - function (expectedMessage, cb) { - nextPage(function (err, resultPage) { - if (err) { - cb(err); - return; - } - /* verify expected number of messages in this page */ - expect(resultPage.items.length).to.equal(1, 'Verify a single message received'); - var resultMessage = resultPage.items[0]; - ids[resultMessage.id] = resultMessage; - - /* verify expected message */ - expect(expectedMessage.name).to.equal(resultMessage.name, 'Verify expected name value present'); - expect(expectedMessage.data).to.deep.equal(resultMessage.data, 'Verify expected data value present'); - - if (--totalMessagesExpected > 0) { - expect(resultPage.hasNext(), 'Verify next link is present').to.be.ok; - nextPage = resultPage.next; - } - cb(); - }); - }, - function (err) { - if (err) { - done(err); - return; - } - /* verify message ids are unique */ - expect(utils.keysArray(ids).length).to.equal( - testMessages.length, - 'Verify correct number of distinct message ids found' - ); - done(); - } - ); - }); - } catch (err) { - done(err); + + /* so now the messages are there; try querying the timeline to get messages one at a time */ + var ids = {}, + totalMessagesExpected = testMessages.length; + + var resultPage = await testchannel.history({ limit: 1, direction: 'forwards' }); + for (var expectedMessage of testMessages) { + /* verify expected number of messages in this page */ + expect(resultPage.items.length).to.equal(1, 'Verify a single message received'); + var resultMessage = resultPage.items[0]; + ids[resultMessage.id] = resultMessage; + + /* verify expected message */ + expect(expectedMessage.name).to.equal(resultMessage.name, 'Verify expected name value present'); + expect(expectedMessage.data).to.deep.equal(resultMessage.data, 'Verify expected data value present'); + + if (--totalMessagesExpected > 0) { + expect(resultPage.hasNext(), 'Verify next link is present').to.be.ok; + var resultPage = await resultPage.next(); + } } + + /* verify message ids are unique */ + expect(utils.keysArray(ids).length).to.equal( + testMessages.length, + 'Verify correct number of distinct message ids found' + ); }); - restTestOnJsonMsgpack('history_encoding_errors', function (done, rest, channelName) { + restTestOnJsonMsgpackAsync('history_encoding_errors', async function (rest, channelName) { var testchannel = rest.channels.get('persisted:' + channelName); var badMessage = { name: 'jsonUtf8string', encoding: 'json/utf-8', data: '{"foo":"bar"}' }; - try { - testchannel.publish(badMessage, function (err) { - if (err) { - done(err); - return; - } - setTimeout(function () { - testchannel.history(function (err, resultPage) { - if (err) { - done(err); - return; - } - /* verify all messages are received */ - var message = resultPage.items[0]; - expect(message.data).to.equal(badMessage.data, 'Verify data preserved'); - expect(message.encoding).to.equal(badMessage.encoding, 'Verify encoding preserved'); - done(); - }); - }, 1000); - }); - } catch (err) { - done(err); - } + testchannel.publish(badMessage); + await new Promise((resolve) => setTimeout(resolve, 1000)); + var resultPage = await testchannel.history(); + /* verify all messages are received */ + var message = resultPage.items[0]; + expect(message.data).to.equal(badMessage.data, 'Verify data preserved'); + expect(message.encoding).to.equal(badMessage.encoding, 'Verify encoding preserved'); }); if (typeof Promise !== 'undefined') { From b07d0325cb2188ba4fe5b10e3ec82261c2684e78 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Wed, 26 Apr 2023 18:00:59 +0100 Subject: [PATCH 07/30] test: remove legacy rest history promise test Co-authored-by: Lawrence Forooghian --- test/rest/history.test.js | 36 ------------------------------------ 1 file changed, 36 deletions(-) diff --git a/test/rest/history.test.js b/test/rest/history.test.js index 8946788e64..a4d7420ee5 100644 --- a/test/rest/history.test.js +++ b/test/rest/history.test.js @@ -236,41 +236,5 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { expect(message.data).to.equal(badMessage.data, 'Verify data preserved'); expect(message.encoding).to.equal(badMessage.encoding, 'Verify encoding preserved'); }); - - if (typeof Promise !== 'undefined') { - it('historyPromise', function (done) { - var rest = helper.AblyRest({ internal: { promises: true } }); - var testchannel = rest.channels.get('persisted:history_promise'); - - testchannel - .publish('one', null) - .then(function () { - return testchannel.publish('two', null); - }) - .then(function () { - return testchannel.history({ limit: 1, direction: 'forwards' }); - }) - .then(function (resultPage) { - expect(resultPage.items.length).to.equal(1); - expect(resultPage.items[0].name).to.equal('one'); - return resultPage.first(); - }) - .then(function (resultPage) { - expect(resultPage.items[0].name).to.equal('one'); - return resultPage.current(); - }) - .then(function (resultPage) { - expect(resultPage.items[0].name).to.equal('one'); - return resultPage.next(); - }) - .then(function (resultPage) { - expect(resultPage.items[0].name).to.equal('two'); - done(); - }) - ['catch'](function (err) { - done(err); - }); - }); - } }); }); From 24d299e17041ff0885220ff7e53979f8f1d0b322 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Wed, 26 Apr 2023 18:14:21 +0100 Subject: [PATCH 08/30] test: convert rest http tests to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/http.test.js | 62 ++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/test/rest/http.test.js b/test/rest/http.test.js index 21502fed71..ff363d3b19 100644 --- a/test/rest/http.test.js +++ b/test/rest/http.test.js @@ -9,7 +9,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { this.timeout(60 * 1000); before(function (done) { helper.setupApp(function () { - rest = helper.AblyRest({ + rest = helper.AblyRestPromise({ agents: { 'custom-agent': '0.1.2', }, @@ -21,46 +21,44 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { /** * RSC7a */ - it('Should send X-Ably-Version and Ably-Agent headers in get/post requests', function (done) { - //Intercept Http.do with test - function testRequestHandler(_, __, ___, headers) { - try { - expect('X-Ably-Version' in headers, 'Verify version header exists').to.be.ok; - expect('Ably-Agent' in headers, 'Verify agent header exists').to.be.ok; + it('Should send X-Ably-Version and Ably-Agent headers in get/post requests', async function () { + var originalDo = rest.http.do; - // This test should not directly validate version against Defaults.version, as - // ultimately the version header has been derived from that value. - expect(headers['X-Ably-Version']).to.equal('2', 'Verify current version number'); - expect(headers['Ably-Agent'].indexOf('ably-js/' + Defaults.version) > -1, 'Verify agent').to.be.ok; - expect(headers['Ably-Agent'].indexOf('custom-agent/0.1.2') > -1, 'Verify custom agent').to.be.ok; + // Intercept Http.do with test + function testRequestHandler(method, rest, path, headers, body, params, callback) { + expect('X-Ably-Version' in headers, 'Verify version header exists').to.be.ok; + expect('Ably-Agent' in headers, 'Verify agent header exists').to.be.ok; - // We don't test on NativeScript so a check for that platform is excluded here - if (typeof document !== 'undefined') { - // browser - expect(headers['Ably-Agent'].indexOf('browser') > -1, 'Verify agent').to.be.ok; - } else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { - // reactnative - expect(headers['Ably-Agent'].indexOf('reactnative') > -1, 'Verify agent').to.be.ok; - } else { - // node - expect(headers['Ably-Agent'].indexOf('nodejs') > -1, 'Verify agent').to.be.ok; - } - } catch (err) { - done(err); + // This test should not directly validate version against Defaults.version, as + // ultimately the version header has been derived from that value. + expect(headers['X-Ably-Version']).to.equal('2', 'Verify current version number'); + expect(headers['Ably-Agent'].indexOf('ably-js/' + Defaults.version) > -1, 'Verify agent').to.be.ok; + expect(headers['Ably-Agent'].indexOf('custom-agent/0.1.2') > -1, 'Verify custom agent').to.be.ok; + + // We don't test on NativeScript so a check for that platform is excluded here + if (typeof document !== 'undefined') { + // browser + expect(headers['Ably-Agent'].indexOf('browser') > -1, 'Verify agent').to.be.ok; + } else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { + // reactnative + expect(headers['Ably-Agent'].indexOf('reactnative') > -1, 'Verify agent').to.be.ok; + } else { + // node + expect(headers['Ably-Agent'].indexOf('nodejs') > -1, 'Verify agent').to.be.ok; } + + originalDo.call(rest.http, method, rest, path, headers, body, params, callback); } rest.http.do = testRequestHandler; // Call all methods that use rest http calls - rest.auth.requestToken(); - rest.time(); - rest.stats(); + await rest.auth.requestToken(); + await rest.time(); + await rest.stats(); var channel = rest.channels.get('http_test_channel'); - channel.publish('test', 'Testing http headers'); - channel.presence.get(); - - done(); + await channel.publish('test', 'Testing http headers'); + await channel.presence.get(); }); }); }); From d40ea8f962e787bcbce0396276ea395ab8ef1012 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Wed, 26 Apr 2023 18:16:34 +0100 Subject: [PATCH 09/30] test: convert rest constructor tests to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/init.test.js | 48 +++++++++++++----------------------------- 1 file changed, 15 insertions(+), 33 deletions(-) diff --git a/test/rest/init.test.js b/test/rest/init.test.js index 7d83f277e0..11f9b5a11d 100644 --- a/test/rest/init.test.js +++ b/test/rest/init.test.js @@ -18,59 +18,48 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('Init with key string', function () { var keyStr = helper.getTestApp().keys[0].keyStr; - var rest = new helper.Ably.Rest(keyStr); + var rest = new helper.Ably.Rest.Promise(keyStr); expect(rest.options.key).to.equal(keyStr); }); - it('Init with token string', function (done) { - try { - /* first generate a token ... */ - var rest = helper.AblyRest(); - var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; + it('Init with token string', async function () { + /* first generate a token ... */ + var rest = helper.AblyRestPromise(); + var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; - rest.auth.requestToken(null, testKeyOpts, function (err, tokenDetails) { - if (err) { - done(err); - return; - } + var tokenDetails = await rest.auth.requestToken(null, testKeyOpts); + var tokenStr = tokenDetails.token, + rest = new helper.Ably.Rest.Promise(tokenStr); - var tokenStr = tokenDetails.token, - rest = new helper.Ably.Rest(tokenStr); - - expect(rest.options.token).to.equal(tokenStr); - done(); - }); - } catch (err) { - done(err); - } + expect(rest.options.token).to.equal(tokenStr); }); it('Init with tls: false', function () { - var rest = helper.AblyRest({ tls: false, port: 123, tlsPort: 456 }); + var rest = helper.AblyRestPromise({ tls: false, port: 123, tlsPort: 456 }); expect(rest.baseUri('example.com')).to.equal('http://example.com:123'); }); it('Init with tls: true', function () { - var rest = helper.AblyRest({ tls: true, port: 123, tlsPort: 456 }); + var rest = helper.AblyRestPromise({ 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 () { - var rest = helper.AblyRest({ port: 123, tlsPort: 456 }); + var rest = helper.AblyRestPromise({ 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 () { expect(function () { - var rest = helper.AblyRest({ clientId: '*' }); + var rest = helper.AblyRestPromise({ clientId: '*' }); }, 'Check can’t init library with a wildcard clientId').to.throw; expect(function () { - var rest = helper.AblyRest({ clientId: 123 }); + var rest = helper.AblyRestPromise({ clientId: 123 }); }, 'Check can’t init library with a numerical clientId').to.throw; expect(function () { - var rest = helper.AblyRest({ clientId: false }); + var rest = helper.AblyRestPromise({ clientId: false }); }, 'Check can’t init library with a boolean clientId').to.throw; }); @@ -78,9 +67,6 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var rest, keyStr = helper.getTestApp().keys[0].keyStr; - rest = new Ably.Rest(keyStr); - expect(!rest.options.promises, 'Check promises defaults to false').to.be.ok; - rest = new Ably.Rest.Promise(keyStr); expect(rest.options.promises, 'Check promises default to true with promise constructor').to.be.ok; @@ -88,10 +74,6 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var AblyPromises = require('../../promises'); rest = new AblyPromises.Rest(keyStr); expect(rest.options.promises, 'Check promises default to true with promise require target').to.be.ok; - - var AblyCallbacks = require('../../callbacks'); - rest = new AblyCallbacks.Rest(keyStr); - expect(!rest.options.promises, 'Check promises default to false with callback require target').to.be.ok; } }); }); From 152f4e59c7c338beb158cddff4b1a971add0c4ec Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Wed, 26 Apr 2023 18:29:09 +0100 Subject: [PATCH 10/30] test: convert rest message tests to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/message.test.js | 308 ++++++++++++-------------------------- 1 file changed, 96 insertions(+), 212 deletions(-) diff --git a/test/rest/message.test.js b/test/rest/message.test.js index 546f678c97..ca56219987 100644 --- a/test/rest/message.test.js +++ b/test/rest/message.test.js @@ -18,211 +18,121 @@ 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', function (done) { + it('Should implicitly send clientId when authenticated with clientId', async function () { var clientId = 'implicit_client_id_0', - rest = helper.AblyRest({ clientId: clientId, useBinaryProtocol: false }), + rest = helper.AblyRestPromise({ clientId: clientId, useBinaryProtocol: false }), channel = rest.channels.get('rest_implicit_client_id_0'); var originalPublish = channel._publish; channel._publish = function (requestBody) { var message = JSON.parse(requestBody)[0]; - try { - expect(message.name === 'event0', 'Outgoing message interecepted').to.be.ok; - expect(!message.clientId, 'client ID is not added by the client library as it is implicit').to.be.ok; - } catch (err) { - done(err); - } + expect(message.name === 'event0', 'Outgoing message interecepted').to.be.ok; + expect(!message.clientId, 'client ID is not added by the client library as it is implicit').to.be.ok; originalPublish.apply(channel, arguments); }; - channel.publish('event0', null, function (err) { - if (err) { - done(err); - return; - } - - channel.history(function (err, page) { - if (err) { - done(err); - return; - } + await channel.publish('event0', null); + var page = await channel.history(); - var message = page.items[0]; - try { - expect(message.clientId == clientId, 'Client ID was added implicitly').to.be.ok; - done(); - } catch (err) { - done(err); - } - }); - }); + var message = page.items[0]; + expect(message.clientId == clientId, 'Client ID was added implicitly').to.be.ok; }); /* 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', function (done) { + it('Should publish clientId when provided explicitly in message', async function () { var clientId = 'explicit_client_id_0', - rest = helper.AblyRest({ clientId: clientId, useBinaryProtocol: false }), + rest = helper.AblyRestPromise({ clientId: clientId, useBinaryProtocol: false }), channel = rest.channels.get('rest_explicit_client_id_0'); var originalPublish = channel._publish; channel._publish = function (requestBody) { var message = JSON.parse(requestBody)[0]; - try { - expect(message.name === 'event0', 'Outgoing message interecepted').to.be.ok; - expect( - message.clientId == clientId, - 'client ID is added by the client library as it is explicit in the publish' - ).to.be.ok; - } catch (err) { - done(err); - } + expect(message.name === 'event0', 'Outgoing message interecepted').to.be.ok; + expect( + message.clientId == clientId, + 'client ID is added by the client library as it is explicit in the publish' + ).to.be.ok; originalPublish.apply(channel, arguments); }; - channel.publish({ name: 'event0', clientId: clientId }, function (err) { - if (err) { - done(err); - } - - channel.history(function (err, page) { - if (err) { - done(err); - return; - } - - var message = page.items[0]; - try { - expect(message.clientId == clientId, 'Client ID was retained').to.be.ok; - done(); - } catch (err) { - done(err); - } - }); - }); + await channel.publish({ name: 'event0', clientId: clientId }); + var page = await channel.history(); + var message = page.items[0]; + expect(message.clientId == clientId, 'Client ID was retained').to.be.ok; }); /* 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', function (done) { + it('Should error when clientId sent in message is different than authenticated clientId', async function () { var clientId = 'explicit_client_id_0', invalidClientId = 'invalid'; - helper.AblyRest().auth.requestToken({ clientId: clientId }, function (err, token) { - try { - expect(token.clientId === clientId, 'client ID is present in the Token').to.be.ok; - } catch (err) { - done(err); - } - - // REST client uses a token string so is unaware of the clientId so cannot reject before communicating with Ably - var rest = helper.AblyRest({ token: token.token, useBinaryProtocol: false }), - channel = rest.channels.get('rest_explicit_client_id_1'); - - var originalPublish = channel._publish; - channel._publish = function (requestBody) { - var message = JSON.parse(requestBody)[0]; - try { - expect(message.name === 'event0', 'Outgoing message interecepted').to.be.ok; - expect( - message.clientId == invalidClientId, - 'invalid client ID is added by the client library as it is explicit in the publish' - ).to.be.ok; - } catch (err) { - done(err); - } - originalPublish.apply(channel, arguments); - }; + var token = await helper.AblyRestPromise().auth.requestToken({ clientId: clientId }); + expect(token.clientId === clientId, 'client ID is present in the Token').to.be.ok; - channel.publish({ name: 'event0', clientId: invalidClientId }, function (err) { - if (!err) { - done(new Error('Publish should have failed with invalid clientId')); - return; - } + // REST client uses a token string so is unaware of the clientId so cannot reject before communicating with Ably + var rest = helper.AblyRestPromise({ token: token.token, useBinaryProtocol: false }), + channel = rest.channels.get('rest_explicit_client_id_1'); - channel.history(function (err, page) { - if (err) { - done(err); - return; - } + var originalPublish = channel._publish; + channel._publish = function (requestBody) { + var message = JSON.parse(requestBody)[0]; + expect(message.name === 'event0', 'Outgoing message interecepted').to.be.ok; + expect( + message.clientId == invalidClientId, + 'invalid client ID is added by the client library as it is explicit in the publish' + ).to.be.ok; + originalPublish.apply(channel, arguments); + }; - try { - expect(page.items.length).to.equal(0, 'Message should not have been published'); - done(); - } catch (err) { - done(err); - } - }); - }); - }); + try { + await channel.publish({ name: 'event0', clientId: invalidClientId }); + } catch (err) { + var page = await channel.history(); + expect(page.items.length).to.equal(0, 'Message should not have been published'); + return; + } + expect.fail('Publish should have failed with invalid clientId'); }); /* TO3l8; CD2C; RSL1i */ - it('Should error when publishing message larger than maxMessageSize', function (done) { + 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({ internal: { maxMessageSize: 64 } }), + var realtime = helper.AblyRestPromise({ internal: { maxMessageSize: 64 } }), channel = realtime.channels.get('maxMessageSize'); - channel.publish('foo', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', function (err) { - try { - expect(err, 'Check publish refused').to.be.ok; - expect(err.code).to.equal(40009); - done(); - } catch (err) { - done(err); - } - }); + try { + await channel.publish('foo', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'); + } catch (err) { + expect(err, 'Check publish refused').to.be.ok; + expect(err.code).to.equal(40009); + return; + } + expect.fail('Expected channel.publish() to throw error'); }); /* Check ids are correctly sent */ - it('Should send correct IDs when idempotentRestPublishing set to false', function (done) { - var rest = helper.AblyRest({ idempotentRestPublishing: false, useBinaryProtocol: false }), + it('Should send correct IDs when idempotentRestPublishing set to false', async function () { + var rest = helper.AblyRestPromise({ idempotentRestPublishing: false, useBinaryProtocol: false }), channel = rest.channels.get('idempotent_rest_publishing'), message = { name: 'test', id: 'idempotent-msg-id:0' }; - async.parallel( - [ - function (parCb) { - channel.publish(message, parCb); - }, - function (parCb) { - channel.publish(message, parCb); - }, - function (parCb) { - channel.publish(message, parCb); - }, - ], - function (err) { - if (err) { - done(err); - return; - } + await Promise.all([channel.publish(message), channel.publish(message), channel.publish(message)]); - channel.history(function (err, page) { - if (err) { - done(err); - return; - } - try { - expect(page.items.length).to.equal(1, 'Check only one message published'); - expect(page.items[0].id).to.equal(message.id, 'Check message id preserved in history'); - done(); - } catch (err) { - done(err); - } - }); - } - ); + var page = await channel.history(); + expect(page.items.length).to.equal(1, 'Check only one message published'); + expect(page.items[0].id).to.equal(message.id, 'Check message id preserved in history'); }); /* Check ids are added when automatic idempotent rest publishing option enabled */ - it('Should add IDs when automatic idempotent rest publishing option enabled', function (done) { + 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 dummyRest = helper.AblyRestPromise(), 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 */ - rest = helper.AblyRest({ + rest = helper.AblyRestPromise({ idempotentRestPublishing: true, useBinaryProtocol: false, fallbackHosts: [host, host, host], @@ -234,27 +144,22 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async originalDoUri = Ably.Realtime.Platform.Http.doUri; channel._publish = function (requestBody) { - try { - var messageOne = JSON.parse(requestBody)[0]; - var messageTwo = JSON.parse(requestBody)[1]; - expect(messageOne.name).to.equal('one', 'Outgoing message 1 interecepted'); - expect(messageTwo.name).to.equal('two', 'Outgoing message 2 interecepted'); - idOne = messageOne.id; - idTwo = messageTwo.id; - expect(idOne, 'id set on message 1').to.be.ok; - expect(idTwo, 'id set on message 2').to.be.ok; - expect(idOne && idOne.split(':')[1]).to.equal('0', 'check zero-based index'); - expect(idTwo && idTwo.split(':')[1]).to.equal('1', 'check zero-based index'); - originalPublish.apply(channel, arguments); - } catch (err) { - done(err); - } + var messageOne = JSON.parse(requestBody)[0]; + var messageTwo = JSON.parse(requestBody)[1]; + expect(messageOne.name).to.equal('one', 'Outgoing message 1 interecepted'); + expect(messageTwo.name).to.equal('two', 'Outgoing message 2 interecepted'); + idOne = messageOne.id; + idTwo = messageTwo.id; + expect(idOne, 'id set on message 1').to.be.ok; + expect(idTwo, 'id set on message 2').to.be.ok; + expect(idOne && idOne.split(':')[1]).to.equal('0', 'check zero-based index'); + expect(idTwo && idTwo.split(':')[1]).to.equal('1', 'check zero-based index'); + originalPublish.apply(channel, arguments); }; Ably.Rest.Platform.Http.doUri = function (method, rest, uri, headers, body, params, callback) { originalDoUri(method, rest, uri, headers, body, params, function (err) { if (err) { - done(err); callback(err); return; } @@ -264,35 +169,19 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async Ably.Rest.Platform.Http.doUri = originalDoUri; }; - channel.publish([{ name: 'one' }, { name: 'two' }], function (err) { - if (err) { - done(err); - return; - } - - channel.history({ direction: 'forwards' }, function (err, page) { - if (err) { - done(err); - return; - } - /* TODO uncomment when idempotent publishing works on sandbox - * until then, test with ABLY_ENV=idempotent-dev - test.equal(page.items.length, 2, 'Only one message (with two items) should have been published'); - */ - try { - expect(page.items[0].id).to.equal(idOne, 'Check message id 1 preserved in history'); - expect(page.items[1].id).to.equal(idTwo, 'Check message id 1 preserved in history'); - done(); - } catch (err) { - done(err); - } - }); - }); + await channel.publish([{ name: 'one' }, { name: 'two' }]); + var page = await channel.history({ direction: 'forwards' }); + /* TODO uncomment when idempotent publishing works on sandbox + * until then, test with ABLY_ENV=idempotent-dev + * test.equal(page.items.length, 2, 'Only one message (with two items) should have been published'); + */ + expect(page.items[0].id).to.equal(idOne, 'Check message id 1 preserved in history'); + expect(page.items[1].id).to.equal(idTwo, 'Check message id 1 preserved in history'); }); if (typeof Promise !== undefined) { it('Rest publish promise', function (done) { - var rest = helper.AblyRest({ internal: { promises: true } }); + var rest = helper.AblyRestPromise({ internal: { promises: true } }); var channel = rest.channels.get('publishpromise'); channel @@ -318,31 +207,26 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); } - it('Rest publish params', function (done) { - var rest = helper.AblyRest(), + it('Rest publish params', async function () { + var rest = helper.AblyRestPromise(), channel = rest.channels.get('publish_params'); + var originalPublish = channel._publish; + /* Stub out _publish to check params */ - var i = 0; channel._publish = function (requestBody, headers, params) { - try { - expect(params && params.testParam).to.equal('testParamValue'); - } catch (err) { - done(err); - } - if (++i === 8) { - done(); - } + expect(params && params.testParam).to.equal('testParamValue'); + originalPublish.apply(channel, arguments); }; - channel.publish('foo', 'bar', { testParam: 'testParamValue' }); - channel.publish('foo', { data: 'data' }, { testParam: 'testParamValue' }); - channel.publish('foo', { data: 'data' }, { testParam: 'testParamValue' }, noop); - channel.publish('foo', null, { testParam: 'testParamValue' }); - channel.publish(null, 'foo', { testParam: 'testParamValue' }); - channel.publish({ name: 'foo', data: 'bar' }, { testParam: 'testParamValue' }); - channel.publish([{ name: 'foo', data: 'bar' }], { testParam: 'testParamValue' }); - channel.publish([{ name: 'foo', data: 'bar' }], { testParam: 'testParamValue' }, noop); + await channel.publish('foo', 'bar', { testParam: 'testParamValue' }); + await channel.publish('foo', { data: 'data' }, { testParam: 'testParamValue' }); + await channel.publish('foo', { data: 'data' }, { testParam: 'testParamValue' }, noop); + await channel.publish('foo', null, { testParam: 'testParamValue' }); + await channel.publish(null, 'foo', { testParam: 'testParamValue' }); + await channel.publish({ name: 'foo', data: 'bar' }, { testParam: 'testParamValue' }); + await channel.publish([{ name: 'foo', data: 'bar' }], { testParam: 'testParamValue' }); + await channel.publish([{ name: 'foo', data: 'bar' }], { testParam: 'testParamValue' }, noop); }); }); }); From 8b9e0f9364fed9a2501ace2466495dc7fcb3bad2 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Wed, 26 Apr 2023 18:29:38 +0100 Subject: [PATCH 11/30] test: remove legacy rest message promise test Co-authored-by: Lawrence Forooghian --- test/rest/message.test.js | 28 ---------------------------- 1 file changed, 28 deletions(-) diff --git a/test/rest/message.test.js b/test/rest/message.test.js index ca56219987..bb62a52791 100644 --- a/test/rest/message.test.js +++ b/test/rest/message.test.js @@ -179,34 +179,6 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async expect(page.items[1].id).to.equal(idTwo, 'Check message id 1 preserved in history'); }); - if (typeof Promise !== undefined) { - it('Rest publish promise', function (done) { - var rest = helper.AblyRestPromise({ internal: { promises: true } }); - var channel = rest.channels.get('publishpromise'); - - channel - .publish('name', 'data') - .then(function () { - return channel.history(); - }) - .then(function (page) { - var message = page.items[0]; - try { - expect( - message.data == 'data', - 'Check publish and history promise methods both worked as expected' - ).to.be.ok; - done(); - } catch (err) { - done(err); - } - }) - ['catch'](function (err) { - done(err); - }); - }); - } - it('Rest publish params', async function () { var rest = helper.AblyRestPromise(), channel = rest.channels.get('publish_params'); From d76a03fe6a5f683812fa8622ce9b0ad29600abdb Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 15:30:18 +0100 Subject: [PATCH 12/30] test: convert rest presence tests to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/presence.test.js | 161 ++++++++++++++----------------------- 1 file changed, 61 insertions(+), 100 deletions(-) diff --git a/test/rest/presence.test.js b/test/rest/presence.test.js index 4d36d63665..d21c22b50c 100644 --- a/test/rest/presence.test.js +++ b/test/rest/presence.test.js @@ -21,52 +21,44 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } describe('rest/presence', function () { + this.timeout(60 * 1000); + before(function (done) { helper.setupApp(function () { - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); cipherConfig = helper.getTestApp().cipherConfig; done(); }); }); function presence_simple(operation) { - return function (done) { - try { - var cipherParams = cipherParamsFromConfig(cipherConfig); - var channel = rest.channels.get('persisted:presence_fixtures', { cipher: cipherParams }); - channel.presence[operation](function (err, resultPage) { - if (err) { - done(err); - return; - } - var presenceMessages = resultPage.items; - expect(presenceMessages.length).to.equal(6, 'Verify correct number of messages found'); - if (presenceMessages.length != 6) { - console.log('presenceMessages: ', JSON.stringify(presenceMessages)); - } - var encodedMessage = arrFind(presenceMessages, function (msg) { - return msg.clientId == 'client_encoded'; - }); - var decodedMessage = arrFind(presenceMessages, function (msg) { - return msg.clientId == 'client_decoded'; - }); - var boolMessage = arrFind(presenceMessages, function (msg) { - return msg.clientId == 'client_bool'; - }); - var intMessage = arrFind(presenceMessages, function (msg) { - return msg.clientId == 'client_int'; - }); - expect(encodedMessage.data).to.deep.equal(decodedMessage.data, 'Verify message decoding works correctly'); - expect(encodedMessage.encoding).to.equal(null, 'Decoding should remove encoding field'); - expect(decodedMessage.encoding).to.equal(null, 'Decoding should remove encoding field'); - expect(boolMessage.data).to.equal('true', 'should not attempt to parse string data when no encoding field'); - expect(intMessage.data).to.equal('24', 'should not attempt to parse string data when no encoding field'); - expect(boolMessage.action).to.equal(operation === 'get' ? 'present' : 'enter', 'appropriate action'); - done(); - }); - } catch (err) { - done(err); + return async function () { + var cipherParams = cipherParamsFromConfig(cipherConfig); + var channel = rest.channels.get('persisted:presence_fixtures', { cipher: cipherParams }); + var resultPage = await channel.presence[operation](); + var presenceMessages = resultPage.items; + expect(presenceMessages.length).to.equal(6, 'Verify correct number of messages found'); + if (presenceMessages.length != 6) { + console.log('presenceMessages: ', JSON.stringify(presenceMessages)); } + var encodedMessage = arrFind(presenceMessages, function (msg) { + return msg.clientId == 'client_encoded'; + }); + var decodedMessage = arrFind(presenceMessages, function (msg) { + return msg.clientId == 'client_decoded'; + }); + var boolMessage = arrFind(presenceMessages, function (msg) { + return msg.clientId == 'client_bool'; + }); + var intMessage = arrFind(presenceMessages, function (msg) { + return msg.clientId == 'client_int'; + }); + expect(encodedMessage.data).to.deep.equal(decodedMessage.data, 'Verify message decoding works correctly'); + expect(encodedMessage.encoding).to.equal(null, 'Decoding should remove encoding field'); + expect(decodedMessage.encoding).to.equal(null, 'Decoding should remove encoding field'); + expect(boolMessage.data).to.equal('true', 'should not attempt to parse string data when no encoding field'); + expect(intMessage.data).to.equal('24', 'should not attempt to parse string data when no encoding field'); + expect(boolMessage.action).to.equal(operation === 'get' ? 'present' : 'enter', 'appropriate action'); }; } @@ -75,75 +67,44 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* Ensure that calling JSON strinfigy on the Presence object converts the action string value back to a numeric value which the API requires */ - it('Presence message JSON serialisation', function (done) { + it('Presence message JSON serialisation', async function () { var channel = rest.channels.get('persisted:presence_fixtures'); - channel.presence.get(function (err, resultPage) { - if (err) { - done(err); - return; - } - var presenceMessages = resultPage.items; - var presenceBool = arrFind(presenceMessages, function (msg) { - return msg.clientId == 'client_bool'; - }); - try { - expect(JSON.parse(JSON.stringify(presenceBool)).action).to.equal(1); // present - presenceBool.action = 'leave'; - expect(JSON.parse(JSON.stringify(presenceBool)).action).to.equal(3); // leave - done(); - } catch (err) { - done(err); - } + var resultPage = await channel.presence.get(); + var presenceMessages = resultPage.items; + var presenceBool = arrFind(presenceMessages, function (msg) { + return msg.clientId == 'client_bool'; }); + expect(JSON.parse(JSON.stringify(presenceBool)).action).to.equal(1); // present + presenceBool.action = 'leave'; + expect(JSON.parse(JSON.stringify(presenceBool)).action).to.equal(3); // leave }); - it('Presence get limits and filtering', function (done) { - try { - var channel = rest.channels.get('persisted:presence_fixtures'); + it('Presence get limits and filtering', async function () { + var channel = rest.channels.get('persisted:presence_fixtures'); - var tests = [ - // Result limit - function (cb) { - channel.presence.get({ limit: 3 }, function (err, resultPage) { - if (err) cb(err); - var presenceMessages = resultPage.items; - expect(presenceMessages.length).to.equal(3, 'Verify correct number of messages found'); - cb(); - }); - }, - // Filter by clientId - function (cb) { - channel.presence.get({ clientId: 'client_json' }, function (err, resultPage) { - if (err) cb(err); - var presenceMessages = resultPage.items; - expect(presenceMessages.length).to.equal(1, 'Verify correct number of messages found'); - cb(); - }); - }, - // Filter by connectionId - function (cb) { - channel.presence.get(function (err, resultPage) { - if (err) cb(err); - channel.presence.get({ connectionId: resultPage.items[0].connectionId }, function (err, resultPage) { - if (err) cb(err); - var presenceMessages = resultPage.items; - expect(presenceMessages.length).to.equal(6, 'Verify correct number of messages found'); - cb(); - }); - }); - }, - ]; + var tests = [ + // Result limit + async function () { + var resultPage = await channel.presence.get({ limit: 3 }); + var presenceMessages = resultPage.items; + expect(presenceMessages.length).to.equal(3, 'Verify correct number of messages found'); + }, + // Filter by clientId + async function (cb) { + var resultPage = await channel.presence.get({ clientId: 'client_json' }); + var presenceMessages = resultPage.items; + expect(presenceMessages.length).to.equal(1, 'Verify correct number of messages found'); + }, + // Filter by connectionId + async function () { + var resultPage = await channel.presence.get(); + var resultPage2 = await channel.presence.get({ connectionId: resultPage.items[0].connectionId }); + var presenceMessages = resultPage2.items; + expect(presenceMessages.length).to.equal(6, 'Verify correct number of messages found'); + }, + ]; - async.parallel(tests, function (err) { - if (err) { - done(err); - return; - } - done(); - }); - } catch (err) { - done(err); - } + await Promise.all(tests); }); if (typeof Promise !== 'undefined') { From 4ef4a989c2e1c24d7160662259f8a78f61ea7965 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 15:30:33 +0100 Subject: [PATCH 13/30] test: remove legacy rest presence promise test Co-authored-by: Lawrence Forooghian --- test/rest/presence.test.js | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/test/rest/presence.test.js b/test/rest/presence.test.js index d21c22b50c..7e7f519084 100644 --- a/test/rest/presence.test.js +++ b/test/rest/presence.test.js @@ -106,21 +106,5 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async await Promise.all(tests); }); - - if (typeof Promise !== 'undefined') { - it('presencePromise', function (done) { - var rest = helper.AblyRest({ internal: { promises: true } }); - var channel = rest.channels.get('some_channel'); - - channel.presence - .get() - .then(function () { - done(); - }) - ['catch'](function (err) { - done(err); - }); - }); - } }); }); From 844af87e202a0dd5456a70e575bf58ab678f1721 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 17:14:30 +0100 Subject: [PATCH 14/30] test: convert rest push tests to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/push.test.js | 467 ++++++++++++++--------------------------- 1 file changed, 154 insertions(+), 313 deletions(-) diff --git a/test/rest/push.test.js b/test/rest/push.test.js index ca75676c6b..44337ffc13 100644 --- a/test/rest/push.test.js +++ b/test/rest/push.test.js @@ -39,7 +39,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }); - it('Get subscriptions', function (done) { + it('Get subscriptions', async function () { var subscribes = []; var deletes = []; var subsByChannel = {}; @@ -51,58 +51,31 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } subsByChannel[sub.channel].push(sub); - var rest = helper.AblyRest({ clientId: sub.clientId }); - subscribes.push(function (callback) { - rest.push.admin.channelSubscriptions.save(sub, callback); - }); - deletes.push(function (callback) { - rest.push.admin.channelSubscriptions.remove(sub, callback); - }); + var rest = helper.AblyRestPromise({ clientId: sub.clientId }); + subscribes.push(() => rest.push.admin.channelSubscriptions.save(sub)); + deletes.push(() => rest.push.admin.channelSubscriptions.remove(sub)); })(i); } - var rest = helper.AblyRest(); - - async.series( - [ - function (callback) { - async.parallel(subscribes, callback); - }, - function (callback) { - rest.push.admin.channelSubscriptions.list({ channel: 'pushenabled:foo1' }, callback); - }, - function (callback) { - rest.push.admin.channelSubscriptions.list({ channel: 'pushenabled:foo2' }, callback); - }, - function (callback) { - async.parallel(deletes, callback); - }, - ], - function (err, result) { - if (err) { - done(err); - return; - } - try { - testIncludesUnordered(untyped(result[1].items), untyped(subsByChannel['pushenabled:foo1'])); - testIncludesUnordered(untyped(result[2].items), untyped(subsByChannel['pushenabled:foo2'])); - done(); - } catch (err) { - done(err); - } - } - ); + var rest = helper.AblyRestPromise(); + + await Promise.all(subscribes.map((sub) => sub())); + + var res1 = await rest.push.admin.channelSubscriptions.list({ channel: 'pushenabled:foo1' }); + var res2 = await rest.push.admin.channelSubscriptions.list({ channel: 'pushenabled:foo2' }); + + await Promise.all(deletes.map((del) => del())); + + testIncludesUnordered(untyped(res1.items), untyped(subsByChannel['pushenabled:foo1'])); + testIncludesUnordered(untyped(res2.items), untyped(subsByChannel['pushenabled:foo2'])); }); - it('Publish', function (done) { - var realtime = helper.AblyRealtime(); + it('Publish', async function () { + try { + var realtime = helper.AblyRealtimePromise(); - var channel = realtime.channels.get('pushenabled:foo'); - channel.attach(function (err) { - if (err) { - closeAndFinish(done, realtime, err); - return; - } + var channel = realtime.channels.get('pushenabled:foo'); + await channel.attach(); var pushPayload = { notification: { title: 'Test message', body: 'Test message body' }, @@ -117,29 +90,34 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async ablyUrl: baseUri, }; - channel.subscribe('__ably_push__', function (msg) { - var receivedPushPayload = JSON.parse(msg.data); - try { + var prom = new Promise(function (resolve, reject) { + channel.subscribe('__ably_push__', function (msg) { expect(receivedPushPayload.data).to.deep.equal(pushPayload.data); expect(receivedPushPayload.notification.title).to.deep.equal(pushPayload.notification.title); expect(receivedPushPayload.notification.body).to.deep.equal(pushPayload.notification.body); - closeAndFinish(done, realtime); - } catch (err) { - closeAndFinish(done, realtime, err); - } + resolve(); + }); }); - realtime.push.admin.publish(pushRecipient, pushPayload, function (err) { - if (err) { - closeAndFinish(done, realtime, err); - } - }); - }); + await realtime.push.admin.publish(pushRecipient, pushPayload); + realtime.close(); + } catch (err) { + realtime.close(); + throw err; + } }); if (typeof Promise !== 'undefined') { +<<<<<<< HEAD it('Publish promise', function (done) { var realtime = helper.AblyRealtime({ internal: { promises: true } }); +||||||| parent of 8295a1a8 (test: convert rest push tests to Promise API) + it('Publish promise', function (done) { + var realtime = helper.AblyRealtime({ promises: true }); +======= + it('Publish promise', async function () { + var realtime = helper.AblyRealtime({ promises: true }); +>>>>>>> 8295a1a8 (test: convert rest push tests to Promise API) var channelName = 'pushenabled:publish_promise'; var channel = realtime.channels.get(channelName); channel.attach(function (err) { @@ -185,43 +163,21 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); } - it('deviceRegistrations save', function (done) { - var rest = helper.AblyRest(); - - async.series( - [ - function (callback) { - rest.push.admin.deviceRegistrations.save(testDevice, callback); - }, - function (callback) { - rest.push.admin.deviceRegistrations.get(testDevice.id, callback); - }, - function (callback) { - rest.push.admin.deviceRegistrations.remove(testDevice.id, callback); - }, - ], - function (err, result) { - if (err) { - done(err); - return; - } - var saved = result[0]; - var got = result[1]; - try { - expect(got.push.state).to.equal('ACTIVE'); - delete got.metadata; // Ignore these properties for testing - delete got.push.state; - testIncludesUnordered(untyped(got), testDevice_withoutSecret); - testIncludesUnordered(untyped(saved), testDevice_withoutSecret); - done(); - } catch (err) { - done(err); - } - } - ); + it('deviceRegistrations save', async function () { + var rest = helper.AblyRestPromise(); + + var saved = await rest.push.admin.deviceRegistrations.save(testDevice); + var got = await rest.push.admin.deviceRegistrations.get(testDevice.id); + await rest.push.admin.deviceRegistrations.remove(testDevice.id); + + expect(got.push.state).to.equal('ACTIVE'); + delete got.metadata; // Ignore these properties for testing + delete got.push.state; + testIncludesUnordered(untyped(got), testDevice_withoutSecret); + testIncludesUnordered(untyped(saved), testDevice_withoutSecret); }); - it('deviceRegistrations get and list', function (done) { + it('deviceRegistrations get and list', async function () { var registrations = []; var deletes = []; var devices = []; @@ -262,113 +218,65 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async devices.push(device); devices_withoutSecret.push(device_withoutSecret); - var rest = helper.AblyRest({ clientId: device.clientId }); - registrations.push(function (callback) { - rest.push.admin.deviceRegistrations.save(device, callback); + var rest = helper.AblyRestPromise({ clientId: device.clientId }); + registrations.push(function () { + return rest.push.admin.deviceRegistrations.save(device); }); - deletes.push(function (callback) { - rest.push.admin.deviceRegistrations.remove('device' + (i + 1), callback); + deletes.push(function () { + return rest.push.admin.deviceRegistrations.remove('device' + (i + 1)); }); })(i); } - var rest = helper.AblyRest(); - - async.series( - [ - function (callback) { - async.parallel(registrations, callback); - }, - function (callback) { - rest.push.admin.deviceRegistrations.list(null, callback); - }, - function (callback) { - rest.push.admin.deviceRegistrations.list({ clientId: 'testClient1' }, callback); - }, - function (callback) { - rest.push.admin.deviceRegistrations.list({ clientId: 'testClient2' }, callback); - }, - function (callback) { - rest.push.admin.deviceRegistrations.get(devices[0].id, callback); - }, - function (callback) { - async.parallel( - [ - function (callback) { - rest.push.admin.deviceRegistrations.removeWhere({ clientId: 'testClient1' }, callback); - }, - function (callback) { - rest.push.admin.deviceRegistrations.removeWhere({ clientId: 'testClient2' }, callback); - }, - ], - callback - ); - }, - function (callback) { - async.parallel(deletes, callback); - }, - ], - function (err, result) { - if (err) { - done(err); - return; - } - try { - expect(numberOfDevices).to.equal(result[0].length); - testIncludesUnordered(untyped(result[1].items), untyped(devices_withoutSecret)); - testIncludesUnordered(untyped(result[2].items), untyped(devicesByClientId['testClient1'])); - testIncludesUnordered(untyped(result[3].items), untyped(devicesByClientId['testClient2'])); - testIncludesUnordered(untyped(result[4]), untyped(devices[0])); - done(); - } catch (err) { - done(err); - } - } - ); + var rest = helper.AblyRestPromise(); + + var res0 = await Promise.all(registrations.map((x) => x())); + var res1 = await rest.push.admin.deviceRegistrations.list(null); + var res2 = await rest.push.admin.deviceRegistrations.list({ clientId: 'testClient1' }); + var res3 = await rest.push.admin.deviceRegistrations.list({ clientId: 'testClient2' }); + var res4 = await rest.push.admin.deviceRegistrations.get(devices[0].id); + + await Promise.all([ + rest.push.admin.deviceRegistrations.removeWhere({ clientId: 'testClient1' }), + rest.push.admin.deviceRegistrations.removeWhere({ clientId: 'testClient2' }), + ]); + + await Promise.all(deletes.map((x) => x())); + + expect(numberOfDevices).to.equal(res0.length); + testIncludesUnordered(untyped(res1.items), untyped(devices_withoutSecret)); + testIncludesUnordered(untyped(res2.items), untyped(devicesByClientId['testClient1'])); + testIncludesUnordered(untyped(res3.items), untyped(devicesByClientId['testClient2'])); + testIncludesUnordered(untyped(res4), untyped(devices[0])); }); - it('deviceRegistrations remove removeWhere', function (done) { - var rest = helper.AblyRest(); - - async.series( - [ - function (callback) { - rest.push.admin.deviceRegistrations.save(testDevice, callback); - }, - function (callback) { - rest.push.admin.deviceRegistrations.remove(testDevice.id, callback); - }, - function (callback) { - rest.push.admin.deviceRegistrations.get(testDevice.id, function (err, result) { - expect(err && err.statusCode).to.equal(404, 'Check device reg not found after removal'); - callback(null); - }); - }, - function (callback) { - rest.push.admin.deviceRegistrations.save(testDevice, callback); - }, - function (callback) { - rest.push.admin.deviceRegistrations.removeWhere({ deviceId: testDevice.id }, callback); - }, - function (callback) { - rest.push.admin.deviceRegistrations.get(testDevice.id, function (err, result) { - expect(err && err.statusCode).to.equal(404, 'Check device reg not found after removal'); - callback(null); - }); - }, - ], - function (err, result) { - if (err) { - done(err); - } - done(); - } - ); + it('deviceRegistrations remove removeWhere', async function () { + var rest = helper.AblyRestPromise(); + + await rest.push.admin.deviceRegistrations.save(testDevice); + await rest.push.admin.deviceRegistrations.remove(testDevice.id); + + try { + await rest.push.admin.deviceRegistrations.get(testDevice.id); + expect.fail('Expected push.admin.deviceRegistrations.get() to throw'); + } catch (err) { + expect(err.statusCode).to.equal(404, 'Check device reg not found after removal'); + } + + await rest.push.admin.deviceRegistrations.save(testDevice); + await rest.push.admin.deviceRegistrations.removeWhere({ deviceId: testDevice.id }); + + try { + await rest.push.admin.deviceRegistrations.get(testDevice.id); + expect.fail('Expected push.admin.deviceRegistrations.get() to throw'); + } catch (err) { + expect(err.statusCode).to.equal(404, 'Check device reg not found after removal'); + } }); if (typeof Promise !== undefined) { it('deviceRegistrations promise', function (done) { - var rest = helper.AblyRest({ internal: { promises: true } }); + var rest = helper.AblyRestPromise({ internal: { promises: true } }); /* save */ rest.push.admin.deviceRegistrations @@ -404,43 +312,22 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); } - it('channelSubscriptions save', function (done) { - var rest = helper.AblyRest({ clientId: 'testClient' }); + it('channelSubscriptions save', async function () { + var rest = helper.AblyRestPromise({ clientId: 'testClient' }); var subscription = { clientId: 'testClient', channel: 'pushenabled:foo' }; - async.series( - [ - function (callback) { - rest.push.admin.channelSubscriptions.save(subscription, callback); - }, - function (callback) { - rest.push.admin.channelSubscriptions.list({ channel: 'pushenabled:foo' }, callback); - }, - function (callback) { - rest.push.admin.channelSubscriptions.remove(subscription, callback); - }, - ], - function (err, result) { - if (err) { - done(err); - return; - } - var saved = result[0]; - var sub = result[1].items[0]; - try { - expect(subscription.clientId).to.equal(saved.clientId); - expect(subscription.channel).to.equal(saved.channel); - expect(subscription.clientId).to.equal(sub.clientId); - expect(subscription.channel).to.equal(sub.channel); - done(); - } catch (err) { - done(err); - } - } - ); + var saved = await rest.push.admin.channelSubscriptions.save(subscription); + var result = await rest.push.admin.channelSubscriptions.list({ channel: 'pushenabled:foo' }); + var sub = result.items[0]; + await rest.push.admin.channelSubscriptions.remove(subscription); + + expect(subscription.clientId).to.equal(saved.clientId); + expect(subscription.channel).to.equal(saved.channel); + expect(subscription.clientId).to.equal(sub.clientId); + expect(subscription.channel).to.equal(sub.channel); }); - it('channelSubscriptions get', function (done) { + it('channelSubscriptions get', async function () { var subscribes = []; var deletes = []; var subsByChannel = {}; @@ -452,121 +339,75 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } subsByChannel[sub.channel].push(sub); - var rest = helper.AblyRest(); - subscribes.push(function (callback) { - rest.push.admin.channelSubscriptions.save(sub, callback); + var rest = helper.AblyRestPromise(); + subscribes.push(function () { + return rest.push.admin.channelSubscriptions.save(sub); }); - deletes.push(function (callback) { - rest.push.admin.channelSubscriptions.remove({ clientId: 'testClient' + i }, callback); + deletes.push(function () { + return rest.push.admin.channelSubscriptions.remove({ clientId: 'testClient' + i }); }); })(i); } - var rest = helper.AblyRest(); - - async.series( - [ - function (callback) { - async.parallel(subscribes, callback); - }, - function (callback) { - rest.push.admin.channelSubscriptions.list({ channel: 'pushenabled:foo1' }, callback); - }, - function (callback) { - rest.push.admin.channelSubscriptions.list({ channel: 'pushenabled:foo2' }, callback); - }, - function (callback) { - async.parallel(deletes, callback); - }, - ], - function (err, result) { - if (err) { - done(err); - return; - } - try { - testIncludesUnordered(untyped(result[1].items), untyped(subsByChannel['pushenabled:foo1'])); - testIncludesUnordered(untyped(result[2].items), untyped(subsByChannel['pushenabled:foo2'])); - done(); - } catch (err) { - done(err); - } - } - ); + var rest = helper.AblyRestPromise(); + + await Promise.all(subscribes.map((x) => x())); + + var res1 = await rest.push.admin.channelSubscriptions.list({ channel: 'pushenabled:foo1' }); + var res2 = await rest.push.admin.channelSubscriptions.list({ channel: 'pushenabled:foo2' }); + + await Promise.all(deletes.map((x) => x())); + + testIncludesUnordered(untyped(res1.items), untyped(subsByChannel['pushenabled:foo1'])); + testIncludesUnordered(untyped(res2.items), untyped(subsByChannel['pushenabled:foo2'])); }); - exports.push_channelSubscriptions_remove = function (test) { - var rest = helper.AblyRest({ clientId: 'testClient' }); + it('push_channelSubscriptions_remove', async function () { + var rest = helper.AblyRestPromise({ clientId: 'testClient' }); var subscription = { clientId: 'testClient', channel: 'pushenabled:foo' }; - async.series( - [ - function (callback) { - rest.push.admin.channelSubscriptions.save(subscription, callback); - }, - function (callback) { - rest.push.admin.channelSubscriptions.remove(subscription, callback); - }, - ], - function (err, result) { - if (err) { - test.ok(false, err.message); - test.done(); - return; - } - test.done(); - } - ); - }; + await rest.push.admin.channelSubscriptions.save(subscription); + await rest.push.admin.channelSubscriptions.remove(subscription); + }); - it('channelSubscriptions listChannels', function (done) { + it('channelSubscriptions listChannels', async function () { var subscribes = []; var deletes = []; for (var i = 0; i < 5; i++) { (function (i) { var sub = { channel: 'pushenabled:listChannels' + ((i % 2) + 1), clientId: 'testClient' + ((i % 3) + 1) }; - var rest = helper.AblyRest({ clientId: sub.clientId }); + var rest = helper.AblyRestPromise({ clientId: sub.clientId }); subscribes.push(function (callback) { - rest.push.admin.channelSubscriptions.save(sub, callback); + return rest.push.admin.channelSubscriptions.save(sub); }); - deletes.push(function (callback) { - rest.push.admin.channelSubscriptions.remove(sub, callback); + deletes.push(function () { + return rest.push.admin.channelSubscriptions.remove(sub); }); })(i); } - var rest = helper.AblyRest(); - - async.series( - [ - function (callback) { - async.parallel(subscribes, callback); - }, - function (callback) { - rest.push.admin.channelSubscriptions.listChannels(null, callback); - }, - function (callback) { - async.parallel(deletes, callback); - }, - ], - function (err, result) { - if (err) { - done(err); - return; - } - try { - testIncludesUnordered(['pushenabled:listChannels1', 'pushenabled:listChannels2'], result[1].items); - done(); - } catch (err) { - done(err); - } - } - ); + var rest = helper.AblyRestPromise(); + + await Promise.all(subscribes.map((x) => x())); + + var result = await rest.push.admin.channelSubscriptions.listChannels(null); + + await Promise.all(deletes.map((x) => x())); + + testIncludesUnordered(['pushenabled:listChannels1', 'pushenabled:listChannels2'], result.items); }); if (typeof Promise !== 'undefined') { +<<<<<<< HEAD it('channelSubscriptions promise', function (done) { var rest = helper.AblyRest({ internal: { promises: true } }); +||||||| parent of 8295a1a8 (test: convert rest push tests to Promise API) + it('channelSubscriptions promise', function (done) { + var rest = helper.AblyRest({ promises: true }); +======= + it('channelSubscriptions promise', async function () { + var rest = helper.AblyRestPromise({ promises: true }); +>>>>>>> 8295a1a8 (test: convert rest push tests to Promise API) var channelId = 'pushenabled:channelsubscriptions_promise'; var subscription = { clientId: 'testClient', channel: channelId }; From 469229b06e1a040bc3989c9cd784631be22cf322 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 17:15:05 +0100 Subject: [PATCH 15/30] test: remove legacy rest push promise tests Co-authored-by: Lawrence Forooghian --- test/rest/push.test.js | 134 ----------------------------------------- 1 file changed, 134 deletions(-) diff --git a/test/rest/push.test.js b/test/rest/push.test.js index 44337ffc13..5bfe1eb4e0 100644 --- a/test/rest/push.test.js +++ b/test/rest/push.test.js @@ -107,62 +107,6 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } }); - if (typeof Promise !== 'undefined') { -<<<<<<< HEAD - it('Publish promise', function (done) { - var realtime = helper.AblyRealtime({ internal: { promises: true } }); -||||||| parent of 8295a1a8 (test: convert rest push tests to Promise API) - it('Publish promise', function (done) { - var realtime = helper.AblyRealtime({ promises: true }); -======= - it('Publish promise', async function () { - var realtime = helper.AblyRealtime({ promises: true }); ->>>>>>> 8295a1a8 (test: convert rest push tests to Promise API) - var channelName = 'pushenabled:publish_promise'; - var channel = realtime.channels.get(channelName); - channel.attach(function (err) { - if (err) { - closeAndFinish(done, realtime, err); - return; - } - - var pushPayload = { - notification: { title: 'Test message', body: 'Test message body' }, - data: { foo: 'bar' }, - }; - - var baseUri = realtime.baseUri(Ably.Rest.Platform.Defaults.getHost(realtime.options)); - var pushRecipient = { - transportType: 'ablyChannel', - channel: 'pushenabled:foo', - ablyKey: realtime.options.key, - ablyUrl: baseUri, - }; - - channel.subscribe('__ably_push__', function (msg) { - var receivedPushPayload = JSON.parse(msg.data); - try { - expect(receivedPushPayload.data).to.deep.equal(pushPayload.data); - expect(receivedPushPayload.notification.title).to.deep.equal(pushPayload.notification.title); - expect(receivedPushPayload.notification.body).to.deep.equal(pushPayload.notification.body); - closeAndFinish(done, realtime, err); - } catch (err) { - done(err); - } - }); - - realtime.push.admin - .publish(pushRecipient, pushPayload) - .then(function () { - closeAndFinish(done, realtime); - }) - ['catch'](function (err) { - closeAndFinish(done, realtime, err); - }); - }); - }); - } - it('deviceRegistrations save', async function () { var rest = helper.AblyRestPromise(); @@ -274,44 +218,6 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } }); - if (typeof Promise !== undefined) { - it('deviceRegistrations promise', function (done) { - var rest = helper.AblyRestPromise({ internal: { promises: true } }); - - /* save */ - rest.push.admin.deviceRegistrations - .save(testDevice) - .then(function (saved) { - expect(saved.push.state).to.equal('ACTIVE'); - testIncludesUnordered(untyped(saved), testDevice_withoutSecret); - /* get */ - return rest.push.admin.deviceRegistrations.get(testDevice.id); - }) - .then(function (got) { - expect(got.push.state).to.equal('ACTIVE'); - delete got.metadata; // Ignore these properties for testing - delete got.push.state; - testIncludesUnordered(untyped(got), testDevice_withoutSecret); - /* list */ - return rest.push.admin.deviceRegistrations.list({ clientId: testDevice.clientId }); - }) - .then(function (result) { - expect(result.items.length).to.equal(1); - var got = result.items[0]; - expect(got.push.state).to.equal('ACTIVE'); - testIncludesUnordered(untyped(got), testDevice_withoutSecret); - /* remove */ - return rest.push.admin.deviceRegistrations.removeWhere({ deviceId: testDevice.id }); - }) - .then(function () { - done(); - }) - ['catch'](function (err) { - done(err); - }); - }); - } - it('channelSubscriptions save', async function () { var rest = helper.AblyRestPromise({ clientId: 'testClient' }); var subscription = { clientId: 'testClient', channel: 'pushenabled:foo' }; @@ -397,46 +303,6 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testIncludesUnordered(['pushenabled:listChannels1', 'pushenabled:listChannels2'], result.items); }); - if (typeof Promise !== 'undefined') { -<<<<<<< HEAD - it('channelSubscriptions promise', function (done) { - var rest = helper.AblyRest({ internal: { promises: true } }); -||||||| parent of 8295a1a8 (test: convert rest push tests to Promise API) - it('channelSubscriptions promise', function (done) { - var rest = helper.AblyRest({ promises: true }); -======= - it('channelSubscriptions promise', async function () { - var rest = helper.AblyRestPromise({ promises: true }); ->>>>>>> 8295a1a8 (test: convert rest push tests to Promise API) - var channelId = 'pushenabled:channelsubscriptions_promise'; - var subscription = { clientId: 'testClient', channel: channelId }; - - rest.push.admin.channelSubscriptions - .save(subscription) - .then(function (saved) { - expect(subscription.clientId).to.equal(saved.clientId); - expect(subscription.channel).to.equal(saved.channel); - return rest.push.admin.channelSubscriptions.list({ channel: channelId }); - }) - .then(function (result) { - var sub = result.items[0]; - expect(subscription.clientId).to.equal(sub.clientId); - expect(subscription.channel).to.equal(sub.channel); - return rest.push.admin.channelSubscriptions.listChannels(null); - }) - .then(function (result) { - expect(Utils.arrIn(result.items, channelId)).to.be.ok; - return rest.push.admin.channelSubscriptions.remove(subscription); - }) - .then(function () { - done(); - }) - ['catch'](function (err) { - done(err); - }); - }); - } - function untyped(x) { return JSON.parse(JSON.stringify(x)); } From 1e698e2e501694c34adaf6b6ee6cc23fc2eec2ea Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 17:21:52 +0100 Subject: [PATCH 16/30] test: convert rest request tests to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/request.test.js | 301 +++++++++++++------------------------- 1 file changed, 101 insertions(+), 200 deletions(-) diff --git a/test/rest/request.test.js b/test/rest/request.test.js index 6f931e0c90..d122ed430e 100644 --- a/test/rest/request.test.js +++ b/test/rest/request.test.js @@ -5,7 +5,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var expect = chai.expect; var utils = helper.Utils; var echoServerHost = 'echo.ably.io'; - var restTestOnJsonMsgpack = helper.restTestOnJsonMsgpack; + var restTestOnJsonMsgpackAsync = helper.restTestOnJsonMsgpackAsync; var Defaults = Ably.Rest.Platform.Defaults; describe('rest/request', function () { @@ -22,7 +22,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }); - restTestOnJsonMsgpack('request_version', function (done, rest) { + restTestOnJsonMsgpackAsync('request_version', function (rest) { const version = 150; // arbitrarily chosen function testRequestHandler(_, __, ___, headers) { @@ -37,239 +37,140 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async rest.http.do = testRequestHandler; - rest.request('get', '/time' /* arbitrarily chosen */, version, null, null, null, function (err, res) {}); + rest.request('get', '/time' /* arbitrarily chosen */, version, null, null, null); }); - restTestOnJsonMsgpack('request_time', function (done, rest) { - rest.request('get', '/time', Defaults.protocolVersion, null, null, null, function (err, res) { - try { - expect(!err, err && helper.displayError(err)).to.be.ok; - expect(res.statusCode).to.equal(200, 'Check statusCode'); - expect(res.success).to.equal(true, 'Check success'); - expect(utils.isArray(res.items), true, 'Check array returned').to.be.ok; - expect(res.items.length).to.equal(1, 'Check array was of length 1'); - done(); - } catch (err) { - done(err); - } - }); + restTestOnJsonMsgpackAsync('request_time', async function (rest) { + const res = await rest.request('get', '/time', Defaults.protocolVersion, null, null, null); + expect(res.statusCode).to.equal(200, 'Check statusCode'); + expect(res.success).to.equal(true, 'Check success'); + expect(utils.isArray(res.items), true, 'Check array returned').to.be.ok; + expect(res.items.length).to.equal(1, 'Check array was of length 1'); }); - restTestOnJsonMsgpack('request_404', function (done, rest) { + restTestOnJsonMsgpackAsync('request_404', async function (rest) { /* NB: can't just use /invalid or something as the CORS preflight will * fail. Need something superficially a valid path but where the actual * request fails */ - rest.request( + const res = await rest.request( 'get', '/keys/ablyjs.test/requestToken', Defaults.protocolVersion, null, null, - null, - function (err, res) { - try { - expect(err).to.equal( - null, - 'Check that we do not get an error response for a failure that returns an actual ably error code' - ); - expect(res.success).to.equal(false, 'Check res.success is false for a failure'); - expect(res.statusCode).to.equal(404, 'Check HPR.statusCode is 404'); - expect(res.errorCode).to.equal(40400, 'Check HPR.errorCode is 40400'); - expect(res.errorMessage, 'Check have an HPR.errorMessage').to.be.ok; - done(); - } catch (err) { - done(err); - } - } + null ); + expect(res.success).to.equal(false, 'Check res.success is false for a failure'); + expect(res.statusCode).to.equal(404, 'Check HPR.statusCode is 404'); + expect(res.errorCode).to.equal(40400, 'Check HPR.errorCode is 40400'); + expect(res.errorMessage, 'Check have an HPR.errorMessage').to.be.ok; }); /* With a network issue, should get an actual err, not an HttpPaginatedResponse with error members */ - it('request_network_error', function (done) { - rest = helper.AblyRest({ restHost: helper.unroutableAddress }); - rest.request('get', '/time', Defaults.protocolVersion, null, null, null, function (err, res) { - try { - expect(err, 'Check get an err').to.be.ok; - expect(!res, 'Check do not get a res').to.be.ok; - done(); - } catch (err) { - done(err); - } - }); + it('request_network_error', async function () { + rest = helper.AblyRestPromise({ restHost: helper.unroutableAddress }); + try { + var res = await rest.request('get', '/time', Defaults.protocolVersion, null, null, null); + } catch (err) { + expect(err, 'Check get an err').to.be.ok; + expect(!res, 'Check do not get a res').to.be.ok; + return; + } + expect.fail('Expected rest.request to throw'); }); /* Use the request feature to publish, then retrieve (one at a time), some messages */ - restTestOnJsonMsgpack('request_post_get_messages', function (done, rest, channelName) { + restTestOnJsonMsgpackAsync('request_post_get_messages', async function (rest, channelName) { var channelPath = '/channels/' + channelName + '/messages', msgone = { name: 'faye', data: 'whittaker' }, msgtwo = { name: 'martin', data: 'reed' }; - async.waterfall( - [ - function (cb) { - rest.request('post', channelPath, Defaults.protocolVersion, null, msgone, null, function (err, res) { - try { - expect(!err, err && helper.displayError(err)).to.be.ok; - expect(res.statusCode).to.equal(201, 'Check statusCode is 201'); - expect(res.success).to.equal(true, 'Check post was a success'); - expect(res.items && res.items.length).to.equal(1, 'Check number of results is as expected'); - cb(); - } catch (err) { - cb(err); - } - }); - }, - function (cb) { - rest.request('post', channelPath, Defaults.protocolVersion, null, msgtwo, null, function (err, res) { - try { - expect(!err, err && helper.displayError(err)).to.be.ok; - expect(res.statusCode).to.equal(201, 'Check statusCode is 201'); - expect(res.items && res.items.length).to.equal(1, 'Check number of results is as expected'); - cb(); - } catch (err) { - cb(err); - } - }); - }, - function (cb) { - rest.request( - 'get', - channelPath, - Defaults.protocolVersion, - { limit: 1, direction: 'forwards' }, - null, - null, - function (err, res) { - try { - expect(!err, err && helper.displayError(err)).to.be.ok; - expect(res.statusCode).to.equal(200, 'Check statusCode is 200'); - expect(res.items.length).to.equal(1, 'Check only one msg returned'); - expect(res.items[0].name).to.equal(msgone.name, 'Check name is as expected'); - expect(res.items[0].data).to.equal(msgone.data, 'Check data is as expected'); - expect(res.hasNext, 'Check hasNext is true').to.be.ok; - cb(null, res.next); - } catch (err) { - cb(err); - } - } - ); - }, - function (next, cb) { - next(function (err, res) { - try { - expect(!err, err && helper.displayError(err)).to.be.ok; - expect(res.statusCode).to.equal(200, 'Check statusCode is 200'); - expect(res.success).to.equal(true, 'Check success'); - expect(res.items.length).to.equal(1, 'Check only one msg returned'); - expect(res.items[0].name).to.equal(msgtwo.name, 'Check name is as expected'); - expect(res.items[0].data).to.equal(msgtwo.data, 'Check data is as expected'); - cb(); - } catch (err) { - cb(err); - } - }); - }, - function (cb) { - /* Finally check the messages the 'normal' way to make sure everything's as expected */ - rest.channels.get(channelName).history(function (err, res) { - try { - expect(!err, err && helper.displayError(err)).to.be.ok; - expect(res.items.length).to.equal(2, 'Check both msgs returned'); - expect(res.items[0].name).to.equal(msgtwo.name, 'Check name is as expected'); - expect(res.items[0].data).to.equal(msgtwo.data, 'Check data is as expected'); - cb(); - } catch (err) { - cb(err); - } - }); - }, - ], - function (err) { - if (err) { - done(err); - return; - } - done(); - } + var res = await rest.request('post', channelPath, Defaults.protocolVersion, null, msgone, null); + expect(res.statusCode).to.equal(201, 'Check statusCode is 201'); + expect(res.success).to.equal(true, 'Check post was a success'); + expect(res.items && res.items.length).to.equal(1, 'Check number of results is as expected'); + + res = await rest.request('post', channelPath, Defaults.protocolVersion, null, msgtwo, null); + expect(res.statusCode).to.equal(201, 'Check statusCode is 201'); + expect(res.items && res.items.length).to.equal(1, 'Check number of results is as expected'); + + res = await rest.request( + 'get', + channelPath, + Defaults.protocolVersion, + { limit: 1, direction: 'forwards' }, + null, + null ); + expect(res.statusCode).to.equal(200, 'Check statusCode is 200'); + expect(res.items.length).to.equal(1, 'Check only one msg returned'); + expect(res.items[0].name).to.equal(msgone.name, 'Check name is as expected'); + expect(res.items[0].data).to.equal(msgone.data, 'Check data is as expected'); + expect(res.hasNext, 'Check hasNext is true').to.be.ok; + + res = await res.next(); + expect(res.statusCode).to.equal(200, 'Check statusCode is 200'); + expect(res.success).to.equal(true, 'Check success'); + expect(res.items.length).to.equal(1, 'Check only one msg returned'); + expect(res.items[0].name).to.equal(msgtwo.name, 'Check name is as expected'); + expect(res.items[0].data).to.equal(msgtwo.data, 'Check data is as expected'); + + /* Finally check the messages the 'normal' way to make sure everything's as expected */ + res = await rest.channels.get(channelName).history(); + expect(res.items.length).to.equal(2, 'Check both msgs returned'); + expect(res.items[0].name).to.equal(msgtwo.name, 'Check name is as expected'); + expect(res.items[0].data).to.equal(msgtwo.data, 'Check data is as expected'); }); - restTestOnJsonMsgpack('request_batch_api_success', function (done, rest, name) { + restTestOnJsonMsgpackAsync('request_batch_api_success', async function (rest, name) { var body = { channels: [name + '1', name + '2'], messages: { data: 'foo' } }; - rest.request('POST', '/messages', Defaults.protocolVersion, {}, body, {}, function (err, res) { - try { - expect(err).to.equal(null, 'Check that we do not get an error response for a success'); - expect(res.success).to.equal(true, 'Check res.success is true for a success'); - expect(res.statusCode).to.equal(201, 'Check res.statusCode is 201 for a success'); - expect(res.errorCode).to.equal(null, 'Check res.errorCode is null for a success'); - expect(res.errorMessage).to.equal(null, 'Check res.errorMessage is null for a success'); - - expect( - !res.items[0].batchResponse, - 'Check no batchResponse, since items is now just a flat array of channel responses' - ).to.be.ok; - expect(res.items.length).to.equal(2, 'Verify batched response includes response for each channel'); - expect(!res.items[0].error, 'Verify channel1 response is not an error').to.be.ok; - expect(res.items[0].channel).to.equal(name + '1', 'Verify channel1 response includes correct channel'); - expect(!res.items[1].error, 'Verify channel2 response is not an error').to.be.ok; - expect(res.items[1].channel).to.equal(name + '2', 'Verify channel2 response includes correct channel'); - done(); - } catch (err) { - done(err); - } - }); + const res = await rest.request('POST', '/messages', Defaults.protocolVersion, {}, body, {}); + expect(res.success).to.equal(true, 'Check res.success is true for a success'); + expect(res.statusCode).to.equal(201, 'Check res.statusCode is 201 for a success'); + expect(res.errorCode).to.equal(null, 'Check res.errorCode is null for a success'); + expect(res.errorMessage).to.equal(null, 'Check res.errorMessage is null for a success'); + + expect( + !res.items[0].batchResponse, + 'Check no batchResponse, since items is now just a flat array of channel responses' + ).to.be.ok; + expect(res.items.length).to.equal(2, 'Verify batched response includes response for each channel'); + expect(!res.items[0].error, 'Verify channel1 response is not an error').to.be.ok; + expect(res.items[0].channel).to.equal(name + '1', 'Verify channel1 response includes correct channel'); + expect(!res.items[1].error, 'Verify channel2 response is not an error').to.be.ok; + expect(res.items[1].channel).to.equal(name + '2', 'Verify channel2 response includes correct channel'); }); - restTestOnJsonMsgpack.skip('request_batch_api_partial_success', function (done, rest, name) { + restTestOnJsonMsgpackAsync.skip('request_batch_api_partial_success', async function (rest, name) { var body = { channels: [name, '[invalid', ''], messages: { data: 'foo' } }; - rest.request('POST', '/messages', Defaults.protocolVersion, {}, body, {}, function (err, res) { - try { - expect(err).to.equal(null, 'Check that we do not get an error response for a partial success'); - expect(res.success).to.equal(false, 'Check res.success is false for a partial failure'); - expect(res.statusCode).to.equal(400, 'Check HPR.statusCode is 400 for a partial failure'); - expect(res.errorCode).to.equal(40020, 'Check HPR.errorCode is 40020 for a partial failure'); - expect(res.errorMessage, 'Check have an HPR.errorMessage').to.be.ok; - - var response = res.items[0]; - expect(response.error.code).to.equal(40020, 'Verify response has an errorCode'); - expect(response.batchResponse.length).to.equal( - 3, - 'Verify batched response includes response for each channel' - ); - expect(response.batchResponse[0].channel).to.equal(name, 'Verify channel1 response includes correct channel'); - expect(!response.batchResponse[0].error, 'Verify first channel response is not an error').to.be.ok; - expect(response.batchResponse[1].error.code).to.equal( - 40010, - 'Verify [invalid response includes an error with the right code' - ); - expect(response.batchResponse[2].error.code).to.equal( - 40010, - 'Verify empty channel response includes an error with the right code' - ); - done(); - } catch (err) { - done(err); - } - }); + var res = await rest.request('POST', '/messages', Defaults.protocolVersion, {}, body, {}); + expect(res.success).to.equal(false, 'Check res.success is false for a partial failure'); + expect(res.statusCode).to.equal(400, 'Check HPR.statusCode is 400 for a partial failure'); + expect(res.errorCode).to.equal(40020, 'Check HPR.errorCode is 40020 for a partial failure'); + expect(res.errorMessage, 'Check have an HPR.errorMessage').to.be.ok; + + var response = res.items[0]; + expect(response.error.code).to.equal(40020, 'Verify response has an errorCode'); + expect(response.batchResponse.length).to.equal(3, 'Verify batched response includes response for each channel'); + expect(response.batchResponse[0].channel).to.equal(name, 'Verify channel1 response includes correct channel'); + expect(!response.batchResponse[0].error, 'Verify first channel response is not an error').to.be.ok; + expect(response.batchResponse[1].error.code).to.equal( + 40010, + 'Verify [invalid response includes an error with the right code' + ); + expect(response.batchResponse[2].error.code).to.equal( + 40010, + 'Verify empty channel response includes an error with the right code' + ); }); utils.arrForEach(['put', 'patch', 'delete'], function (method) { - it('check' + method, function (done) { - var restEcho = helper.AblyRest({ useBinaryProtocol: false, restHost: echoServerHost, tls: true }); - restEcho.request(method, '/methods', Defaults.protocolVersion, {}, {}, {}, function (err, res) { - if (err) { - done(err); - } else { - try { - expect(res.items[0] && res.items[0].method).to.equal(method); - done(); - } catch (err) { - done(err); - } - } - }); + it('check' + method, async function () { + var restEcho = helper.AblyRestPromise({ 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); }); }); From b69496369e8a577a242c192a65f5b30f23835166 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 17:22:17 +0100 Subject: [PATCH 17/30] test: remove legacy rest request promise test Co-authored-by: Lawrence Forooghian --- test/rest/request.test.js | 21 +-------------------- 1 file changed, 1 insertion(+), 20 deletions(-) diff --git a/test/rest/request.test.js b/test/rest/request.test.js index d122ed430e..8f1279f22d 100644 --- a/test/rest/request.test.js +++ b/test/rest/request.test.js @@ -17,7 +17,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async done(err); return; } - rest = helper.AblyRest({ useBinaryProtocol: false }); + rest = helper.AblyRestPromise({ useBinaryProtocol: false }); done(); }); }); @@ -173,24 +173,5 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async expect(res.items[0] && res.items[0].method).to.equal(method); }); }); - - if (typeof Promise !== 'undefined') { - it('request_promise', function (done) { - var client = helper.AblyRest({ internal: { promises: true } }); - - client - .request('get', '/time', Defaults.protocolVersion, null, null, null) - .then(function (res) { - expect(res.statusCode).to.equal(200, 'Check statusCode'); - expect(res.success).to.equal(true, 'Check success'); - expect(utils.isArray(res.items), true, 'Check array returned').to.be.ok; - expect(res.items.length).to.equal(1, 'Check array was of length 1'); - done(); - }) - ['catch'](function (err) { - done(err); - }); - }); - } }); }); From f8829974b49320b9d0bf597e90d8f2e759d473d0 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 17:30:45 +0100 Subject: [PATCH 18/30] test: convert rest stats tests to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/stats.test.js | 707 ++++++++++++++-------------------------- 1 file changed, 241 insertions(+), 466 deletions(-) diff --git a/test/rest/stats.test.js b/test/rest/stats.test.js index b9a3c04a26..d3e8b64b8e 100644 --- a/test/rest/stats.test.js +++ b/test/rest/stats.test.js @@ -64,7 +64,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 helper.setupApp(true, function () { - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); helper.createStats(helper.getTestApp(), statsFixtures, function (err) { if (err) { done(err); @@ -79,525 +79,300 @@ define(['shared_helper', 'chai'], function (helper, chai) { * Using an interval ID string format, check minute-level inbound and outbound stats match fixture data (forwards) * @spec : (RSC6b4) */ - it('appstats_minute0', function (done) { - rest.stats( - { - start: lastYear + '-02-03:15:03', - end: lastYear + '-02-03:15:05', - direction: 'forwards', - }, - function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length).to.equal(3, 'Verify 3 stat records found'); - - var totalInbound = 0, - totalOutbound = 0; - for (var i = 0; i < stats.length; i++) { - totalInbound += stats[i].inbound.all.messages.count; - totalOutbound += stats[i].outbound.all.messages.count; - } - - expect(totalInbound).to.equal(50 + 60 + 70, 'Verify all inbound messages found'); - expect(totalOutbound).to.equal(20 + 10 + 40, 'Verify all outbound messages found'); - done(); - } catch (err) { - done(err); - } - } - ); + it('appstats_minute0', async function () { + var page = await rest.stats({ + start: lastYear + '-02-03:15:03', + end: lastYear + '-02-03:15:05', + direction: 'forwards', + }); + var stats = page.items; + expect(stats.length).to.equal(3, 'Verify 3 stat records found'); + + var totalInbound = 0, + totalOutbound = 0; + for (var i = 0; i < stats.length; i++) { + totalInbound += stats[i].inbound.all.messages.count; + totalOutbound += stats[i].outbound.all.messages.count; + } + + expect(totalInbound).to.equal(50 + 60 + 70, 'Verify all inbound messages found'); + expect(totalOutbound).to.equal(20 + 10 + 40, 'Verify all outbound messages found'); }); /** * Using milliseconds since epoch, check minute-level inbound and outbound stats match fixture data (forwards) * @spec : (RSC6b4) */ - it('appstats_minute1', function (done) { - rest.stats( - { - start: firstIntervalEpoch, - end: secondIntervalEpoch, - direction: 'forwards', - }, - function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length).to.equal(3, 'Verify 3 stat records found'); - - var totalInbound = 0, - totalOutbound = 0; - for (var i = 0; i < stats.length; i++) { - totalInbound += stats[i].inbound.all.messages.count; - totalOutbound += stats[i].outbound.all.messages.count; - } - - expect(totalInbound).to.equal(50 + 60 + 70, 'Verify all inbound messages found'); - expect(totalOutbound).to.equal(20 + 10 + 40, 'Verify all outbound messages found'); - done(); - } catch (err) { - done(err); - } - } - ); + it('appstats_minute1', async function () { + var page = await rest.stats({ + start: firstIntervalEpoch, + end: secondIntervalEpoch, + direction: 'forwards', + }); + var stats = page.items; + expect(stats.length).to.equal(3, 'Verify 3 stat records found'); + + var totalInbound = 0, + totalOutbound = 0; + for (var i = 0; i < stats.length; i++) { + totalInbound += stats[i].inbound.all.messages.count; + totalOutbound += stats[i].outbound.all.messages.count; + } + + expect(totalInbound).to.equal(50 + 60 + 70, 'Verify all inbound messages found'); + expect(totalOutbound).to.equal(20 + 10 + 40, 'Verify all outbound messages found'); }); /** * Check hour-level inbound and outbound stats match fixture data (forwards) * @spec : (RSC6b4) */ - it('appstats_hour0', function (done) { - rest.stats( - { - start: lastYear + '-02-03:15', - end: lastYear + '-02-03:18', - direction: 'forwards', - by: 'hour', - }, - function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length).to.equal(1, 'Verify 1 stat record found'); - - var totalInbound = 0, - totalOutbound = 0; - for (var i = 0; i < stats.length; i++) { - totalInbound += stats[i].inbound.all.messages.count; - totalOutbound += stats[i].outbound.all.messages.count; - } - - expect(totalInbound).to.equal(50 + 60 + 70, 'Verify all inbound messages found'); - expect(totalOutbound).to.equal(20 + 10 + 40, 'Verify all outbound messages found'); - done(); - } catch (err) { - done(err); - } - } - ); + it('appstats_hour0', async function () { + var page = await rest.stats({ + start: lastYear + '-02-03:15', + end: lastYear + '-02-03:18', + direction: 'forwards', + by: 'hour', + }); + var stats = page.items; + expect(stats.length).to.equal(1, 'Verify 1 stat record found'); + + var totalInbound = 0, + totalOutbound = 0; + for (var i = 0; i < stats.length; i++) { + totalInbound += stats[i].inbound.all.messages.count; + totalOutbound += stats[i].outbound.all.messages.count; + } + + expect(totalInbound).to.equal(50 + 60 + 70, 'Verify all inbound messages found'); + expect(totalOutbound).to.equal(20 + 10 + 40, 'Verify all outbound messages found'); }); /** * Check day-level stats exist (forwards) * @spec : (RSC6b4) */ - it.skip('appstats_day0', function (done) { - rest.stats( - { - end: lastYear + '-02-03', - direction: 'forwards', - by: 'day', - }, - function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length == 1, 'Verify 1 stat records found').to.be.ok; - - var totalInbound = 0, - totalOutbound = 0; - for (var i = 0; i < stats.length; i++) { - totalInbound += stats[i].inbound.all.messages.count; - totalOutbound += stats[i].outbound.all.messages.count; - } - - expect(totalInbound).to.equal(50 + 60 + 70, 'Verify all inbound messages found'); - expect(totalOutbound).to.equal(20 + 10 + 40, 'Verify all outbound messages found'); - done(); - } catch (err) { - done(err); - } - } - ); + it.skip('appstats_day0', async function () { + var page = await rest.stats({ + end: lastYear + '-02-03', + direction: 'forwards', + by: 'day', + }); + var stats = page.items; + expect(stats.length == 1, 'Verify 1 stat records found').to.be.ok; + + var totalInbound = 0, + totalOutbound = 0; + for (var i = 0; i < stats.length; i++) { + totalInbound += stats[i].inbound.all.messages.count; + totalOutbound += stats[i].outbound.all.messages.count; + } + + expect(totalInbound).to.equal(50 + 60 + 70, 'Verify all inbound messages found'); + expect(totalOutbound).to.equal(20 + 10 + 40, 'Verify all outbound messages found'); }); /** * Check month-level stats exist (forwards) * @spec : (RSC6b4) */ - it.skip('appstats_month0', function (done) { - rest.stats( - { - end: lastYear + '-02', - direction: 'forwards', - by: 'month', - }, - function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length == 1, 'Verify 1 stat records found').to.be.ok; - - var totalInbound = 0, - totalOutbound = 0; - for (var i = 0; i < stats.length; i++) { - totalInbound += stats[i].inbound.all.messages.count; - totalOutbound += stats[i].outbound.all.messages.count; - } - - expect(totalInbound).to.equal(50 + 60 + 70, 'Verify all inbound messages found'); - expect(totalOutbound).to.equal(20 + 10 + 40, 'Verify all outbound messages found'); - done(); - } catch (err) { - done(err); - } - } - ); + it.skip('appstats_month0', async function () { + var page = await rest.stats({ + end: lastYear + '-02', + direction: 'forwards', + by: 'month', + }); + var stats = page.items; + expect(stats.length == 1, 'Verify 1 stat records found').to.be.ok; + + var totalInbound = 0, + totalOutbound = 0; + for (var i = 0; i < stats.length; i++) { + totalInbound += stats[i].inbound.all.messages.count; + totalOutbound += stats[i].outbound.all.messages.count; + } + + expect(totalInbound).to.equal(50 + 60 + 70, 'Verify all inbound messages found'); + expect(totalOutbound).to.equal(20 + 10 + 40, 'Verify all outbound messages found'); }); /** * Check limit query param (backwards) * @spec : (RSC6b3) */ - it('appstats_limit_backwards', function (done) { - rest.stats( - { - end: lastYear + '-02-03:15:04', - direction: 'backwards', - limit: 1, - }, - function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length == 1, 'Verify 1 stat records found').to.be.ok; - - var totalInbound = 0, - totalOutbound = 0; - for (var i = 0; i < stats.length; i++) { - totalInbound += stats[i].inbound.all.messages.count; - totalOutbound += stats[i].outbound.all.messages.count; - } - - expect(totalInbound).to.equal(60, 'Verify all inbound messages found'); - expect(totalOutbound).to.equal(10, 'Verify all outbound messages found'); - done(); - } catch (err) { - done(err); - } - } - ); + it('appstats_limit_backwards', async function () { + var page = await rest.stats({ + end: lastYear + '-02-03:15:04', + direction: 'backwards', + limit: 1, + }); + var stats = page.items; + expect(stats.length == 1, 'Verify 1 stat records found').to.be.ok; + + var totalInbound = 0, + totalOutbound = 0; + for (var i = 0; i < stats.length; i++) { + totalInbound += stats[i].inbound.all.messages.count; + totalOutbound += stats[i].outbound.all.messages.count; + } + + expect(totalInbound).to.equal(60, 'Verify all inbound messages found'); + expect(totalOutbound).to.equal(10, 'Verify all outbound messages found'); }); /** * Check limit query param (forwards) * @spec : (RSC6b3) */ - it('appstats_limit_forwards', function (done) { - rest.stats( - { - end: lastYear + '-02-03:15:04', - direction: 'forwards', - limit: 1, - }, - function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length == 1, 'Verify 1 stat records found').to.be.ok; - - var totalInbound = 0, - totalOutbound = 0; - for (var i = 0; i < stats.length; i++) { - totalInbound += stats[i].inbound.all.messages.count; - totalOutbound += stats[i].outbound.all.messages.count; - } - - expect(totalInbound).to.equal(50, 'Verify all inbound messages found'); - expect(totalOutbound).to.equal(20, 'Verify all outbound messages found'); - done(); - } catch (err) { - done(err); - } - } - ); + it('appstats_limit_forwards', async function () { + var page = await rest.stats({ + end: lastYear + '-02-03:15:04', + direction: 'forwards', + limit: 1, + }); + var stats = page.items; + expect(stats.length == 1, 'Verify 1 stat records found').to.be.ok; + + var totalInbound = 0, + totalOutbound = 0; + for (var i = 0; i < stats.length; i++) { + totalInbound += stats[i].inbound.all.messages.count; + totalOutbound += stats[i].outbound.all.messages.count; + } + + expect(totalInbound).to.equal(50, 'Verify all inbound messages found'); + expect(totalOutbound).to.equal(20, 'Verify all outbound messages found'); }); /** * Check query pagination (backwards) * @spec : (RSC6b2) */ - it('appstats_pagination_backwards', function (done) { - rest.stats( - { - end: lastYear + '-02-03:15:05', - direction: 'backwards', - limit: 1, - }, - function (err, page) { - if (err) { - done(err); - return; - } - - var stats = page.items; - expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; - var totalData = 0; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(7000, 'Verify all published message data found'); - - /* get next page */ - expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; - page.next(function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; - var totalData = 0; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(6000, 'Verify all published message data found'); - - /* get next page */ - expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; - } catch (err) { - done(err); - return; - } - page.next(function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; - var totalData = 0; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(5000, 'Verify all published message data found'); - - /* verify no further pages */ - expect(page.isLast(), 'Verify last page').to.be.ok; - } catch (err) { - done(err); - return; - } - - page.first(function (err, page) { - if (err) { - done(err); - return; - } - try { - var totalData = 0; - var stats = page.items; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(7000, 'Verify all published message data found'); - - /* that's it */ - done(); - } catch (err) { - done(err); - return; - } - }); - }); - }); - } - ); + it('appstats_pagination_backwards', async function () { + var page = await rest.stats({ + end: lastYear + '-02-03:15:05', + direction: 'backwards', + limit: 1, + }); + var stats = page.items; + expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; + var totalData = 0; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(7000, 'Verify all published message data found'); + + /* get next page */ + expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; + var page = await page.next(); + var stats = page.items; + expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; + var totalData = 0; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(6000, 'Verify all published message data found'); + + /* get next page */ + expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; + var page = await page.next(); + var stats = page.items; + expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; + var totalData = 0; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(5000, 'Verify all published message data found'); + + /* verify no further pages */ + expect(page.isLast(), 'Verify last page').to.be.ok; + + var page = await page.first(); + var totalData = 0; + var stats = page.items; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(7000, 'Verify all published message data found'); }); /** * Check query pagination (forwards) * @spec : (RSC6b2) */ - it('appstats_pagination_forwards', function (done) { - rest.stats( - { - end: lastYear + '-02-03:15:05', - direction: 'forwards', - limit: 1, - }, - function (err, page) { - if (err) { - done(err); - return; - } - - try { - var stats = page.items; - expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; - var totalData = 0; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(5000, 'Verify all published message data found'); - - /* get next page */ - expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; - } catch (err) { - done(err); - return; - } - page.next(function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; - var totalData = 0; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(6000, 'Verify all published message data found'); - - /* get next page */ - expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; - } catch (err) { - done(err); - return; - } - page.next(function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; - var totalData = 0; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(7000, 'Verify all published message data found'); - - /* verify no further pages */ - expect(page.isLast(), 'Verify last page').to.be.ok; - } catch (err) { - done(err); - return; - } - - page.first(function (err, page) { - if (err) { - done(err); - return; - } - try { - var totalData = 0; - var stats = page.items; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(5000, 'Verify all published message data found'); - - /* that's it */ - done(); - } catch (err) { - done(err); - } - }); - }); - }); - } - ); + it('appstats_pagination_forwards', async function () { + var page = await rest.stats({ + end: lastYear + '-02-03:15:05', + direction: 'forwards', + limit: 1, + }); + var stats = page.items; + expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; + var totalData = 0; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(5000, 'Verify all published message data found'); + + /* get next page */ + expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; + var page = await page.next(); + var stats = page.items; + expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; + var totalData = 0; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(6000, 'Verify all published message data found'); + + /* get next page */ + expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; + var page = await page.next(); + var stats = page.items; + expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; + var totalData = 0; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(7000, 'Verify all published message data found'); + + /* verify no further pages */ + expect(page.isLast(), 'Verify last page').to.be.ok; + + var page = await page.first(); + var totalData = 0; + var stats = page.items; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(5000, 'Verify all published message data found'); }); /** * Check query pagination omitted (defaults to backwards) * @spec : (RSC6b2) */ - it('appstats_pagination_omitted', function (done) { - rest.stats( - { - end: lastYear + '-02-03:15:05', - limit: 1, - }, - function (err, page) { - if (err) { - done(err); - return; - } - - try { - var stats = page.items; - expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; - var totalData = 0; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(7000, 'Verify all published message data found'); - - /* get next page */ - expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; - } catch (err) { - done(err); - return; - } - page.next(function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; - var totalData = 0; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(6000, 'Verify all published message data found'); - - /* get next page */ - expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; - } catch (err) { - done(err); - return; - } - page.next(function (err, page) { - if (err) { - done(err); - return; - } - try { - var stats = page.items; - expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; - var totalData = 0; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(5000, 'Verify all published message data found'); - - /* verify no further pages */ - expect(page.isLast(), 'Verify last page').to.be.ok; - } catch (err) { - done(err); - return; - } - - page.first(function (err, page) { - if (err) { - done(err); - return; - } - try { - var totalData = 0; - var stats = page.items; - for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; - expect(totalData).to.equal(7000, 'Verify all published message data found'); - - /* that's it */ - done(); - } catch (err) { - done(err); - } - }); - }); - }); - } - ); + it('appstats_pagination_omitted', async function () { + var page = await rest.stats({ + end: lastYear + '-02-03:15:05', + limit: 1, + }); + var stats = page.items; + expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; + var totalData = 0; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(7000, 'Verify all published message data found'); + + /* get next page */ + expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; + var page = await page.next(); + var stats = page.items; + expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; + var totalData = 0; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(6000, 'Verify all published message data found'); + + /* get next page */ + expect(page.hasNext(), 'Verify next page rel link present').to.be.ok; + var page = await page.next(); + var stats = page.items; + expect(stats.length == 1, 'Verify exactly one stats record found').to.be.ok; + var totalData = 0; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(5000, 'Verify all published message data found'); + + /* verify no further pages */ + expect(page.isLast(), 'Verify last page').to.be.ok; + + var page = await page.first(); + var totalData = 0; + var stats = page.items; + for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; + expect(totalData).to.equal(7000, 'Verify all published message data found'); }); if (typeof Promise !== 'undefined') { From 2448be717c3384605c65b110a9f1c762eeac29ef Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 17:31:04 +0100 Subject: [PATCH 19/30] test: remove legacy rest stats promise test Co-authored-by: Lawrence Forooghian --- test/rest/stats.test.js | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/test/rest/stats.test.js b/test/rest/stats.test.js index d3e8b64b8e..b733be0c45 100644 --- a/test/rest/stats.test.js +++ b/test/rest/stats.test.js @@ -374,21 +374,5 @@ define(['shared_helper', 'chai'], function (helper, chai) { for (var i = 0; i < stats.length; i++) totalData += stats[i].inbound.all.messages.data; expect(totalData).to.equal(7000, 'Verify all published message data found'); }); - - if (typeof Promise !== 'undefined') { - it('stats_promise', function (done) { - var client = helper.AblyRest({ internal: { promises: true } }); - - client - .stats() - .then(function () { - console.log('here'); - done(); - }) - ['catch'](function (err) { - done(err); - }); - }); - } }); }); From 44808edb31ae0dc9b18e7cf46c89ecfa62115353 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 17:32:10 +0100 Subject: [PATCH 20/30] test: convert rest status test to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/status.test.js | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/test/rest/status.test.js b/test/rest/status.test.js index 91cc27b6e0..ef36d1f632 100644 --- a/test/rest/status.test.js +++ b/test/rest/status.test.js @@ -15,29 +15,23 @@ define(['shared_helper', 'chai'], function (helper, chai) { done(err); return; } - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); done(); }); }); - it('status0', function (done) { + it('status0', async function () { var channel = rest.channels.get('status0'); - channel.status(function (err, channelDetails) { - try { - expect(channelDetails.channelId).to.equal('status0'); - expect(channelDetails.status.isActive).to.be.a('boolean'); - var metrics = channelDetails.status.occupancy.metrics; - expect(metrics.connections).to.be.a('number'); - expect(metrics.presenceConnections).to.be.a('number'); - expect(metrics.presenceMembers).to.be.a('number'); - expect(metrics.presenceSubscribers).to.be.a('number'); - expect(metrics.publishers).to.be.a('number'); - expect(metrics.subscribers).to.be.a('number'); - done(); - } catch (err) { - done(err); - } - }); + var channelDetails = await channel.status(); + expect(channelDetails.channelId).to.equal('status0'); + expect(channelDetails.status.isActive).to.be.a('boolean'); + var metrics = channelDetails.status.occupancy.metrics; + expect(metrics.connections).to.be.a('number'); + expect(metrics.presenceConnections).to.be.a('number'); + expect(metrics.presenceMembers).to.be.a('number'); + expect(metrics.presenceSubscribers).to.be.a('number'); + expect(metrics.publishers).to.be.a('number'); + expect(metrics.subscribers).to.be.a('number'); }); if (typeof Promise !== 'undefined') { From e9081a30aca92168b86876a7aef15a21025abfc0 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 17:32:34 +0100 Subject: [PATCH 21/30] test: remove legacy rest status promise test Co-authored-by: Lawrence Forooghian --- test/rest/status.test.js | 28 ---------------------------- 1 file changed, 28 deletions(-) diff --git a/test/rest/status.test.js b/test/rest/status.test.js index ef36d1f632..91063551e0 100644 --- a/test/rest/status.test.js +++ b/test/rest/status.test.js @@ -33,33 +33,5 @@ define(['shared_helper', 'chai'], function (helper, chai) { expect(metrics.publishers).to.be.a('number'); expect(metrics.subscribers).to.be.a('number'); }); - - if (typeof Promise !== 'undefined') { - it('statusPromise', function (done) { - var rest = helper.AblyRest({ internal: { promises: true } }); - var channel = rest.channels.get('statusPromise'); - channel - .status() - .then(function (channelDetails) { - try { - expect(channelDetails.channelId).to.equal('statusPromise'); - expect(channelDetails.status.isActive).to.be.a('boolean'); - var metrics = channelDetails.status.occupancy.metrics; - expect(metrics.connections).to.be.a('number'); - expect(metrics.presenceConnections).to.be.a('number'); - expect(metrics.presenceMembers).to.be.a('number'); - expect(metrics.presenceSubscribers).to.be.a('number'); - expect(metrics.publishers).to.be.a('number'); - expect(metrics.subscribers).to.be.a('number'); - done(); - } catch (err) { - done(err); - } - }) - ['catch'](function (err) { - done(err); - }); - }); - } }); }); From edcecfa4000b25cb46b93174730d8c69a13a80df Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 17:36:54 +0100 Subject: [PATCH 22/30] test: convert rest time test to Promise API Co-authored-by: Lawrence Forooghian --- test/rest/time.test.js | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/test/rest/time.test.js b/test/rest/time.test.js index f05025a1f0..73d9399557 100644 --- a/test/rest/time.test.js +++ b/test/rest/time.test.js @@ -12,28 +12,18 @@ define(['shared_helper', 'chai'], function (helper, chai) { done(err); return; } - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); done(); }); }); - it('time0', function (done) { - rest.time(function (err, serverTime) { - if (err) { - done(err); - return; - } - try { - var localFiveMinutesAgo = utils.now() - 5 * 60 * 1000; - expect( - serverTime > localFiveMinutesAgo, - 'Verify returned time matches current local time with 5 minute leeway for badly synced local clocks' - ).to.be.ok; - done(); - } catch (err) { - done(err); - } - }); + it('time0', async function () { + var serverTime = await rest.time(); + var localFiveMinutesAgo = utils.now() - 5 * 60 * 1000; + expect( + serverTime > localFiveMinutesAgo, + 'Verify returned time matches current local time with 5 minute leeway for badly synced local clocks' + ).to.be.ok; }); if (typeof Promise !== 'undefined') { From 6796bed1322646509fce8738276dc8affac5def7 Mon Sep 17 00:00:00 2001 From: Owen Pearson Date: Thu, 27 Apr 2023 17:37:13 +0100 Subject: [PATCH 23/30] test: remove legacy rest time promise test Co-authored-by: Lawrence Forooghian --- test/rest/time.test.js | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/test/rest/time.test.js b/test/rest/time.test.js index 73d9399557..62fba2c66b 100644 --- a/test/rest/time.test.js +++ b/test/rest/time.test.js @@ -25,19 +25,5 @@ define(['shared_helper', 'chai'], function (helper, chai) { 'Verify returned time matches current local time with 5 minute leeway for badly synced local clocks' ).to.be.ok; }); - - if (typeof Promise !== 'undefined') { - it('timePromise', function (done) { - var rest = helper.AblyRest({ internal: { promises: true } }); - rest - .time() - .then(function () { - done(); - }) - ['catch'](function (err) { - done(err); - }); - }); - } }); }); From 17d2aaa66112ae0202635edfb013f984665d49d6 Mon Sep 17 00:00:00 2001 From: Lawrence Forooghian Date: Tue, 20 Jun 2023 14:26:03 -0300 Subject: [PATCH 24/30] Remove test of Ably.Rest.Callbacks --- test/realtime/api.test.js | 2 -- test/rest/api.test.js | 2 -- 2 files changed, 4 deletions(-) diff --git a/test/realtime/api.test.js b/test/realtime/api.test.js index 1a4dae77be..36f3dd080b 100644 --- a/test/realtime/api.test.js +++ b/test/realtime/api.test.js @@ -7,8 +7,6 @@ define(['ably', 'chai'], function (Ably, chai) { it('Client constructors', function () { expect(typeof Ably.Realtime).to.equal('function'); expect(typeof Ably.Realtime.Promise).to.equal('function'); - expect(typeof Ably.Realtime.Callbacks).to.equal('function'); - expect(Ably.Realtime.Callbacks).to.equal(Ably.Realtime); }); it('Crypto', function () { diff --git a/test/rest/api.test.js b/test/rest/api.test.js index dd3610c982..02950ca883 100644 --- a/test/rest/api.test.js +++ b/test/rest/api.test.js @@ -7,8 +7,6 @@ define(['ably', 'chai'], function (Ably, chai) { it('Client constructors', function () { expect(typeof Ably.Rest).to.equal('function'); expect(typeof Ably.Rest.Promise).to.equal('function'); - expect(typeof Ably.Rest.Callbacks).to.equal('function'); - expect(Ably.Rest.Callbacks).to.equal(Ably.Rest); }); it('Crypto', function () { From a36fe51833917dc40a3e3c1364b5cd2f01c99369 Mon Sep 17 00:00:00 2001 From: Lawrence Forooghian Date: Tue, 20 Jun 2023 12:00:24 -0300 Subject: [PATCH 25/30] Remove "Async" from name of restTestOnJsonMsgpackAsync --- test/common/modules/shared_helper.js | 19 ++----------------- test/rest/history.test.js | 10 +++++----- test/rest/request.test.js | 14 +++++++------- 3 files changed, 14 insertions(+), 29 deletions(-) diff --git a/test/common/modules/shared_helper.js b/test/common/modules/shared_helper.js index d9a6b7216e..bbb47e4907 100644 --- a/test/common/modules/shared_helper.js +++ b/test/common/modules/shared_helper.js @@ -149,20 +149,6 @@ define([ }; function restTestOnJsonMsgpack(name, testFn, skip) { - var itFn = skip ? it.skip : it; - itFn(name + ' with binary protocol', function (done) { - testFn(done, new clientModule.AblyRest({ useBinaryProtocol: true }), name + '_binary'); - }); - itFn(name + ' with text protocol', function (done) { - testFn(done, new clientModule.AblyRest({ useBinaryProtocol: false }), name + '_text'); - }); - } - - restTestOnJsonMsgpack.skip = function (name, testFn) { - restTestOnJsonMsgpack(name, testFn, true); - }; - - function restTestOnJsonMsgpackAsync(name, testFn, skip) { var itFn = skip ? it.skip : it; itFn(name + ' with binary protocol', async function () { await testFn(new clientModule.AblyRestPromise({ useBinaryProtocol: true }), name + '_binary'); @@ -172,8 +158,8 @@ define([ }); } - restTestOnJsonMsgpackAsync.skip = function (name, testFn) { - restTestOnJsonMsgpackAsync(name, testFn, true); + restTestOnJsonMsgpack.skip = function (name, testFn) { + restTestOnJsonMsgpack(name, testFn, true); }; function clearTransportPreference() { @@ -242,7 +228,6 @@ define([ becomeSuspended: becomeSuspended, testOnAllTransports: testOnAllTransports, restTestOnJsonMsgpack: restTestOnJsonMsgpack, - restTestOnJsonMsgpackAsync: restTestOnJsonMsgpackAsync, availableTransports: availableTransports, bestTransport: bestTransport, clearTransportPreference: clearTransportPreference, diff --git a/test/rest/history.test.js b/test/rest/history.test.js index a4d7420ee5..98eab3e5ab 100644 --- a/test/rest/history.test.js +++ b/test/rest/history.test.js @@ -4,7 +4,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { var rest; var expect = chai.expect; var exports = {}; - var restTestOnJsonMsgpackAsync = helper.restTestOnJsonMsgpackAsync; + var restTestOnJsonMsgpack = helper.restTestOnJsonMsgpack; var utils = helper.Utils; var testMessages = [ { name: 'event0', data: 'some data' }, @@ -27,7 +27,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { }); }); - restTestOnJsonMsgpackAsync('history_simple', async function (rest, channelName) { + restTestOnJsonMsgpack('history_simple', async function (rest, channelName) { var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ @@ -53,7 +53,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { ); }); - restTestOnJsonMsgpackAsync('history_multiple', async function (rest, channelName) { + restTestOnJsonMsgpack('history_multiple', async function (rest, channelName) { var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ @@ -76,7 +76,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { ); }); - restTestOnJsonMsgpackAsync('history_simple_paginated_b', async function (rest, channelName) { + restTestOnJsonMsgpack('history_simple_paginated_b', async function (rest, channelName) { var testchannel = rest.channels.get('persisted:' + channelName); /* first, send a number of events to this channel */ @@ -225,7 +225,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { ); }); - restTestOnJsonMsgpackAsync('history_encoding_errors', async function (rest, channelName) { + restTestOnJsonMsgpack('history_encoding_errors', async function (rest, channelName) { var testchannel = rest.channels.get('persisted:' + channelName); var badMessage = { name: 'jsonUtf8string', encoding: 'json/utf-8', data: '{"foo":"bar"}' }; testchannel.publish(badMessage); diff --git a/test/rest/request.test.js b/test/rest/request.test.js index 8f1279f22d..844d7f75cd 100644 --- a/test/rest/request.test.js +++ b/test/rest/request.test.js @@ -5,7 +5,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var expect = chai.expect; var utils = helper.Utils; var echoServerHost = 'echo.ably.io'; - var restTestOnJsonMsgpackAsync = helper.restTestOnJsonMsgpackAsync; + var restTestOnJsonMsgpack = helper.restTestOnJsonMsgpack; var Defaults = Ably.Rest.Platform.Defaults; describe('rest/request', function () { @@ -22,7 +22,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }); - restTestOnJsonMsgpackAsync('request_version', function (rest) { + restTestOnJsonMsgpack('request_version', function (rest) { const version = 150; // arbitrarily chosen function testRequestHandler(_, __, ___, headers) { @@ -40,7 +40,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async rest.request('get', '/time' /* arbitrarily chosen */, version, null, null, null); }); - restTestOnJsonMsgpackAsync('request_time', async function (rest) { + restTestOnJsonMsgpack('request_time', async function (rest) { const res = await rest.request('get', '/time', Defaults.protocolVersion, null, null, null); expect(res.statusCode).to.equal(200, 'Check statusCode'); expect(res.success).to.equal(true, 'Check success'); @@ -48,7 +48,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async expect(res.items.length).to.equal(1, 'Check array was of length 1'); }); - restTestOnJsonMsgpackAsync('request_404', async function (rest) { + restTestOnJsonMsgpack('request_404', async function (rest) { /* NB: can't just use /invalid or something as the CORS preflight will * fail. Need something superficially a valid path but where the actual * request fails */ @@ -80,7 +80,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); /* Use the request feature to publish, then retrieve (one at a time), some messages */ - restTestOnJsonMsgpackAsync('request_post_get_messages', async function (rest, channelName) { + restTestOnJsonMsgpack('request_post_get_messages', async function (rest, channelName) { var channelPath = '/channels/' + channelName + '/messages', msgone = { name: 'faye', data: 'whittaker' }, msgtwo = { name: 'martin', data: 'reed' }; @@ -122,7 +122,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async expect(res.items[0].data).to.equal(msgtwo.data, 'Check data is as expected'); }); - restTestOnJsonMsgpackAsync('request_batch_api_success', async function (rest, name) { + restTestOnJsonMsgpack('request_batch_api_success', async function (rest, name) { var body = { channels: [name + '1', name + '2'], messages: { data: 'foo' } }; const res = await rest.request('POST', '/messages', Defaults.protocolVersion, {}, body, {}); @@ -142,7 +142,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async expect(res.items[1].channel).to.equal(name + '2', 'Verify channel2 response includes correct channel'); }); - restTestOnJsonMsgpackAsync.skip('request_batch_api_partial_success', async function (rest, name) { + restTestOnJsonMsgpack.skip('request_batch_api_partial_success', async function (rest, name) { var body = { channels: [name, '[invalid', ''], messages: { data: 'foo' } }; var res = await rest.request('POST', '/messages', Defaults.protocolVersion, {}, body, {}); From a1c35929b9539cad1c7e574a4d029078496545a8 Mon Sep 17 00:00:00 2001 From: Lawrence Forooghian Date: Tue, 20 Jun 2023 16:56:05 -0300 Subject: [PATCH 26/30] Remove parts of test relating to setOptions calling its callback immediately MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As part of #1213, I’ll be updating this test to use the Promise-based API, to which the concept of "calls the callback before returning" can’t be detected, since the JavaScript engine always calls Promise callbacks asynchronously. --- test/realtime/channel.test.js | 40 ----------------------------------- 1 file changed, 40 deletions(-) diff --git a/test/realtime/channel.test.js b/test/realtime/channel.test.js index 13993e6f54..5e463a9eae 100644 --- a/test/realtime/channel.test.js +++ b/test/realtime/channel.test.js @@ -686,23 +686,6 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async async.series( [ - function (cb) { - var setOptionsReturned = false; - channel.setOptions( - { - params: params, - modes: modes, - }, - function () { - expect( - !setOptionsReturned, - 'setOptions failed to call back immediately, when no reattach is required' - ).to.be.ok; - cb(); - } - ); - setOptionsReturned = true; - }, function (cb) { channel.attach(cb); }, @@ -715,7 +698,6 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channelUpdated = true; }); - var setOptionsReturned = false; channel.setOptions( { params: params, @@ -724,10 +706,6 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* Wait a tick so we don' depend on whether the update event runs the * channelUpdated listener or the setOptions listener first */ Ably.Realtime.Platform.Config.nextTick(function () { - expect( - setOptionsReturned, - 'setOptions should return immediately and call back after the reattach' - ).to.be.ok; expect( channelUpdated, 'Check channel went to the server to update the channel params' @@ -736,7 +714,6 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); } ); - setOptionsReturned = true; }, function (cb) { var channelUpdated = false; @@ -744,34 +721,17 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channelUpdated = true; }); - var setOptionsReturned = false; channel.setOptions( { modes: modes, }, function () { Ably.Realtime.Platform.Config.nextTick(function () { - expect( - setOptionsReturned, - 'setOptions should return immediately and call back after the reattach' - ).to.be.ok; expect(channelUpdated, 'Check channel went to the server to update the channel mode').to.be.ok; cb(); }); } ); - setOptionsReturned = true; - }, - function (cb) { - var setOptionsReturned = false; - channel.setOptions({}, function () { - expect( - !setOptionsReturned, - 'setOptions failed to call back immediately, when no reattach is required' - ).to.be.ok; - cb(); - }); - setOptionsReturned = true; }, ], function (err) { From 050b95b370478c7e0aab96472efc0363a35a9a44 Mon Sep 17 00:00:00 2001 From: Lawrence Forooghian Date: Tue, 20 Jun 2023 17:46:09 -0300 Subject: [PATCH 27/30] Prepare realtime channel publish disallowed test for conversion to Promise API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When we switch to using the Promise-based API, we’ll need to wait for the result of `publish`, so let’s put the supporting code in place for that. --- test/realtime/message.test.js | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/test/realtime/message.test.js b/test/realtime/message.test.js index 03143bac53..3cd4f663e5 100644 --- a/test/realtime/message.test.js +++ b/test/realtime/message.test.js @@ -440,22 +440,25 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - /* publish events */ - var restChannel = rest.channels.get('publishDisallowed'); - for (var i = 0; i < testArguments.length; i++) { - try { - restChannel.publish.apply(restChannel, testArguments[i]); - closeAndFinish(done, realtime, new Error('Exception was not raised')); - } catch (err) { + (async function () { + /* publish events */ + var restChannel = rest.channels.get('publishDisallowed'); + for (var i = 0; i < testArguments.length; i++) { try { - expect(err.code).to.equal(40013, 'Invalid data type exception raised'); + restChannel.publish.apply(restChannel, testArguments[i]); + closeAndFinish(done, realtime, new Error('Exception was not raised')); } catch (err) { - closeAndFinish(done, realtime, err); - return; + try { + expect(err.code).to.equal(40013, 'Invalid data type exception raised'); + } catch (err) { + closeAndFinish(done, realtime, err); + return; + } } } - } - closeAndFinish(done, realtime); + })().then(() => { + closeAndFinish(done, realtime); + }); }); }); monitorConnection(done, realtime); From 43a2d1d91d71c84595476e072c44b76729ee93a1 Mon Sep 17 00:00:00 2001 From: Lawrence Forooghian Date: Wed, 14 Jun 2023 14:21:22 -0300 Subject: [PATCH 28/30] =?UTF-8?q?Update=20Realtime=20tests=20to=20use=20SD?= =?UTF-8?q?K=E2=80=99s=20Promise-based=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I’ve chosen to do this with the lightest touch possible — that is, maintaining the tests’ callback-based approach and simply bridging the SDK’s Promise-based API back to callbacks. I did this for the sake of reviewability and not accidentally changing the behaviour of the tests in some subtle way that I’d then have to put time into understanding. It would be good to, at some point, update the structure of the tests to use `async` / `await`, to improve readability and to make them reflect how the users actually interact with the Promise-based API in the real world. I’ve split out into the separate task #1348. Note that I haven’t made any changes to the calls to EventEmitter’s `once` or `whenState` methods — we’re going to keep the callback-based versions of those methods, since there is no Promise equivalent of being able to turn them off using `off`. Resolves #1213. --- test/browser/connection.test.js | 32 +-- test/browser/http.test.js | 7 +- test/browser/simple.test.js | 7 +- test/common/modules/shared_helper.js | 14 ++ test/realtime/auth.test.js | 249 ++++++++++---------- test/realtime/channel.test.js | 183 +++++++-------- test/realtime/connection.test.js | 25 +- test/realtime/connectivity.test.js | 17 +- test/realtime/crypto.test.js | 43 ++-- test/realtime/delta.test.js | 23 +- test/realtime/encoding.test.js | 46 ++-- test/realtime/event_emitter.test.js | 34 +-- test/realtime/failure.test.js | 41 ++-- test/realtime/history.test.js | 15 +- test/realtime/init.test.js | 47 ++-- test/realtime/message.test.js | 157 +++++++------ test/realtime/presence.test.js | 330 ++++++++++++++------------- test/realtime/reauth.test.js | 17 +- test/realtime/resume.test.js | 51 +++-- test/realtime/sync.test.js | 35 +-- test/realtime/upgrade.test.js | 43 ++-- 21 files changed, 734 insertions(+), 682 deletions(-) diff --git a/test/browser/connection.test.js b/test/browser/connection.test.js index d615c133c8..3ae2abdba3 100644 --- a/test/browser/connection.test.js +++ b/test/browser/connection.test.js @@ -51,7 +51,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('device_going_offline_causes_disconnected_state', function (done) { - var realtime = helper.AblyRealtime(), + var realtime = helper.AblyRealtimePromise(), connection = realtime.connection, offlineEvent = new Event('offline', { bubbles: true }); @@ -94,7 +94,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { it('device_going_online_causes_disconnected_connection_to_reconnect_immediately', function (done) { /* Give up trying to connect fairly quickly */ - var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 1000 }), + var realtime = helper.AblyRealtimePromise({ realtimeRequestTimeout: 1000 }), connection = realtime.connection, onlineEvent = new Event('online', { bubbles: true }); @@ -139,7 +139,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { it('device_going_online_causes_suspended_connection_to_reconnect_immediately', function (done) { /* move to suspended state after 2s of being disconnected */ - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ disconnectedRetryTimeout: 500, realtimeRequestTimeout: 500, connectionStateTtl: 2000, @@ -183,7 +183,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('device_going_online_causes_connecting_connection_to_retry_attempt', function (done) { - var realtime = helper.AblyRealtime({}), + var realtime = helper.AblyRealtimePromise({}), connection = realtime.connection, onlineEvent = new Event('online', { bubbles: true }), oldTransport, @@ -223,7 +223,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { cb(true); }, }, - realtime = helper.AblyRealtime(realtimeOpts), + realtime = helper.AblyRealtimePromise(realtimeOpts), refreshEvent = new Event('beforeunload', { bubbles: true }); monitorConnection(done, realtime); @@ -242,7 +242,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { return; } - var newRealtime = helper.AblyRealtime(realtimeOpts); + var newRealtime = helper.AblyRealtimePromise(realtimeOpts); newRealtime.connection.once('connected', function () { try { expect( @@ -264,7 +264,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { cb(false); }, }; - var realtime = helper.AblyRealtime(realtimeOpts), + var realtime = helper.AblyRealtimePromise(realtimeOpts), refreshEvent = new Event('beforeunload', { bubbles: true }); monitorConnection(done, realtime); @@ -283,7 +283,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { return; } - var newRealtime = helper.AblyRealtime(realtimeOpts); + var newRealtime = helper.AblyRealtimePromise(realtimeOpts); newRealtime.connection.once('connected', function () { try { expect( @@ -301,7 +301,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('page_refresh_with_close_on_unload', function (done) { - var realtime = helper.AblyRealtime({ closeOnUnload: true }), + var realtime = helper.AblyRealtimePromise({ closeOnUnload: true }), refreshEvent = new Event('beforeunload', { bubbles: true }); monitorConnection(done, realtime); @@ -321,7 +321,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('page_refresh_with_manual_recovery', function (done) { - var realtime = helper.AblyRealtime({ closeOnUnload: false }), + var realtime = helper.AblyRealtimePromise({ closeOnUnload: false }), refreshEvent = new Event('beforeunload', { bubbles: true }); monitorConnection(done, realtime); @@ -342,7 +342,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { return; } - var newRealtime = helper.AblyRealtime({ recover: recoveryKey }); + var newRealtime = helper.AblyRealtimePromise({ recover: recoveryKey }); newRealtime.connection.once('connected', function () { try { expect( @@ -359,7 +359,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('persist_preferred_transport', function (done) { - var realtime = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); realtime.connection.connectionManager.on(function (transport) { if (this.event === 'transport.active' && transport.shortName === 'web_socket') { @@ -381,7 +381,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { var transportPreferenceName = 'ably-transport-preference'; window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: 'web_socket' })); - var realtime = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); realtime.connection.connectionManager.on(function (transport) { if (this.event === 'transport.active') { @@ -400,7 +400,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { it('use_persisted_transport1', function (done) { window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: 'xhr_streaming' })); - var realtime = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); realtime.connection.connectionManager.on(function (transport) { if (this.event === 'transport.active') { @@ -417,7 +417,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('browser_transports', function (done) { - var realtime = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); try { expect(realtime.connection.connectionManager.baseTransport).to.equal('xhr_polling'); expect(realtime.connection.connectionManager.upgradeTransports).to.deep.equal([ @@ -437,7 +437,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { * realtime) */ it('connection behaviour with a proxy through which streaming is broken', function (done) { - const realtime = helper.AblyRealtime({ + const realtime = helper.AblyRealtimePromise({ transportParams: { simulateNoStreamingProxy: true, maxStreamDuration: 7500, diff --git a/test/browser/http.test.js b/test/browser/http.test.js index dfb93c9032..8c810f04b0 100644 --- a/test/browser/http.test.js +++ b/test/browser/http.test.js @@ -3,6 +3,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var rest; var expect = chai.expect; + var whenPromiseSettles = helper.whenPromiseSettles; describe('rest/http/fetch', function () { this.timeout(60 * 1000); @@ -11,7 +12,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { initialXhrSupported = Ably.Rest.Platform.Config.xhrSupported; Ably.Rest.Platform.Config.xhrSupported = false; helper.setupApp(function () { - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); done(); }); }); @@ -33,7 +34,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('Should succeed in using fetch to publish a message', function (done) { const channel = rest.channels.get('http_test_channel'); - channel.publish('test', 'Testing fetch support', (err) => { + whenPromiseSettles(channel.publish('test', 'Testing fetch support'), (err) => { expect(err).to.not.exist; done(); }); @@ -41,7 +42,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('Should pass errors correctly', function (done) { const channel = rest.channels.get(''); - channel.publish('test', 'Invalid message', (err) => { + whenPromiseSettles(channel.publish('test', 'Invalid message'), (err) => { expect(err).to.exist; done(); }); diff --git a/test/browser/simple.test.js b/test/browser/simple.test.js index 18ea08d6b7..e4ca140ec1 100644 --- a/test/browser/simple.test.js +++ b/test/browser/simple.test.js @@ -2,6 +2,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var expect = chai.expect; + var whenPromiseSettles = helper.whenPromiseSettles; describe('browser/simple', function () { this.timeout(60 * 1000); @@ -22,7 +23,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { function realtimeConnection(transports) { var options = {}; if (transports) options.transports = transports; - return helper.AblyRealtime(options); + return helper.AblyRealtimePromise(options); } function failWithin(timeInSeconds, done, ably, description) { @@ -71,7 +72,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { ably.connection.on('connected', function () { connectionTimeout.stop(); heartbeatTimeout = failWithin(25, done, ably, 'wait for heartbeat'); - ably.connection.ping(function (err) { + whenPromiseSettles(ably.connection.ping(), function (err) { heartbeatTimeout.stop(); done(err); ably.close(); @@ -115,7 +116,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { receiveMessagesTimeout = failWithin(15, done, ably, 'wait for published messages to be received'); timer = setInterval(function () { - channel.publish('event0', 'Hello world at: ' + new Date(), function (err) { + whenPromiseSettles(channel.publish('event0', 'Hello world at: ' + new Date()), function (err) { sentCbCount++; checkFinish(); }); diff --git a/test/common/modules/shared_helper.js b/test/common/modules/shared_helper.js index bbb47e4907..8af3164629 100644 --- a/test/common/modules/shared_helper.js +++ b/test/common/modules/shared_helper.js @@ -57,6 +57,19 @@ define([ }); } + /** + * Uses a callback to communicate the result of a `Promise`. The first argument passed to the callback will be either an error (when the promise is rejected) or `null` (when the promise is fulfilled). In the case where the promise is fulfilled, the resulting value will be passed to the callback as a second argument. + */ + function whenPromiseSettles(promise, callback) { + promise + .then((result) => { + callback(null, result); + }) + .catch((err) => { + callback(err); + }); + } + function simulateDroppedConnection(realtime) { // Go into the 'disconnected' state before actually disconnecting the transports // to avoid the instantaneous reconnect attempt that would be triggered in @@ -237,5 +250,6 @@ define([ unroutableAddress: unroutableAddress, arrFind: arrFind, arrFilter: arrFilter, + whenPromiseSettles: whenPromiseSettles, }); }); diff --git a/test/realtime/auth.test.js b/test/realtime/auth.test.js index bfb6604154..b36ca70159 100644 --- a/test/realtime/auth.test.js +++ b/test/realtime/auth.test.js @@ -15,6 +15,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var http = new Ably.Realtime.Platform.Http(); var jwtTestChannelName = 'JWT_test' + String(Math.floor(Math.random() * 10000) + 1); var echoServer = 'https://echo.ably.io'; + var whenPromiseSettles = helper.whenPromiseSettles; /* * Helper function to fetch JWT tokens from the echo server @@ -39,14 +40,14 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var rest = helper.AblyRest({ queryTime: true }); - rest.time(function (err, time) { + var rest = helper.AblyRestPromise({ queryTime: true }); + whenPromiseSettles(rest.time(), function (err, time) { if (err) { done(err); return; } else { currentTime = time; - rest.auth.requestToken({}, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken({}), function (err, tokenDetails) { try { expect(!err, err && displayError(err)).to.be.ok; done(); @@ -63,8 +64,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async * Base token generation case */ it('authbase0', function (done) { - var realtime = helper.AblyRealtime(); - realtime.auth.requestToken(function (err, tokenDetails) { + var realtime = helper.AblyRealtimePromise(); + whenPromiseSettles(realtime.auth.requestToken(), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; @@ -87,8 +88,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthUrl_json', function (done) { var realtime, - rest = helper.AblyRest(); - rest.auth.requestToken(null, null, function (err, tokenDetails) { + rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; @@ -96,7 +97,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var authPath = echoServer + '/?type=json&body=' + encodeURIComponent(JSON.stringify(tokenDetails)); - realtime = helper.AblyRealtime({ authUrl: authPath }); + realtime = helper.AblyRealtimePromise({ authUrl: authPath }); realtime.connection.on('connected', function () { closeAndFinish(done, realtime); @@ -112,8 +113,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthUrl_post_json', function (done) { var realtime, - rest = helper.AblyRest(); - rest.auth.requestToken(null, null, function (err, tokenDetails) { + rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; @@ -121,7 +122,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var authUrl = echoServer + '/?type=json&'; - realtime = helper.AblyRealtime({ authUrl: authUrl, authMethod: 'POST', authParams: tokenDetails }); + realtime = helper.AblyRealtimePromise({ authUrl: authUrl, authMethod: 'POST', authParams: tokenDetails }); realtime.connection.on('connected', function () { closeAndFinish(done, realtime); @@ -137,8 +138,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthUrl_plainText', function (done) { var realtime, - rest = helper.AblyRest(); - rest.auth.requestToken(null, null, function (err, tokenDetails) { + rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; @@ -146,7 +147,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var authPath = echoServer + '/?type=text&body=' + tokenDetails['token']; - realtime = helper.AblyRealtime({ authUrl: authPath }); + realtime = helper.AblyRealtimePromise({ authUrl: authPath }); realtime.connection.on('connected', function () { closeAndFinish(done, realtime); @@ -162,9 +163,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthCallback_tokenRequestResponse', function (done) { var realtime, - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); var authCallback = function (tokenParams, callback) { - rest.auth.createTokenRequest(tokenParams, null, function (err, tokenRequest) { + whenPromiseSettles(rest.auth.createTokenRequest(tokenParams, null), function (err, tokenRequest) { if (err) { closeAndFinish(done, realtime, err); return; @@ -178,7 +179,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtime({ authCallback: authCallback }); + realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { @@ -199,10 +200,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthCallback_tokenDetailsResponse', function (done) { var realtime, - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { - rest.auth.requestToken(tokenParams, null, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; @@ -217,7 +218,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtime({ authCallback: authCallback, clientId: clientId }); + realtime = helper.AblyRealtimePromise({ authCallback: authCallback, clientId: clientId }); realtime.connection.on('connected', function () { try { @@ -236,9 +237,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthCallback_tokenStringResponse', function (done) { var realtime, - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); var authCallback = function (tokenParams, callback) { - rest.auth.requestToken(tokenParams, null, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; @@ -252,7 +253,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtime({ authCallback: authCallback }); + realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { @@ -274,8 +275,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthUrl_mixed_authParams_qsParams', function (done) { var realtime, - rest = helper.AblyRest(); - rest.auth.createTokenRequest(null, null, function (err, tokenRequest) { + rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.createTokenRequest(null, null), function (err, tokenRequest) { if (err) { closeAndFinish(done, realtime, err); return; @@ -295,7 +296,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }; var authPath = echoServer + '/qs_to_body' + utils.toQueryString(lowerPrecedenceTokenRequestParts); - realtime = helper.AblyRealtime({ authUrl: authPath, authParams: higherPrecedenceTokenRequestParts }); + realtime = helper.AblyRealtimePromise({ authUrl: authPath, authParams: higherPrecedenceTokenRequestParts }); realtime.connection.on('connected', function () { closeAndFinish(done, realtime); @@ -309,10 +310,10 @@ 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 rest = helper.AblyRestPromise(), testClientId = 'testClientId'; var authCallback = function (tokenParams, callback) { - rest.auth.requestToken({ clientId: testClientId }, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { if (err) { done(err); return; @@ -321,7 +322,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - var realtime = helper.AblyRealtime({ authCallback: authCallback }); + var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { @@ -349,13 +350,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('auth_clientid_inheritance2', function (done) { var clientRealtime, testClientId = 'test client id'; - var rest = helper.AblyRest(); - rest.auth.requestToken({ clientId: testClientId }, function (err, tokenDetails) { + var rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { if (err) { done(err); return; } - clientRealtime = helper.AblyRealtime({ token: tokenDetails, clientId: 'WRONG' }); + clientRealtime = helper.AblyRealtimePromise({ token: tokenDetails, clientId: 'WRONG' }); clientRealtime.connection.once('failed', function (stateChange) { try { expect(stateChange.reason.code).to.equal(40102); @@ -375,13 +376,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('auth_clientid_inheritance3', function (done) { var realtime, testClientId = 'test client id'; - var rest = helper.AblyRest(); - rest.auth.requestToken({ clientId: '*' }, function (err, tokenDetails) { + var rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken({ clientId: '*' }), function (err, tokenDetails) { if (err) { done(err); return; } - realtime = helper.AblyRealtime({ token: tokenDetails.token, clientId: 'test client id' }); + realtime = helper.AblyRealtimePromise({ token: tokenDetails.token, clientId: 'test client id' }); realtime.connection.on('connected', function () { try { expect(realtime.auth.clientId).to.equal(testClientId); @@ -403,13 +404,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('auth_clientid_inheritance4', function (done) { var realtime, testClientId = 'test client id'; - var rest = helper.AblyRest(); - rest.auth.requestToken({ clientId: '*' }, function (err, tokenDetails) { + var rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken({ clientId: '*' }), function (err, tokenDetails) { if (err) { done(err); return; } - realtime = helper.AblyRealtime({ token: tokenDetails, clientId: 'test client id' }); + realtime = helper.AblyRealtimePromise({ token: tokenDetails, clientId: 'test client id' }); realtime.connection.on('connected', function () { try { expect(realtime.auth.clientId).to.equal(testClientId); @@ -431,13 +432,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('auth_clientid_inheritance5', function (done) { var clientRealtime, testClientId = 'test client id'; - var rest = helper.AblyRest(); - rest.auth.requestToken({ clientId: testClientId }, function (err, tokenDetails) { + var rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { if (err) { done(err); return; } - clientRealtime = helper.AblyRealtime({ token: tokenDetails.token }); + clientRealtime = helper.AblyRealtimePromise({ token: tokenDetails.token }); clientRealtime.connection.on('connected', function () { try { expect(clientRealtime.auth.clientId).to.equal(testClientId); @@ -456,7 +457,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ function authCallback_failures(realtimeOptions, expectFailure) { return function (done) { - var realtime = helper.AblyRealtime(realtimeOptions); + var realtime = helper.AblyRealtimePromise(realtimeOptions); realtime.connection.on(function (stateChange) { if (stateChange.previous !== 'initialized') { try { @@ -606,8 +607,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('authUrl_403_previously_active', function (done) { var realtime, - rest = helper.AblyRest(); - rest.auth.requestToken(null, null, function (err, tokenDetails) { + rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; @@ -615,13 +616,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var authPath = echoServer + '/?type=json&body=' + encodeURIComponent(JSON.stringify(tokenDetails)); - realtime = helper.AblyRealtime({ authUrl: authPath }); + realtime = helper.AblyRealtimePromise({ authUrl: authPath }); realtime.connection.on('connected', function () { /* replace the authUrl and reauth */ - realtime.auth.authorize( - null, - { authUrl: echoServer + '/respondwith?status=403' }, + whenPromiseSettles( + realtime.auth.authorize(null, { authUrl: echoServer + '/respondwith?status=403' }), function (err, tokenDetails) { try { expect(err && err.statusCode).to.equal(403, 'Check err statusCode'); @@ -649,14 +649,16 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('auth_token_expires', function (realtimeOpts) { return function (done) { var clientRealtime, - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); - rest.auth.requestToken({ ttl: 5000 }, null, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken({ ttl: 5000 }, null), function (err, tokenDetails) { if (err) { done(err); return; } - clientRealtime = helper.AblyRealtime(mixin(realtimeOpts, { tokenDetails: tokenDetails, queryTime: true })); + clientRealtime = helper.AblyRealtimePromise( + mixin(realtimeOpts, { tokenDetails: tokenDetails, queryTime: true }) + ); clientRealtime.connection.on('failed', function () { closeAndFinish(done, clientRealtime, new Error('Failed to connect before token expired')); @@ -683,7 +685,7 @@ 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 rest = helper.AblyRestPromise({ queryTime: true }), timeRequestCount = 0, originalTime = rest.time; @@ -706,7 +708,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var asyncFns = []; for (var i = 0; i < 10; i++) { asyncFns.push(function (callback) { - rest.auth.createTokenRequest({}, null, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.createTokenRequest({}, null), function (err, tokenDetails) { if (err) { return callback(err); } @@ -741,11 +743,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('auth_tokenDetails_expiry_with_authcallback', function (realtimeOpts) { return function (done) { var realtime, - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { tokenParams.ttl = 5000; - rest.auth.requestToken(tokenParams, null, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; @@ -754,7 +756,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtime(mixin(realtimeOpts, { authCallback: authCallback, clientId: clientId })); + realtime = helper.AblyRealtimePromise(mixin(realtimeOpts, { authCallback: authCallback, clientId: clientId })); monitorConnection(done, realtime); realtime.connection.once('connected', function () { realtime.connection.once('disconnected', function (stateChange) { @@ -782,11 +784,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('auth_token_string_expiry_with_authcallback', function (realtimeOpts) { return function (done) { var realtime, - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { tokenParams.ttl = 5000; - rest.auth.requestToken(tokenParams, null, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; @@ -795,7 +797,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtime(mixin(realtimeOpts, { authCallback: authCallback, clientId: clientId })); + realtime = helper.AblyRealtimePromise(mixin(realtimeOpts, { authCallback: authCallback, clientId: clientId })); monitorConnection(done, realtime); realtime.connection.once('connected', function () { realtime.connection.once('disconnected', function (stateChange) { @@ -822,35 +824,40 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('auth_token_string_expiry_with_token', function (realtimeOpts) { return function (done) { var realtime, - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); var clientId = 'test clientid'; - rest.auth.requestToken({ ttl: 5000, clientId: clientId }, null, function (err, tokenDetails) { - if (err) { - closeAndFinish(done, realtime, err); - return; - } - realtime = helper.AblyRealtime(mixin(realtimeOpts, { token: tokenDetails.token, clientId: clientId })); - realtime.connection.once('connected', function () { - realtime.connection.once('disconnected', function (stateChange) { - try { - expect(stateChange.reason.code).to.equal(40142, 'Verify correct disconnect code'); - } catch (err) { - done(err); - return; - } - realtime.connection.once('failed', function (stateChange) { - /* Library has no way to generate a new token, so should fail */ + whenPromiseSettles( + rest.auth.requestToken({ ttl: 5000, clientId: clientId }, null), + function (err, tokenDetails) { + if (err) { + closeAndFinish(done, realtime, err); + return; + } + realtime = helper.AblyRealtimePromise( + mixin(realtimeOpts, { token: tokenDetails.token, clientId: clientId }) + ); + realtime.connection.once('connected', function () { + realtime.connection.once('disconnected', function (stateChange) { try { - expect(stateChange.reason.code).to.equal(40171, 'Verify correct cause failure code'); - realtime.close(); - done(); + expect(stateChange.reason.code).to.equal(40142, 'Verify correct disconnect code'); } catch (err) { done(err); + return; } + realtime.connection.once('failed', function (stateChange) { + /* Library has no way to generate a new token, so should fail */ + try { + expect(stateChange.reason.code).to.equal(40171, 'Verify correct cause failure code'); + realtime.close(); + done(); + } catch (err) { + done(err); + } + }); }); }); - }); - }); + } + ); }; }); @@ -860,15 +867,17 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('auth_expired_token_string', function (realtimeOpts) { return function (done) { var realtime, - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); var clientId = 'test clientid'; - rest.auth.requestToken({ ttl: 1, clientId: clientId }, null, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken({ ttl: 1, clientId: clientId }, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; } setTimeout(function () { - realtime = helper.AblyRealtime(mixin(realtimeOpts, { token: tokenDetails.token, clientId: clientId })); + realtime = helper.AblyRealtimePromise( + mixin(realtimeOpts, { token: tokenDetails.token, clientId: clientId }) + ); realtime.connection.once('failed', function (stateChange) { try { expect(stateChange.reason.code).to.equal(40171, 'Verify correct failure code'); @@ -899,13 +908,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports.skip('reauth_authCallback', function (realtimeOpts) { return function (done) { var realtime, - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); var firstTime = true; var authCallback = function (tokenParams, callback) { tokenParams.clientId = '*'; tokenParams.capability = firstTime ? { wrong: ['*'] } : { right: ['*'] }; firstTime = false; - rest.auth.requestToken(tokenParams, null, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; @@ -914,10 +923,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtime(mixin(realtimeOpts, { authCallback: authCallback })); + realtime = helper.AblyRealtimePromise(mixin(realtimeOpts, { authCallback: authCallback })); realtime.connection.once('connected', function () { var channel = realtime.channels.get('right'); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { try { expect(err, 'Check using first token, without channel attach capability').to.be.ok; expect(err.code).to.equal(40160, 'Check expected error code'); @@ -927,14 +936,14 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } /* soon after connected, reauth */ - realtime.auth.authorize(null, null, function (err) { + whenPromiseSettles(realtime.auth.authorize(null, null), function (err) { try { expect(!err, err && displayError(err)).to.be.ok; } catch (err) { done(err); return; } - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { try { expect(!err, 'Check using second token, with channel attach capability').to.be.ok; closeAndFinish(done, realtime); @@ -951,7 +960,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* RSA10j */ it('authorize_updates_stored_details', function (done) { - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ autoConnect: false, defaultTokenParams: { version: 1 }, token: '1', @@ -982,10 +991,10 @@ 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 rest = helper.AblyRestPromise(), authCallback = function (tokenParams, callback) { // Request a token (should happen twice) - rest.auth.requestToken(tokenParams, null, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); return; @@ -993,7 +1002,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async callback(null, tokenDetails); }); }, - realtime = helper.AblyRealtime({ authCallback: authCallback, transports: [helper.bestTransport] }); + realtime = helper.AblyRealtimePromise({ authCallback: authCallback, transports: [helper.bestTransport] }); realtime.connection.once('connected', function () { var transport = realtime.connection.connectionManager.activeProtocol.transport, @@ -1029,7 +1038,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async getJWT(params, callback); }; - var realtime = helper.AblyRealtime({ authCallback: authCallback }); + var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { @@ -1062,7 +1071,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async getJWT(params, callback); }; - var realtime = helper.AblyRealtime({ authCallback: authCallback }); + var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { @@ -1093,10 +1102,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async getJWT(params, callback); }; - var realtime = helper.AblyRealtime({ authCallback: authCallback }); + var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); realtime.connection.once('connected', function () { var channel = realtime.channels.get(jwtTestChannelName); - channel.publish('greeting', 'Hello World!', function (err) { + whenPromiseSettles(channel.publish('greeting', 'Hello World!'), function (err) { try { expect(err.code).to.equal(40160, 'Verify publish denied code'); expect(err.statusCode).to.equal(401, 'Verify publish denied status code'); @@ -1122,7 +1131,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var publishEvent = 'publishEvent', messageData = 'Hello World!'; - var realtime = helper.AblyRealtime({ authCallback: authCallback }); + var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); realtime.connection.once('connected', function () { var channel = realtime.channels.get(jwtTestChannelName); channel.subscribe(publishEvent, function (msg) { @@ -1149,7 +1158,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async getJWT(params, callback); }; - var realtime = helper.AblyRealtime({ authCallback: authCallback }); + var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); realtime.connection.once('connected', function () { realtime.connection.once('disconnected', function (stateChange) { try { @@ -1176,7 +1185,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async getJWT(params, callback); }; - var realtime = helper.AblyRealtime({ authCallback: authCallback }); + var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); realtime.connection.once('connected', function () { var originalToken = realtime.auth.tokenDetails.token; realtime.connection.once('update', function () { @@ -1203,7 +1212,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async done(err); return; } - var realtime = helper.AblyRealtime({ token: token }); + var realtime = helper.AblyRealtimePromise({ token: token }); realtime.connection.once('connected', function () { try { expect(token).to.equal(realtime.auth.tokenDetails.token, 'Verify that token is the same'); @@ -1219,8 +1228,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* RTN14b */ it('reauth_consistently_expired_token', function (done) { var realtime, - rest = helper.AblyRest(); - rest.auth.requestToken({ ttl: 1 }, function (err, token) { + rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken({ ttl: 1 }), function (err, token) { if (err) { done(err); return; @@ -1232,7 +1241,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }; /* Wait a few ms to ensure token is expired */ setTimeout(function () { - realtime = helper.AblyRealtime({ authCallback: authCallback, disconnectedRetryTimeout: 15000 }); + realtime = helper.AblyRealtimePromise({ authCallback: authCallback, disconnectedRetryTimeout: 15000 }); /* Wait 5s, expect to have seen two attempts to get a token -- so the * authCallback called twice -- and the connection to now be sitting in * the disconnected state */ @@ -1252,8 +1261,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, - rest = helper.AblyRest(); - rest.auth.requestToken(function (err, token) { + rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken(), function (err, token) { if (err) { done(err); return; @@ -1265,7 +1274,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async authCallbackCallCount++; callback(null, token); }; - realtime = helper.AblyRealtime({ authCallback: authCallback }); + realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { expect(authCallbackCallCount).to.equal(1, 'Check we did not autoremove an expired token ourselves'); @@ -1280,8 +1289,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, - rest = helper.AblyRest(); - rest.auth.requestToken(function (err, token) { + rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken(), function (err, token) { if (err) { done(err); return; @@ -1293,9 +1302,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async authCallbackCallCount++; callback(null, token); }; - realtime = helper.AblyRealtime({ authCallback: authCallback, autoConnect: false }); + realtime = helper.AblyRealtimePromise({ authCallback: authCallback, autoConnect: false }); /* Set the server time offset */ - realtime.time(function () { + whenPromiseSettles(realtime.time(), function () { realtime.connect(); realtime.connection.on('connected', function () { try { @@ -1314,38 +1323,38 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* Check that only the last authorize matters */ it('multiple_concurrent_authorize', function (done) { - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ logLevel: 4, useTokenAuth: true, defaultTokenParams: { capability: { wrong: ['*'] } }, }); realtime.connection.once('connected', function () { - realtime.auth.authorize({ capability: { stillWrong: ['*'] } }, function (err) { + whenPromiseSettles(realtime.auth.authorize({ capability: { stillWrong: ['*'] } }), function (err) { try { expect(!err, 'Check first authorize cb was called').to.be.ok; } catch (err) { done(err); } }); - realtime.auth.authorize({ capability: { alsoNope: ['*'] } }, function (err) { + whenPromiseSettles(realtime.auth.authorize({ capability: { alsoNope: ['*'] } }), function (err) { try { expect(!err, 'Check second authorize cb was called').to.be.ok; } catch (err) { done(err); } }); - realtime.auth.authorize({ capability: { wtfAreYouThinking: ['*'] } }, function (err) { + whenPromiseSettles(realtime.auth.authorize({ capability: { wtfAreYouThinking: ['*'] } }), function (err) { try { expect(!err, 'Check third authorize one cb was called').to.be.ok; } catch (err) { done(err); } }); - realtime.auth.authorize({ capability: { right: ['*'] } }, function (err) { + whenPromiseSettles(realtime.auth.authorize({ capability: { right: ['*'] } }), function (err) { if (err) { closeAndFinish(done, realtime, err); } - realtime.channels.get('right').attach(function (err) { + whenPromiseSettles(realtime.channels.get('right').attach(), function (err) { try { expect(!err, (err && displayError(err)) || 'Successfully attached').to.be.ok; closeAndFinish(done, realtime); @@ -1359,7 +1368,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('authorize_immediately_after_init', function (realtimeOpts) { return function (done) { - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ useTokenAuth: true, defaultTokenParams: { capability: { wrong: ['*'] } }, }); @@ -1368,7 +1377,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async closeAndFinish(done, realtime, err); }); realtime.connection.once('connected', function () { - realtime.channels.get('right').attach(function (err) { + whenPromiseSettles(realtime.channels.get('right').attach(), function (err) { try { expect(!err, (err && displayError(err)) || 'Successfully attached').to.be.ok; closeAndFinish(done, realtime); diff --git a/test/realtime/channel.test.js b/test/realtime/channel.test.js index 5e463a9eae..9447865aa6 100644 --- a/test/realtime/channel.test.js +++ b/test/realtime/channel.test.js @@ -9,6 +9,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var monitorConnection = helper.monitorConnection; var createPM = Ably.Realtime.ProtocolMessage.fromDeserialized; var testOnAllTransports = helper.testOnAllTransports; + var whenPromiseSettles = helper.whenPromiseSettles; /* Helpers */ function randomString() { @@ -28,7 +29,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async callback(); }); - testChannel.publish(eventName, null, function (err) { + whenPromiseSettles(testChannel.publish(eventName, null), function (err) { if (received) return; if (err) callback(err); timeout = setTimeout(function () { @@ -52,7 +53,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async callback('checkCantSubscribe: unexpectedly received message'); }); - testChannel.publish(eventName, null, function (err) { + whenPromiseSettles(testChannel.publish(eventName, null), function (err) { if (received) return; if (err) callback(err); timeout = setTimeout(function () { @@ -65,13 +66,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async function checkCanPublish(channel) { return function (callback) { - channel.publish(null, null, callback); + whenPromiseSettles(channel.publish(null, null), callback); }; } function checkCantPublish(channel) { return function (callback) { - channel.publish(null, null, function (err) { + whenPromiseSettles(channel.publish(null, null), function (err) { if (err && err.code === 40160) { callback(); } else { @@ -84,7 +85,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async function checkCanEnterPresence(channel) { return function (callback) { var clientId = randomString(); - channel.presence.enterClient(clientId, null, function (err) { + whenPromiseSettles(channel.presence.enterClient(clientId, null), function (err) { channel.presence.leaveClient(clientId); callback(err); }); @@ -93,7 +94,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async function checkCantEnterPresence(channel) { return function (callback) { - channel.presence.enterClient(randomString(), null, function (err) { + whenPromiseSettles(channel.presence.enterClient(randomString(), null), function (err) { if (err && err.code === 40160) { callback(); } else { @@ -117,7 +118,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async callback(); }); - testChannel.presence.enterClient(clientId, null, function (err) { + whenPromiseSettles(testChannel.presence.enterClient(clientId, null), function (err) { if (received) return; if (err) callback(err); timeout = setTimeout(function () { @@ -143,7 +144,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async callback('checkCantPresenceSubscribe: unexpectedly received message'); }); - testChannel.presence.enterClient(clientId, null, function (err) { + whenPromiseSettles(testChannel.presence.enterClient(clientId, null), function (err) { if (received) return; if (err) callback(err); timeout = setTimeout(function () { @@ -176,7 +177,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelinit0', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.on('connected', function () { try { /* set options on init */ @@ -209,10 +210,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattach0', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.on('connected', function () { var channel0 = realtime.channels.get('channelattach0'); - channel0.attach(function (err) { + whenPromiseSettles(channel0.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); } @@ -232,9 +233,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattach2', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); var channel2 = realtime.channels.get('channelattach2'); - channel2.attach(function (err) { + whenPromiseSettles(channel2.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -256,14 +257,14 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.on('connected', function () { var channel0 = realtime.channels.get('channelattach3'); - channel0.attach(function (err) { + whenPromiseSettles(channel0.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); } - channel0.detach(function (err) { + whenPromiseSettles(channel0.detach(), function (err) { if (err) { closeAndFinish(done, realtime, err); } @@ -294,10 +295,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattachempty', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.once('connected', function () { var channel0 = realtime.channels.get(''); - channel0.attach(function (err) { + whenPromiseSettles(channel0.attach(), function (err) { if (err) { setTimeout(function () { try { @@ -326,10 +327,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattachinvalid', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.once('connected', function () { var channel = realtime.channels.get(':hell'); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { try { expect(channel.errorReason.code).to.equal(40010, 'Attach error was set as the channel errorReason'); @@ -364,9 +365,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('publish_no_attach', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.once('connected', function () { - realtime.channels.get('publish_no_attach').publish(function (err) { + whenPromiseSettles(realtime.channels.get('publish_no_attach').publish(), function (err) { if (err) { closeAndFinish(done, realtime, new Error('Unexpected attach failure: ' + helper.displayError(err))); return; @@ -387,9 +388,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattach_publish_invalid', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.once('connected', function () { - realtime.channels.get(':hell').publish(function (err) { + whenPromiseSettles(realtime.channels.get(':hell').publish(), function (err) { if (err) { try { expect(err.code).to.equal(40010, 'correct error code'); @@ -416,12 +417,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattach_invalid_twice', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.once('connected', function () { - realtime.channels.get(':hell').attach(function (err) { + whenPromiseSettles(realtime.channels.get(':hell').attach(), function (err) { if (err) { /* attempt second attach */ - realtime.channels.get(':hell').attach(function (err) { + whenPromiseSettles(realtime.channels.get(':hell').attach(), function (err) { if (err) { setTimeout(function () { try { @@ -452,11 +453,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('channelattachOnceOrIfAfter', function (done) { try { - var realtime = helper.AblyRealtime(), + var realtime = helper.AblyRealtimePromise(), channel = realtime.channels.get('channelattachOnceOrIf'), firedImmediately = false; - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { channel.whenState('attached', function () { firedImmediately = true; }); @@ -478,7 +479,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('channelattachOnceOrIfBefore', function (done) { try { - var realtime = helper.AblyRealtime(), + var realtime = helper.AblyRealtimePromise(), channel = realtime.channels.get('channelattachOnceOrIf'), firedImmediately = false; @@ -503,7 +504,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'attachWithChannelParamsBasicChannelsGet'; try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.on('connected', function () { var params = { modes: 'subscribe', @@ -513,7 +514,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async params: params, }; var channel = realtime.channels.get(testName, channelOptions); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -527,7 +528,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var testRealtime = helper.AblyRealtime(); + var testRealtime = helper.AblyRealtimePromise(); testRealtime.connection.on('connected', function () { var testChannel = testRealtime.channels.get(testName); async.series( @@ -556,7 +557,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'attachWithChannelParamsBasicSetOptions'; try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.on('connected', function () { var params = { modes: 'subscribe', @@ -567,7 +568,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }; var channel = realtime.channels.get(testName); channel.setOptions(channelOptions); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -576,7 +577,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async expect(channel.params).to.deep.equal(params, 'Check result params'); expect(channel.modes).to.deep.equal(['subscribe'], 'Check result modes'); - var testRealtime = helper.AblyRealtime(); + var testRealtime = helper.AblyRealtimePromise(); testRealtime.connection.on('connected', function () { var testChannel = testRealtime.channels.get(testName); async.series( @@ -605,7 +606,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'subscribeAfterSetOptions'; try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.on('connected', function () { var channel = realtime.channels.get(testName); channel.setOptions({ @@ -634,7 +635,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('channelGetShouldThrowWhenWouldCauseReattach', function (done) { var testName = 'channelGetShouldThrowWhenWouldCauseReattach'; try { - var realtime = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); realtime.connection.on('connected', function () { var params = { modes: 'subscribe', @@ -643,7 +644,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channel = realtime.channels.get(testName, { params: params, }); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -675,7 +676,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'setOptionsCallbackBehaviour'; try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.on('connected', function () { var params = { modes: 'subscribe', @@ -698,10 +699,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channelUpdated = true; }); - channel.setOptions( - { + whenPromiseSettles( + channel.setOptions({ params: params, - }, + }), function () { /* Wait a tick so we don' depend on whether the update event runs the * channelUpdated listener or the setOptions listener first */ @@ -721,10 +722,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channelUpdated = true; }); - channel.setOptions( - { + whenPromiseSettles( + channel.setOptions({ modes: modes, - }, + }), function () { Ably.Realtime.Platform.Config.nextTick(function () { expect(channelUpdated, 'Check channel went to the server to update the channel mode').to.be.ok; @@ -751,7 +752,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'attachWithChannelParamsModesAndChannelModes'; try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.on('connected', function () { var paramsModes = ['presence', 'subscribe']; var params = { @@ -762,7 +763,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async modes: ['publish', 'presence_subscribe'], }; var channel = realtime.channels.get(testName, channelOptions); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -776,7 +777,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var testRealtime = helper.AblyRealtime(); + var testRealtime = helper.AblyRealtimePromise(); testRealtime.connection.on('connected', function () { var testChannel = testRealtime.channels.get(testName); async.series( @@ -805,14 +806,14 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'attachWithChannelModes'; try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.on('connected', function () { var modes = ['publish', 'presence_subscribe']; var channelOptions = { modes: modes, }; var channel = realtime.channels.get(testName, channelOptions); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -825,7 +826,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var testRealtime = helper.AblyRealtime(); + var testRealtime = helper.AblyRealtimePromise(); testRealtime.connection.on('connected', function () { var testChannel = testRealtime.channels.get(testName); async.series( @@ -854,7 +855,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'attachWithChannelParamsDeltaAndModes'; try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.on('connected', function () { var modes = ['publish', 'subscribe', 'presence_subscribe']; var channelOptions = { @@ -862,7 +863,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async params: { delta: 'vcdiff' }, }; var channel = realtime.channels.get(testName, channelOptions); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -876,7 +877,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var testRealtime = helper.AblyRealtime(); + var testRealtime = helper.AblyRealtimePromise(); testRealtime.connection.on('connected', function () { var testChannel = testRealtime.channels.get(testName); async.series( @@ -905,13 +906,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var testName = 'attachWithInvalidChannelParams'; var defaultChannelModes = 'presence,publish,subscribe,presence_subscribe'; try { - var realtime = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); realtime.connection.on('connected', function () { var channel = realtime.channels.get(testName); async.series( [ function (cb) { - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { cb(err); }); }, @@ -919,7 +920,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelOptions = { modes: 'subscribe', }; - channel.setOptions(channelOptions, function (err) { + whenPromiseSettles(channel.setOptions(channelOptions), function (err) { expect(err.code).to.equal(40000, 'Check channelOptions validation error code'); expect(err.statusCode).to.equal(400, 'Check channelOptions validation error statusCode'); expect(channel.modes).to.deep.equal( @@ -933,7 +934,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelOptions = { modes: [1, 'subscribe'], }; - channel.setOptions(channelOptions, function (err) { + whenPromiseSettles(channel.setOptions(channelOptions), function (err) { expect(err.code).to.equal(40000, 'Check channelOptions validation error code'); expect(err.statusCode).to.equal(400, 'Check channelOptions validation error statusCode'); expect(channel.modes).to.deep.equal( @@ -947,7 +948,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelOptions = { params: 'test', }; - channel.setOptions(channelOptions, function (err) { + whenPromiseSettles(channel.setOptions(channelOptions), function (err) { expect(err.code).to.equal(40000, 'Check channelOptions validation error code'); expect(err.statusCode).to.equal(400, 'Check channelOptions validation error statusCode'); expect(channel.params).to.deep.equal({}, 'Check channel options params'); @@ -959,7 +960,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelOptions = { params: { nonexistent: 'foo' }, }; - channel.setOptions(channelOptions, function () { + whenPromiseSettles(channel.setOptions(channelOptions), function () { expect(channel.params).to.deep.equal({}, 'Check channel params'); cb(); }); @@ -968,7 +969,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelOptions = { modes: undefined, }; - channel.setOptions(channelOptions, function (err) { + whenPromiseSettles(channel.setOptions(channelOptions), function (err) { expect(err.code).to.equal(40000, 'Check channelOptions validation error code'); expect(err.statusCode).to.equal(400, 'Check channelOptions validation error statusCode'); expect(channel.params).to.deep.equal({}, 'Check channel options params result'); @@ -983,7 +984,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelOptions = { modes: ['susribe'], }; - channel.setOptions(channelOptions, function (err) { + whenPromiseSettles(channel.setOptions(channelOptions), function (err) { expect(err.code).to.equal(40000, 'Check channelOptions validation error code'); expect(err.statusCode).to.equal(400, 'Check channelOptions validation error statusCode'); expect(channel.params).to.deep.equal({}, 'Check channel options params result'); @@ -1011,10 +1012,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('channelsubscribe0', function (done) { try { - var realtime = helper.AblyRealtime({ useBinaryProtocol: true }); + var realtime = helper.AblyRealtimePromise({ useBinaryProtocol: true }); realtime.connection.on('connected', function () { var channel6 = realtime.channels.get('channelsubscribe0'); - channel6.attach(function (err) { + whenPromiseSettles(channel6.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -1047,28 +1048,28 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var messagesReceived = 0; try { - var realtime = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); var channelByEvent, channelByListener, channelAll; var unsubscribeTest = function () { channelByEvent.unsubscribe('event', listenerByEvent); channelByListener.unsubscribe(listenerNoEvent); channelAll.unsubscribe(); - channelByEvent.publish('event', 'data', function (err) { + whenPromiseSettles(channelByEvent.publish('event', 'data'), function (err) { try { expect(!err, 'Error publishing single event: ' + err).to.be.ok; } catch (err) { closeAndFinish(done, realtime, err); return; } - channelByListener.publish(null, 'data', function (err) { + whenPromiseSettles(channelByListener.publish(null, 'data'), function (err) { try { expect(!err, 'Error publishing any event: ' + err).to.be.ok; } catch (err) { closeAndFinish(done, realtime, err); return; } - channelAll.publish(null, 'data', function (err) { + whenPromiseSettles(channelAll.publish(null, 'data'), function (err) { try { expect(!err, 'Error publishing any event: ' + err).to.be.ok; expect(messagesReceived).to.equal(3, 'Only three messages should be received by the listeners'); @@ -1122,7 +1123,7 @@ 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 realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), channelName = 'server_sent_detached', channel = realtime.channels.get(channelName); @@ -1134,7 +1135,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.attach(cb); + whenPromiseSettles(channel.attach(), cb); }, function (cb) { /* Sabotage the reattach attempt, then simulate a server-sent detach */ @@ -1173,7 +1174,7 @@ 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 realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), channelName = 'server_sent_detached_while_attaching', channel = realtime.channels.get(channelName); @@ -1197,7 +1198,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async ); }); }; - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { try { expect(err.code).to.equal(50000, 'check error is propogated to the attach callback'); expect(channel.state).to.equal('suspended', 'check channel goes into suspended'); @@ -1213,12 +1214,12 @@ 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 realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), channelName = 'server_sent_error', channel = realtime.channels.get(channelName); realtime.connection.once('connected', function () { - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -1250,7 +1251,7 @@ 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 realtime = helper.AblyRealtimePromise(), channelName = 'server_sent_attached_err', channel = realtime.channels.get(channelName); @@ -1262,7 +1263,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.attach(cb); + whenPromiseSettles(channel.attach(), cb); }, function (cb) { channel.once(function (stateChange) { @@ -1294,11 +1295,11 @@ 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 realtime = helper.AblyRealtimePromise({ queueMessages: false }), channel = realtime.channels.get('publish_no_queueing'); /* try a publish while not yet connected */ - channel.publish('foo', 'bar', function (err) { + whenPromiseSettles(channel.publish('foo', 'bar'), function (err) { try { expect(err, 'Check publish while disconnected/connecting is rejected').to.be.ok; closeAndFinish(done, realtime); @@ -1313,7 +1314,7 @@ 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 realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport], realtimeRequestTimeout: 2000, channelRetryTimeout: 100, @@ -1332,7 +1333,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { expect(err, 'Channel attach timed out as expected').to.be.ok; expect(err && err.code).to.equal(90007, 'Attach timeout err passed to attach callback'); expect(channel.state).to.equal('suspended', 'Check channel state goes to suspended'); @@ -1361,7 +1362,7 @@ 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 realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport], channelRetryTimeout: 1010, suspendedRetryTimeout: 1100, @@ -1377,7 +1378,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.attach(cb); + whenPromiseSettles(channel.attach(), cb); }, function (cb) { /* Have the connection go into the suspended state, and check that the @@ -1429,7 +1430,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* RTL5i */ it('attached_while_detaching', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), channelName = 'server_sent_detached', channel = realtime.channels.get(channelName); @@ -1441,7 +1442,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.attach(cb); + whenPromiseSettles(channel.attach(), cb); }, function (cb) { /* Sabotage the detach attempt, detach, then simulate a server-sent attached while @@ -1472,12 +1473,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async // RTL5j it('detaching from suspended channel transitions channel to detached state', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); + var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }); var channelName = 'detach_from_suspended'; var channel = realtime.channels.get(channelName); channel.state = 'suspended'; - channel.detach(function () { + whenPromiseSettles(channel.detach(), function () { expect(channel.state).to.equal( 'detached', 'Check that detach on suspended channel results in detached channel' @@ -1488,13 +1489,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async // RTL5b it('detaching from failed channel results in error', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); + var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }); var channelName = 'detach_from_failed'; var channel = realtime.channels.get(channelName); channel.state = 'failed'; - channel.detach(function (err) { + whenPromiseSettles(channel.detach(), function (err) { if (!err) { done(new Error('expected detach to return error response')); return; @@ -1504,7 +1505,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('rewind works on channel after reattaching', function (done) { - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); + var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }); var channelName = 'rewind_after_detach'; var channel = realtime.channels.get(channelName); var channelOpts = { params: { rewind: '1' } }; @@ -1513,7 +1514,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var subscriber = function (message) { expect(message.data).to.equal('message'); channel.unsubscribe(subscriber); - channel.detach(function (err) { + whenPromiseSettles(channel.detach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; diff --git a/test/realtime/connection.test.js b/test/realtime/connection.test.js index 260e6fdae7..3922e745fb 100644 --- a/test/realtime/connection.test.js +++ b/test/realtime/connection.test.js @@ -6,6 +6,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var createPM = Ably.Realtime.ProtocolMessage.fromDeserialized; var displayError = helper.displayError; var monitorConnection = helper.monitorConnection; + var whenPromiseSettles = helper.whenPromiseSettles; describe('realtime/connection', function () { this.timeout(60 * 1000); @@ -22,7 +23,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('connectionPing', function (done) { var realtime; try { - realtime = helper.AblyRealtime(); + realtime = helper.AblyRealtimePromise(); realtime.connection.on('connected', function () { try { realtime.connection.ping(); @@ -40,9 +41,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('connectionPingWithCallback', function (done) { var realtime; try { - realtime = helper.AblyRealtime(); + realtime = helper.AblyRealtimePromise(); realtime.connection.on('connected', function () { - realtime.connection.ping(function (err, responseTime) { + whenPromiseSettles(realtime.connection.ping(), function (err, responseTime) { if (err) { closeAndFinish(done, realtime, err); return; @@ -65,7 +66,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('connectionAttributes', function (done) { var realtime; try { - realtime = helper.AblyRealtime({ logLevel: 4 }); + realtime = helper.AblyRealtimePromise({ logLevel: 4 }); realtime.connection.on('connected', function () { try { const recoveryContext = JSON.parse(realtime.connection.recoveryKey); @@ -77,7 +78,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } var channel = realtime.channels.get('connectionattributes'); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -95,7 +96,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.publish('name', 'data', cb); + whenPromiseSettles(channel.publish('name', 'data'), cb); }, ], function (err) { @@ -130,7 +131,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channelSerials: {}, }); try { - realtime = helper.AblyRealtime({ recover: fakeRecoveryKey }); + realtime = helper.AblyRealtimePromise({ recover: fakeRecoveryKey }); realtime.connection.on('connected', function (stateChange) { try { expect(stateChange.reason.code).to.equal( @@ -166,13 +167,13 @@ 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 realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), channel = realtime.channels.get('connectionQueuing'), connectionManager = realtime.connection.connectionManager; realtime.connection.once('connected', function () { var transport = connectionManager.activeProtocol.transport; - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -188,7 +189,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async [ function (cb) { /* Sabotaged publish */ - channel.publish('first', null, function (err) { + whenPromiseSettles(channel.publish('first', null), function (err) { try { expect(!err, 'Check publish happened (eventually) without err').to.be.ok; } catch (err) { @@ -247,7 +248,7 @@ 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 realtime = helper.AblyRealtimePromise(), connectionManager = realtime.connection.connectionManager; realtime.connection.once('connected', function () { connectionManager.once('connectiondetails', function (details) { @@ -286,7 +287,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async if (typeof Promise !== 'undefined') { describe('connection_promise', function () { it('ping', function (done) { - var client = helper.AblyRealtime({ internal: { promises: true } }); + var client = helper.AblyRealtimePromise({ internal: { promises: true } }); client.connection .once('connected') diff --git a/test/realtime/connectivity.test.js b/test/realtime/connectivity.test.js index ea4edc9177..ca3cfd4949 100644 --- a/test/realtime/connectivity.test.js +++ b/test/realtime/connectivity.test.js @@ -47,7 +47,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { } it('succeeds with scheme', function (done) { - new helper.AblyRealtime(options(urlScheme + successUrl)).http.checkConnectivity(function (err, res) { + new helper.AblyRealtimePromise(options(urlScheme + successUrl)).http.checkConnectivity(function (err, res) { try { expect(res && !err, 'Connectivity check completed ' + (err && utils.inspectError(err))).to.be.ok; } catch (err) { @@ -59,7 +59,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('fails with scheme', function (done) { - new helper.AblyRealtime(options(urlScheme + failUrl)).http.checkConnectivity(function (err, res) { + new helper.AblyRealtimePromise(options(urlScheme + failUrl)).http.checkConnectivity(function (err, res) { try { expect(!res, 'Connectivity check expected to return false').to.be.ok; done(); @@ -70,7 +70,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('succeeds with querystring', function (done) { - new helper.AblyRealtime(options(successUrl)).http.checkConnectivity(function (err, res) { + new helper.AblyRealtimePromise(options(successUrl)).http.checkConnectivity(function (err, res) { try { expect(res && !err, 'Connectivity check completed ' + (err && utils.inspectError(err))).to.be.ok; done(); @@ -81,7 +81,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('fails with querystring', function (done) { - new helper.AblyRealtime(options(failUrl)).http.checkConnectivity(function (err, res) { + new helper.AblyRealtimePromise(options(failUrl)).http.checkConnectivity(function (err, res) { try { expect(!res, 'Connectivity check expected to return false').to.be.ok; done(); @@ -92,7 +92,10 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('succeeds with plain url', function (done) { - new helper.AblyRealtime(options('sandbox-rest.ably.io/time')).http.checkConnectivity(function (err, res) { + new helper.AblyRealtimePromise(options('sandbox-rest.ably.io/time')).http.checkConnectivity(function ( + err, + res + ) { try { expect(res && !err, 'Connectivity check completed ' + (err && utils.inspectError(err))).to.be.ok; done(); @@ -103,7 +106,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('fails with plain url', function (done) { - new helper.AblyRealtime(options('echo.ably.io')).http.checkConnectivity(function (err, res) { + new helper.AblyRealtimePromise(options('echo.ably.io')).http.checkConnectivity(function (err, res) { try { expect(!res, 'Connectivity check expected to return false').to.be.ok; done(); @@ -115,7 +118,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('disable_connectivity_check', function (done) { - new helper.AblyRealtime({ + new helper.AblyRealtimePromise({ connectivityCheckUrl: 'notarealhost', disableConnectivityCheck: true, }).http.checkConnectivity(function (err, res) { diff --git a/test/realtime/crypto.test.js b/test/realtime/crypto.test.js index f54ffc3cd3..a430aefa23 100644 --- a/test/realtime/crypto.test.js +++ b/test/realtime/crypto.test.js @@ -11,12 +11,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var msgpack = typeof window == 'object' ? Ably.msgpack : require('@ably/msgpack-js'); var testOnAllTransports = helper.testOnAllTransports; var closeAndFinish = helper.closeAndFinish; + var whenPromiseSettles = helper.whenPromiseSettles; function attachChannels(channels, callback) { async.map( channels, function (channel, cb) { - channel.attach(cb); + whenPromiseSettles(channel.attach(), cb); }, callback ); @@ -61,7 +62,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async done(new Error('Unable to get test assets; err = ' + displayError(err))); return; } - var realtime = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); var key = BufferUtils.base64Decode(testData.key); var iv = BufferUtils.base64Decode(testData.iv); var channel = realtime.channels.get(channelName, { cipher: { key: key, iv: iv } }); @@ -408,11 +409,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* For single_send tests we test the 'shortcut' way of setting the cipher * in channels.get. No callback, but that's ok even for node which has * async iv generation since the publish is on an attach cb */ - var realtime = helper.AblyRealtime(realtimeOpts), + var realtime = helper.AblyRealtimePromise(realtimeOpts), channel = realtime.channels.get('single_send', { cipher: { key: key } }), messageText = 'Test message for single_send - ' + JSON.stringify(realtimeOpts); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -458,7 +459,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var realtime = helper.AblyRealtime({ useBinaryProtocol: !text }); + var realtime = helper.AblyRealtimePromise({ useBinaryProtocol: !text }); var channelName = 'multiple_send_' + (text ? 'text_' : 'binary_') + iterations + '_' + delay, channel = realtime.channels.get(channelName), messageText = 'Test message (' + channelName + ')'; @@ -526,8 +527,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtime(txOpts), - rxRealtime = helper.AblyRealtime(rxOpts), + var txRealtime = helper.AblyRealtimePromise(txOpts), + rxRealtime = helper.AblyRealtimePromise(rxOpts), channelName = 'single_send_separate_realtimes'; var messageText = 'Test message for single_send_separate_realtimes', txChannel = txRealtime.channels.get(channelName), @@ -602,8 +603,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtime(), - rxRealtime = helper.AblyRealtime(), + var txRealtime = helper.AblyRealtimePromise(), + rxRealtime = helper.AblyRealtimePromise(), channelName = 'publish_immediately', messageText = 'Test message'; @@ -644,8 +645,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtime(); - var rxRealtime = helper.AblyRealtime(); + var txRealtime = helper.AblyRealtimePromise(); + var rxRealtime = helper.AblyRealtimePromise(); var channelName = 'single_send_key_mismatch', txChannel = txRealtime.channels.get(channelName), messageText = 'Test message (' + channelName + ')', @@ -653,8 +654,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async async.parallel( [ - Crypto.generateRandomKey, - Crypto.generateRandomKey, + function (cb) { + Crypto.generateRandomKey(cb); + }, + function (cb) { + Crypto.generateRandomKey(cb); + }, function (cb) { attachChannels([txChannel, rxChannel], cb); }, @@ -706,8 +711,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtime(); - var rxRealtime = helper.AblyRealtime(); + var txRealtime = helper.AblyRealtimePromise(); + var rxRealtime = helper.AblyRealtimePromise(); var channelName = 'single_send_unencrypted', txChannel = txRealtime.channels.get(channelName), messageText = 'Test message (' + channelName + ')', @@ -749,8 +754,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtime(); - var rxRealtime = helper.AblyRealtime(); + var txRealtime = helper.AblyRealtimePromise(); + var rxRealtime = helper.AblyRealtimePromise(); var channelName = 'single_send_encrypted_unhandled', txChannel = txRealtime.channels.get(channelName), messageText = 'Test message (' + channelName + ')', @@ -793,8 +798,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtime(); - var rxRealtime = helper.AblyRealtime(); + var txRealtime = helper.AblyRealtimePromise(); + var rxRealtime = helper.AblyRealtimePromise(); var channelName = 'set_cipher_params', txChannel = txRealtime.channels.get(channelName), messageText = 'Test message (' + channelName + ')', diff --git a/test/realtime/delta.test.js b/test/realtime/delta.test.js index 9b42c428ee..b66d5951c5 100644 --- a/test/realtime/delta.test.js +++ b/test/realtime/delta.test.js @@ -5,6 +5,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (helper, v var displayError = helper.displayError; var closeAndFinish = helper.closeAndFinish; var monitorConnection = helper.monitorConnection; + var whenPromiseSettles = helper.whenPromiseSettles; var testData = [ { foo: 'bar', count: 1, status: 'active' }, { foo: 'bar', count: 2, status: 'active' }, @@ -43,14 +44,14 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (helper, v var testName = 'deltaPlugin'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ plugins: { vcdiff: testVcdiffDecoder, }, }); var channel = realtime.channels.get(testName, { params: { delta: 'vcdiff' } }); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); } @@ -92,16 +93,16 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (helper, v var testName = 'unusedPlugin'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ plugins: { vcdiff: testVcdiffDecoder, }, }); var channel = realtime.channels.get(testName); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { - closeAndFinish(doner, realtime, err); + closeAndFinish(done, realtime, err); } channel.subscribe(function (message) { try { @@ -132,14 +133,14 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (helper, v var testName = 'lastMessageNotFoundRecovery'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ plugins: { vcdiff: testVcdiffDecoder, }, }); var channel = realtime.channels.get(testName, { params: { delta: 'vcdiff' } }); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); } @@ -200,14 +201,14 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (helper, v }, }; - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ plugins: { vcdiff: failingTestVcdiffDecoder, }, }); var channel = realtime.channels.get(testName, { params: { delta: 'vcdiff' } }); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); } @@ -245,10 +246,10 @@ 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) { try { - var realtime = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); var channel = realtime.channels.get('noPlugin', { params: { delta: 'vcdiff' } }); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); } diff --git a/test/realtime/encoding.test.js b/test/realtime/encoding.test.js index aeef0b94f7..b7837a8ab5 100644 --- a/test/realtime/encoding.test.js +++ b/test/realtime/encoding.test.js @@ -8,6 +8,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var encodingFixturesPath = helper.testResourcesPath + 'messages-encoding.json'; var closeAndFinish = helper.closeAndFinish; var Defaults = Ably.Rest.Platform.Defaults; + var whenPromiseSettles = helper.whenPromiseSettles; describe('realtime/encoding', function () { this.timeout(60 * 1000); @@ -31,8 +32,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async done(err); return; } - var realtime = helper.AblyRealtime({ useBinaryProtocol: false }), - binaryrealtime = helper.AblyRealtime({ useBinaryProtocol: true }), + var realtime = helper.AblyRealtimePromise({ useBinaryProtocol: false }), + binaryrealtime = helper.AblyRealtimePromise({ useBinaryProtocol: true }), channelName = 'message_decoding', channelPath = '/channels/' + channelName + '/messages', channel = realtime.channels.get(channelName), @@ -41,10 +42,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async async.parallel( [ function (attachCb) { - channel.attach(attachCb); + whenPromiseSettles(channel.attach(), attachCb); }, function (attachCb) { - binarychannel.attach(attachCb); + whenPromiseSettles(binarychannel.attach(), attachCb); }, ], function (err) { @@ -96,13 +97,15 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (parallelCb) { - realtime.request( - 'post', - channelPath, - Defaults.protocolVersion, - null, - { name: name, data: encodingSpec.data, encoding: encodingSpec.encoding }, - null, + whenPromiseSettles( + realtime.request( + 'post', + channelPath, + Defaults.protocolVersion, + null, + { name: name, data: encodingSpec.data, encoding: encodingSpec.encoding }, + null + ), function (err) { parallelCb(err); } @@ -130,8 +133,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async done(new Error('Unable to get test assets; err = ' + displayError(err))); return; } - var realtime = helper.AblyRealtime({ useBinaryProtocol: false }), - binaryrealtime = helper.AblyRealtime({ useBinaryProtocol: true }), + var realtime = helper.AblyRealtimePromise({ useBinaryProtocol: false }), + binaryrealtime = helper.AblyRealtimePromise({ useBinaryProtocol: true }), channelName = 'message_encoding', channelPath = '/channels/' + channelName + '/messages', channel = realtime.channels.get(channelName), @@ -140,10 +143,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async async.parallel( [ function (attachCb) { - channel.attach(attachCb); + whenPromiseSettles(channel.attach(), attachCb); }, function (attachCb) { - binarychannel.attach(attachCb); + whenPromiseSettles(binarychannel.attach(), attachCb); }, ], function (err) { @@ -165,10 +168,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async async.parallel( [ function (parallelCb) { - channel.publish(name, data, parallelCb); + whenPromiseSettles(channel.publish(name, data), parallelCb); }, function (parallelCb) { - binarychannel.publish(name, data, parallelCb); + whenPromiseSettles(binarychannel.publish(name, data), parallelCb); }, ], function (err) { @@ -176,13 +179,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async eachOfCb(err); return; } - realtime.request( - 'get', - channelPath, - Defaults.protocolVersion, - null, - null, - null, + whenPromiseSettles( + realtime.request('get', channelPath, Defaults.protocolVersion, null, null, null), function (err, resultPage) { if (err) { eachOfCb(err); diff --git a/test/realtime/event_emitter.test.js b/test/realtime/event_emitter.test.js index 4575594f21..36043e2b7d 100644 --- a/test/realtime/event_emitter.test.js +++ b/test/realtime/event_emitter.test.js @@ -28,7 +28,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { /* Note: realtime now sends an ATTACHED post-upgrade, which can race with * the DETACHED if the DETACH is only sent just after upgrade. Remove * bestTransport with 1.1 spec which has IDs in ATTACHs */ - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), index, expectedConnectionEvents = ['connecting', 'connected', 'closing', 'closed'], expectedChannelEvents = ['attaching', 'attached', 'detaching', 'detached']; @@ -74,7 +74,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('emitCallsAllCallbacksIgnoringExceptions', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ autoConnect: false }), callbackCalled = false, eventEmitter = realtime.connection; @@ -99,7 +99,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('onceCalledOnlyOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ autoConnect: false }), onCallbackCalled = 0, onceCallbackCalled = 0, eventEmitter = realtime.connection; @@ -127,7 +127,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('onceCallbackDoesNotImpactOnCallback', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -153,7 +153,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('offRemovesAllMatchingListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -182,7 +182,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('offRemovesAllListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -211,7 +211,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('offRemovesAllMatchingEventListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -240,7 +240,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('offRemovesAllMatchingEvents', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -276,7 +276,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { * for each previously registered event name */ it('offRemovesEmptyEventNameListeners', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ autoConnect: false }), eventEmitter = realtime.connection; var callback = function () {}; @@ -304,7 +304,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('arrayOfEvents', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -343,7 +343,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('arrayOfEventsWithOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -370,7 +370,7 @@ 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 realtime = helper.AblyRealtimePromise({ autoConnect: false }), eventEmitter = realtime.connection, firstCbCalled = false, secondCbCalled = false; @@ -397,7 +397,7 @@ 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 realtime = helper.AblyRealtimePromise({ autoConnect: false }), eventEmitter = realtime.connection, onCbCalledTimes = 0, onceCbCalledTimes = 0, @@ -442,7 +442,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { if (typeof Promise !== 'undefined') { describe('event_emitter_promise', function () { it('whenState', function (done) { - var realtime = helper.AblyRealtime({ internal: { promises: true } }); + var realtime = helper.AblyRealtimePromise({ internal: { promises: true } }); var eventEmitter = realtime.connection; eventEmitter @@ -456,7 +456,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('once', function (done) { - var realtime = helper.AblyRealtime({ internal: { promises: true } }); + var realtime = helper.AblyRealtimePromise({ internal: { promises: true } }); var eventEmitter = realtime.connection; eventEmitter @@ -470,7 +470,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('anyEventsWithOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ autoConnect: false }), eventEmitter = realtime.connection; const p = eventEmitter.once(); @@ -483,7 +483,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('arrayOfEventsWithOnce', function (done) { - var realtime = helper.AblyRealtime({ autoConnect: false }), + var realtime = helper.AblyRealtimePromise({ 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 142ac9c5f1..c8576e578d 100644 --- a/test/realtime/failure.test.js +++ b/test/realtime/failure.test.js @@ -8,6 +8,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var simulateDroppedConnection = helper.simulateDroppedConnection; var createPM = Ably.Realtime.ProtocolMessage.fromDeserialized; var availableTransports = helper.availableTransports; + var whenPromiseSettles = helper.whenPromiseSettles; describe('realtime/failure', function () { this.timeout(60 * 1000); @@ -28,7 +29,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { var failure_test = function (transports) { return function (cb) { - var realtime = helper.AblyRealtime({ key: 'this.is:wrong', transports: transports }); + var realtime = helper.AblyRealtimePromise({ key: 'this.is:wrong', transports: transports }); realtime.connection.on('failed', function (connectionStateChange) { try { expect(realtime.connection.errorReason.code).to.equal(40400, 'wrong error reason code on connection.'); @@ -77,7 +78,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { var break_test = function (transports) { return function (cb) { - var realtime = helper.AblyRealtime({ transports: transports }); + var realtime = helper.AblyRealtimePromise({ transports: transports }); realtime.connection.once('connected', function () { realtime.connection.once('disconnected', function () { cb(null, realtime); @@ -116,7 +117,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var lifecycleTest = function (transports) { return function (cb) { var connectionEvents = []; - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ transports: transports, realtimeHost: 'invalid', restHost: 'invalid', @@ -188,7 +189,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async utils.arrForEach(availableTransports, function (transport) { it('disconnected_backoff_' + transport, function (done) { var disconnectedRetryTimeout = 150; - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ disconnectedRetryTimeout: disconnectedRetryTimeout, realtimeHost: 'invalid', restHost: 'invalid', @@ -219,13 +220,13 @@ 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) { - var realtime = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); var failChan; var channelFailedCode = 90001; var tests = [ function (callback) { - failChan.publish('event', 'data', function (err) { + whenPromiseSettles(failChan.publish('event', 'data'), function (err) { try { expect(err, 'publish failed').to.be.ok; expect(err.code).to.equal(channelFailedCode, 'publish failure code'); @@ -247,7 +248,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (callback) { - failChan.presence.enterClient('clientId', function (err) { + whenPromiseSettles(failChan.presence.enterClient('clientId'), function (err) { try { expect(err, 'presence enter failed').to.be.ok; expect(err.code).to.equal(channelFailedCode, 'presence enter failure code'); @@ -258,7 +259,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (callback) { - failChan.presence.leaveClient('clientId', function (err) { + whenPromiseSettles(failChan.presence.leaveClient('clientId'), function (err) { try { expect(err, 'presence leave failed').to.be.ok; expect(err.code).to.equal(channelFailedCode, 'presence leave failure code'); @@ -291,7 +292,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (callback) { - failChan.presence.get(function (err) { + whenPromiseSettles(failChan.presence.get(), function (err) { try { expect(err, 'presence get failed').to.be.ok; expect(err.code).to.equal(channelFailedCode, 'presence get failure code'); @@ -306,7 +307,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { realtime.connection.once('connected', function () { failChan = realtime.channels.get('::'); - failChan.attach(function (err) { + whenPromiseSettles(failChan.attach(), function (err) { try { expect(err, 'channel attach failed').to.be.ok; expect(failChan.state).to.equal('failed', 'channel in failed state'); @@ -325,7 +326,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('attach_timeout', function (done) { - var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000, channelRetryTimeout: 1000 }), + var realtime = helper.AblyRealtimePromise({ realtimeRequestTimeout: 2000, channelRetryTimeout: 1000 }), channel = realtime.channels.get('failed_attach'), originalProcessMessage = channel.processMessage.bind(channel); @@ -337,7 +338,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }; realtime.connection.once('connected', function () { - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { try { expect(err.code).to.equal(90007, 'check channel error code'); expect(err.statusCode).to.equal(408, 'check timeout statusCode'); @@ -361,7 +362,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async utils.arrForEach(availableTransports, function (transport) { it('channel_backoff_' + transport, function (done) { var channelRetryTimeout = 150; - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ channelRetryTimeout: channelRetryTimeout, transports: [transport], }), @@ -381,7 +382,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async realtime.connection.on('connected', function () { realtime.options.timeouts.realtimeRequestTimeout = 1; - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { var lastSuspended = performance.now(); channel.on(function (stateChange) { @@ -422,7 +423,7 @@ 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 realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), channel = realtime.channels.get('nack_on_connection_failure'); async.series( @@ -433,7 +434,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.attach(cb); + whenPromiseSettles(channel.attach(), cb); }, function (cb) { var transport = realtime.connection.connectionManager.activeProtocol.transport, @@ -445,7 +446,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async originalOnProtocolMessage.apply(this, arguments); } }; - channel.publish('foo', 'bar', function (err) { + whenPromiseSettles(channel.publish('foo', 'bar'), function (err) { try { expect(err, 'Publish failed as expected').to.be.ok; expect(realtime.connection.state).to.equal( @@ -507,7 +508,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async ); it('idle_transport_timeout', function (done) { - var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000 }), + var realtime = helper.AblyRealtimePromise({ realtimeRequestTimeout: 2000 }), originalOnProtocolMessage; realtime.connection.connectionManager.on('transport.pending', function (transport) { @@ -545,7 +546,7 @@ 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(utils.mixin({ fallbackHosts: ['echo.ably.io'] }, realtimeOpts)), + var realtime = helper.AblyRealtimePromise(utils.mixin({ fallbackHosts: ['echo.ably.io'] }, realtimeOpts)), connection = realtime.connection, connectionManager = connection.connectionManager; @@ -585,7 +586,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var testMessage2 = { foo: 'bar', count: 2, status: 'active' }; try { - var sender_realtime = helper.AblyRealtime(); + var sender_realtime = helper.AblyRealtimePromise(); var sender_channel = sender_realtime.channels.get(testName); var messageReceived = false; diff --git a/test/realtime/history.test.js b/test/realtime/history.test.js index 1017749c00..73112e343f 100644 --- a/test/realtime/history.test.js +++ b/test/realtime/history.test.js @@ -11,11 +11,12 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { }); var closeAndFinish = helper.closeAndFinish; var monitorConnection = helper.monitorConnection; + var whenPromiseSettles = helper.whenPromiseSettles; var parallelPublishMessages = function (done, channel, messages, callback) { var publishTasks = utils.arrMap(messages, function (event) { return function (publishCb) { - channel.publish(event.name, event.data, publishCb); + whenPromiseSettles(channel.publish(event.name, event.data), publishCb); }; }); @@ -46,8 +47,8 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { }); it('history_until_attach', function (done) { - var rest = helper.AblyRest(); - var realtime = helper.AblyRealtime(); + var rest = helper.AblyRestPromise(); + var realtime = helper.AblyRealtimePromise(); var restChannel = rest.channels.get('persisted:history_until_attach'); /* first, send a number of events to this channel before attaching */ @@ -56,7 +57,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { try { realtime.connection.whenState('connected', function () { var rtChannel = realtime.channels.get('persisted:history_until_attach'); - rtChannel.attach(function (err) { + whenPromiseSettles(rtChannel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -72,7 +73,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { var tests = [ function (callback) { - rtChannel.history(function (err, resultPage) { + whenPromiseSettles(rtChannel.history(), function (err, resultPage) { if (err) { callback(err); } @@ -89,7 +90,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { }); }, function (callback) { - rtChannel.history({ untilAttach: false }, function (err, resultPage) { + whenPromiseSettles(rtChannel.history({ untilAttach: false }), function (err, resultPage) { if (err) { callback(err); } @@ -106,7 +107,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { }); }, function (callback) { - rtChannel.history({ untilAttach: true }, function (err, resultPage) { + whenPromiseSettles(rtChannel.history({ untilAttach: true }), function (err, resultPage) { if (err) { callback(err); } diff --git a/test/realtime/init.test.js b/test/realtime/init.test.js index cc3557b1ce..e494f2708e 100644 --- a/test/realtime/init.test.js +++ b/test/realtime/init.test.js @@ -4,6 +4,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var expect = chai.expect; var closeAndFinish = helper.closeAndFinish; var monitorConnection = helper.monitorConnection; + var whenPromiseSettles = helper.whenPromiseSettles; describe('realtime/init', function () { this.timeout(60 * 1000); @@ -28,7 +29,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('initbase0', function (done) { var realtime; try { - realtime = helper.AblyRealtime({ transports: ['web_socket', 'xhr_streaming'] }); + realtime = helper.AblyRealtimePromise({ transports: ['web_socket', 'xhr_streaming'] }); realtime.connection.on('connected', function () { /* check api version */ var transport = realtime.connection.connectionManager.activeProtocol.transport; @@ -53,7 +54,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; - realtime = new helper.Ably.Realtime(keyStr); + realtime = new helper.Ably.Realtime.Promise(keyStr); try { expect(realtime.options.key).to.equal(keyStr); @@ -72,17 +73,17 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('init_token_string', function (done) { try { /* first generate a token ... */ - var rest = helper.AblyRest(); + var rest = helper.AblyRestPromise(); var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; - rest.auth.requestToken(null, testKeyOpts, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken(null, testKeyOpts), function (err, tokenDetails) { if (err) { done(err); return; } var tokenStr = tokenDetails.token, - realtime = new helper.Ably.Realtime(tokenStr); + realtime = new helper.Ably.Realtime.Promise(tokenStr); try { expect(realtime.options.token).to.equal(tokenStr); @@ -102,7 +103,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; - realtime = helper.AblyRealtime({ key: keyStr, useTokenAuth: true }); + realtime = helper.AblyRealtimePromise({ key: keyStr, useTokenAuth: true }); expect(realtime.options.key).to.equal(keyStr); expect(realtime.auth.method).to.equal('token'); expect(realtime.auth.clientId).to.equal(undefined); @@ -127,7 +128,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; - realtime = helper.AblyRealtime({ + realtime = helper.AblyRealtimePromise({ key: keyStr, useTokenAuth: true, defaultTokenParams: { clientId: '*', ttl: 123456 }, @@ -155,7 +156,11 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; - realtime = helper.AblyRealtime({ key: keyStr, useTokenAuth: true, defaultTokenParams: { clientId: 'test' } }); + realtime = helper.AblyRealtimePromise({ + key: keyStr, + useTokenAuth: true, + defaultTokenParams: { clientId: 'test' }, + }); expect(realtime.auth.clientId).to.equal(undefined); realtime.connection.on('connected', function () { try { @@ -177,7 +182,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; - realtime = helper.AblyRealtime({ + realtime = helper.AblyRealtimePromise({ key: keyStr, useTokenAuth: true, clientId: 'yes', @@ -203,7 +208,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { try { var keyStr = helper.getTestApp().keys[0].keyStr; expect(function () { - realtime = new helper.Ably.Realtime({ key: keyStr, useTokenAuth: false, clientId: 'foo' }); + realtime = new helper.Ably.Realtime.Promise({ key: keyStr, useTokenAuth: false, clientId: 'foo' }); }).to.throw; done(); } catch (err) { @@ -217,7 +222,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { /* 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 * test env */ - var realtime = new Ably.Realtime({ key: 'not_a.real:key', autoConnect: false }); + var realtime = new Ably.Realtime.Promise({ key: 'not_a.real:key', autoConnect: false }); var defaultHost = realtime.connection.connectionManager.httpHosts[0]; expect(defaultHost).to.equal('rest.ably.io', 'Verify correct default rest host chosen'); realtime.close(); @@ -230,7 +235,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { /* check changing the default timeouts */ it('init_timeouts', function (done) { try { - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ key: 'not_a.real:key', disconnectedRetryTimeout: 123, suspendedRetryTimeout: 456, @@ -263,7 +268,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { /* check changing the default fallback hosts and changing httpMaxRetryCount */ it('init_fallbacks', function (done) { try { - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ key: 'not_a.real:key', restHost: 'a', httpMaxRetryCount: 2, @@ -311,7 +316,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('node_transports', function (done) { var realtime; try { - realtime = helper.AblyRealtime({ transports: helper.availableTransports }); + realtime = helper.AblyRealtimePromise({ transports: helper.availableTransports }); expect(realtime.connection.connectionManager.baseTransport).to.equal('comet'); expect(realtime.connection.connectionManager.upgradeTransports).to.deep.equal(['web_socket']); closeAndFinish(done, realtime); @@ -326,7 +331,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('init_and_connection_details', function (done) { try { var keyStr = helper.getTestApp().keys[0].keyStr; - var realtime = helper.AblyRealtime({ key: keyStr, useTokenAuth: true }); + var realtime = helper.AblyRealtimePromise({ key: keyStr, useTokenAuth: true }); realtime.connection.connectionManager.once('transport.pending', function (state) { var transport = realtime.connection.connectionManager.pendingTransports[0], originalOnProtocolMessage = transport.onProtocolMessage; @@ -365,7 +370,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('init_fallbacks_once_connected', function (done) { - var realtime = helper.AblyRealtime({ + var realtime = helper.AblyRealtimePromise({ httpMaxRetryCount: 3, fallbackHosts: ['a', 'b', 'c'], }); @@ -385,8 +390,8 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('init_fallbacks_once_connected_2', function (done) { - var goodHost = helper.AblyRest().options.realtimeHost; - var realtime = helper.AblyRealtime({ + var goodHost = helper.AblyRestPromise().options.realtimeHost; + var realtime = helper.AblyRealtimePromise({ httpMaxRetryCount: 3, restHost: 'a', fallbackHosts: [goodHost, 'b', 'c'], @@ -414,18 +419,12 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { return { key: keyStr, autoConnect: false }; }; - realtime = new Ably.Realtime(getOptions()); - expect(!realtime.options.promises, 'Check promises defaults to false').to.be.ok; - realtime = new Ably.Realtime.Promise(getOptions()); expect(realtime.options.promises, 'Check promises default to true with promise constructor').to.be.ok; if (!isBrowser && typeof require == 'function') { realtime = new require('../../promises').Realtime(getOptions()); expect(realtime.options.promises, 'Check promises default to true with promise require target').to.be.ok; - - realtime = new require('../../callbacks').Realtime(getOptions()); - expect(!realtime.options.promises, 'Check promises default to false with callback require target').to.be.ok; } done(); } catch (err) { diff --git a/test/realtime/message.test.js b/test/realtime/message.test.js index 3cd4f663e5..c5463cb692 100644 --- a/test/realtime/message.test.js +++ b/test/realtime/message.test.js @@ -9,10 +9,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var createPM = Ably.Realtime.ProtocolMessage.fromDeserialized; var monitorConnection = helper.monitorConnection; var testOnAllTransports = helper.testOnAllTransports; + var whenPromiseSettles = helper.whenPromiseSettles; var publishIntervalHelper = function (currentMessageNum, channel, dataFn, onPublish) { return function () { - channel.publish('event0', dataFn(), function () { + whenPromiseSettles(channel.publish('event0', dataFn()), function () { onPublish(); }); }; @@ -38,14 +39,14 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('publishonce', function (done) { try { /* set up realtime */ - var realtime = helper.AblyRealtime(); - var rest = helper.AblyRest(); + var realtime = helper.AblyRealtimePromise(); + var rest = helper.AblyRestPromise(); /* connect and attach */ realtime.connection.on('connected', function () { var testMsg = 'Hello world'; var rtChannel = realtime.channels.get('publishonce'); - rtChannel.attach(function (err) { + whenPromiseSettles(rtChannel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -79,10 +80,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('publishfast', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); realtime.connection.once('connected', function () { var channel = realtime.channels.get('publishfast_' + String(Math.random()).substr(2)); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -100,7 +101,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async function (cb) { var ackd = 0; var publish = function (i) { - channel.publish('event', i.toString(), function (err) { + whenPromiseSettles(channel.publish('event', i.toString()), function (err) { try { expect( !err, @@ -143,8 +144,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var txRealtime, rxRealtime; try { - txRealtime = helper.AblyRealtime(utils.mixin(realtimeOpts, { autoConnect: false })); - rxRealtime = helper.AblyRealtime(); + txRealtime = helper.AblyRealtimePromise(utils.mixin(realtimeOpts, { autoConnect: false })); + rxRealtime = helper.AblyRealtimePromise(); var txChannel = txRealtime.channels.get('publishQueued_' + String(Math.random()).substr(2)); var rxChannel = rxRealtime.channels.get(txChannel.name); @@ -156,7 +157,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - rxChannel.attach(function (err) { + whenPromiseSettles(rxChannel.attach(), function (err) { cb(err); }); }, @@ -180,7 +181,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async function (parCb) { var ackd = 0; var publish = function (i) { - txChannel.publish('event', { num: i }, function (err) { + whenPromiseSettles(txChannel.publish('event', { num: i }), function (err) { try { expect( !err, @@ -231,8 +232,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 }), - rtEcho = helper.AblyRealtime({ echoMessages: true }), + var rtNoEcho = helper.AblyRealtimePromise({ echoMessages: false }), + rtEcho = helper.AblyRealtimePromise({ echoMessages: true }), rtNoEchoChannel = rtNoEcho.channels.get('publishecho'), rtEchoChannel = rtEcho.channels.get('publishecho'), testMsg1 = 'Hello', @@ -259,7 +260,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }; // attach rtNoEchoChannel - rtNoEchoChannel.attach(function (err) { + whenPromiseSettles(rtNoEchoChannel.attach(), function (err) { try { expect(!err, 'Attached to rtNoEchoChannel with no error').to.be.ok; } catch (err) { @@ -275,7 +276,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); // attach rtEchoChannel - rtEchoChannel.attach(function (err) { + whenPromiseSettles(rtEchoChannel.attach(), function (err) { try { expect(!err, 'Attached to rtEchoChannel with no error').to.be.ok; } catch (err) { @@ -291,7 +292,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); // publish testMsg1 via rtNoEcho - rtNoEchoChannel.publish('event0', testMsg1, function () { + whenPromiseSettles(rtNoEchoChannel.publish('event0', testMsg1), function () { // publish testMsg2 via rtEcho rtEchoChannel.publish('event0', testMsg2); }); @@ -322,13 +323,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { /* set up realtime */ - realtime = helper.AblyRealtime(); - var rest = helper.AblyRest(); + realtime = helper.AblyRealtimePromise(); + var rest = helper.AblyRestPromise(); /* connect and attach */ realtime.connection.on('connected', function () { var rtChannel = realtime.channels.get('publishVariations'); - rtChannel.attach(function (err) { + whenPromiseSettles(rtChannel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -428,13 +429,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { /* set up realtime */ - var realtime = helper.AblyRealtime(); - var rest = helper.AblyRest(); + var realtime = helper.AblyRealtimePromise(); + var rest = helper.AblyRestPromise(); /* connect and attach */ realtime.connection.on('connected', function () { var rtChannel = realtime.channels.get('publishDisallowed'); - rtChannel.attach(function (err) { + whenPromiseSettles(rtChannel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -445,7 +446,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var restChannel = rest.channels.get('publishDisallowed'); for (var i = 0; i < testArguments.length; i++) { try { - restChannel.publish.apply(restChannel, testArguments[i]); + await restChannel.publish.apply(restChannel, testArguments[i]); closeAndFinish(done, realtime, new Error('Exception was not raised')); } catch (err) { try { @@ -482,13 +483,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { /* set up realtime */ - var realtime = helper.AblyRealtime(); - var rest = helper.AblyRest(); + var realtime = helper.AblyRealtimePromise(); + var rest = helper.AblyRestPromise(); /* connect and attach */ realtime.connection.on('connected', function () { var rtChannel = realtime.channels.get('publishEncodings'); - rtChannel.attach(function (err) { + whenPromiseSettles(rtChannel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -535,7 +536,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testArguments, function iterator(item, callback) { try { - restChannel.publish(item, function (err) { + whenPromiseSettles(restChannel.publish(item), function (err) { try { expect(!err, 'Successfully published').to.be.ok; } catch (err) { @@ -564,8 +565,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('restpublish', function (done) { var count = 10; - var rest = helper.AblyRest(); - var realtime = helper.AblyRealtime(); + var rest = helper.AblyRestPromise(); + var realtime = helper.AblyRealtimePromise(); var messagesSent = []; var sendchannel = rest.channels.get('restpublish'); var recvchannel = realtime.channels.get('restpublish'); @@ -603,7 +604,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async --cbCount; checkFinish(); }; - var realtime = helper.AblyRealtime(realtimeOpts); + var realtime = helper.AblyRealtimePromise(realtimeOpts); var channel = realtime.channels.get('publish ' + JSON.stringify(realtimeOpts)); /* subscribe to event */ channel.subscribe( @@ -626,7 +627,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async and is implicitly added when published */ it('implicit_client_id_0', function (done) { var clientId = 'implicit_client_id_0', - realtime = helper.AblyRealtime({ clientId: clientId }); + realtime = helper.AblyRealtimePromise({ clientId: clientId }); realtime.connection.once('connected', function () { var transport = realtime.connection.connectionManager.activeProtocol.transport, @@ -665,7 +666,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('explicit_client_id_0', function (done) { var clientId = 'explicit_client_id_0', /* Use a fixed transport as intercepting transport.send */ - realtime = helper.AblyRealtime({ clientId: clientId, transports: [helper.bestTransport] }); + realtime = helper.AblyRealtimePromise({ clientId: clientId, transports: [helper.bestTransport] }); realtime.connection.once('connected', function () { var transport = realtime.connection.connectionManager.activeProtocol.transport, @@ -685,7 +686,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channel = realtime.channels.get('explicit_client_id_0'); /* subscribe to event */ - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { try { expect(!err, err && helper.displayError(err)).to.be.ok; @@ -709,7 +710,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.publish({ name: 'event0', clientId: clientId }, function (err) { + whenPromiseSettles(channel.publish({ name: 'event0', clientId: clientId }), function (err) { cb(err); }); }, @@ -727,9 +728,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('explicit_client_id_1', function (done) { var clientId = 'explicit_client_id_1', invalidClientId = 'invalid', - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); - rest.auth.requestToken({ clientId: clientId }, function (err, token) { + whenPromiseSettles(rest.auth.requestToken({ clientId: clientId }), function (err, token) { if (err) { done(err); return; @@ -742,11 +743,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } /* Use a fixed transport as intercepting transport.send */ - var realtime = helper.AblyRealtime({ token: token.token, transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtimePromise({ token: token.token, transports: [helper.bestTransport] }), channel = realtime.channels.get('explicit_client_id_1'); // Publish before authentication to ensure the client library does not reject the message as the clientId is not known - channel.publish({ name: 'event0', clientId: invalidClientId }, function (err) { + whenPromiseSettles(channel.publish({ name: 'event0', clientId: invalidClientId }), function (err) { try { expect(err, 'Message was not published').to.be.ok; } catch (err) { @@ -782,7 +783,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('subscribe_with_event_array', function (done) { - var realtime = helper.AblyRealtime(), + var realtime = helper.AblyRealtimePromise(), channel = realtime.channels.get('subscribe_with_event_array'); async.series( @@ -793,7 +794,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { cb(err); }); }, @@ -819,9 +820,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (innercb) { - channel.publish([{ name: 'a' }, { name: 'b' }, { name: 'c' }, { name: 'd' }], function (err) { - innercb(err); - }); + whenPromiseSettles( + channel.publish([{ name: 'a' }, { name: 'b' }, { name: 'c' }, { name: 'd' }]), + function (err) { + innercb(err); + } + ); }, ], outercb @@ -835,12 +839,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('subscribe_with_filter_object', function (done) { - const realtime = helper.AblyRealtime(); + const realtime = helper.AblyRealtimePromise(); const channel = realtime.channels.get('subscribe_with_filter_object'); function send(cb) { - channel.publish( - [ + whenPromiseSettles( + channel.publish([ { name: 'correct', extras: { @@ -871,7 +875,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }, }, }, - ], + ]), cb ); } @@ -902,7 +906,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - return channel.attach(cb); + return whenPromiseSettles(channel.attach(), cb); }, function (cb) { return async.parallel([subscribe, send], cb); @@ -915,12 +919,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('unsubscribe_with_filter_object', function (done) { - const realtime = helper.AblyRealtime(); + const realtime = helper.AblyRealtimePromise(); const channel = realtime.channels.get('unsubscribe_with_filter_object'); function send(cb) { - channel.publish( - [ + whenPromiseSettles( + channel.publish([ { name: 'incorrect', extras: { @@ -930,7 +934,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }, }, }, - ], + ]), cb ); } @@ -961,7 +965,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - return channel.attach(cb); + return whenPromiseSettles(channel.attach(), cb); }, unsubscribe, send, @@ -973,7 +977,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('extras_field', function (done) { - var realtime = helper.AblyRealtime(), + var realtime = helper.AblyRealtimePromise(), channel = realtime.channels.get('extras_field'), extras = { headers: { some: 'metadata' } }; @@ -984,7 +988,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async cb(); }); }, - channel.attach.bind(channel), + function (cb) { + whenPromiseSettles(channel.attach(), cb); + }, function (outercb) { async.parallel( [ @@ -1001,7 +1007,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (innercb) { - channel.publish([{ name: 'a', extras: extras }], innercb); + whenPromiseSettles(channel.publish([{ name: 'a', extras: extras }]), innercb); }, ], outercb @@ -1016,22 +1022,25 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* TO3l8; CD2C; RSL1i */ it('maxMessageSize', function (done) { - var realtime = helper.AblyRealtime(), + var realtime = helper.AblyRealtimePromise(), connectionManager = realtime.connection.connectionManager, channel = realtime.channels.get('maxMessageSize'); realtime.connection.once('connected', function () { connectionManager.once('connectiondetails', function (details) { - channel.publish('foo', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', function (err) { - try { - expect(err, 'Check publish refused').to.be.ok; - expect(err.code).to.equal(40009); - } catch (err) { - closeAndFinish(done, realtime, err); - return; + whenPromiseSettles( + channel.publish('foo', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'), + function (err) { + try { + expect(err, 'Check publish refused').to.be.ok; + expect(err.code).to.equal(40009); + } catch (err) { + closeAndFinish(done, realtime, err); + return; + } + closeAndFinish(done, realtime); } - closeAndFinish(done, realtime); - }); + ); }); var connectionDetails = connectionManager.connectionDetails; connectionDetails.maxMessageSize = 64; @@ -1047,7 +1056,7 @@ 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 realtime = helper.AblyRealtimePromise({ maxMessageSize: 256, autoConnect: false }), channelOne = realtime.channels.get('bundlingOne'), channelTwo = realtime.channels.get('bundlingTwo'); @@ -1109,10 +1118,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('idempotentRealtimePublishing', function (done) { - var realtime = helper.AblyRealtime(), + var realtime = helper.AblyRealtimePromise(), channel = realtime.channels.get('idempotentRealtimePublishing'); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -1144,7 +1153,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async if (typeof Promise !== 'undefined') { it('publishpromise', function (done) { - var realtime = helper.AblyRealtime({ internal: { promises: true } }); + var realtime = helper.AblyRealtimePromise({ internal: { promises: true } }); var channel = realtime.channels.get('publishpromise'); var publishPromise = realtime.connection @@ -1242,8 +1251,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { /* set up realtime */ - var realtime = helper.AblyRealtime({ key: helper.getTestApp().keys[5].keyStr }); - var rest = helper.AblyRest(); + var realtime = helper.AblyRealtimePromise({ key: helper.getTestApp().keys[5].keyStr }); + var rest = helper.AblyRestPromise(); realtime.connection.on('connected', function () { var rtFilteredChannel = realtime.channels.getDerived('chan', filterOption); @@ -1252,7 +1261,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var filteredMessages = []; var unFilteredMessages = []; /* subscribe to event */ - rtFilteredChannel.attach(function (err) { + whenPromiseSettles(rtFilteredChannel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -1267,7 +1276,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } }); - rtUnfilteredChannel.attach(function (err) { + whenPromiseSettles(rtUnfilteredChannel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; diff --git a/test/realtime/presence.test.js b/test/realtime/presence.test.js index 1c90d988d9..0f5d08bbfb 100644 --- a/test/realtime/presence.test.js +++ b/test/realtime/presence.test.js @@ -6,6 +6,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var createPM = Ably.Realtime.ProtocolMessage.fromDeserialized; var closeAndFinish = helper.closeAndFinish; var monitorConnection = helper.monitorConnection; + var whenPromiseSettles = helper.whenPromiseSettles; function extractClientIds(presenceSet) { return utils @@ -28,10 +29,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var createListenerChannel = function (channelName, callback) { var channel, realtime; try { - realtime = helper.AblyRealtime(); + realtime = helper.AblyRealtimePromise(); realtime.connection.on('connected', function () { channel = realtime.channels.get(channelName); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { callback(err, realtime, channel); }); }); @@ -100,8 +101,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } // Create authTokens associated with specific clientIds try { - rest = helper.AblyRest(); - rest.auth.requestToken({ clientId: testClientId }, function (err, tokenDetails) { + rest = helper.AblyRestPromise(); + whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { if (err) { done(err); return; @@ -114,7 +115,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - rest.auth.requestToken({ clientId: testClientId2 }, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId2 }), function (err, tokenDetails) { if (err) { done(err); return; @@ -142,16 +143,16 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelName = 'attachAndEnter'; var attachAndEnter = function (cb) { /* set up authenticated connection */ - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.attach(function (err) { + whenPromiseSettles(clientChannel.attach(), function (err) { if (err) { cb(err, clientRealtime); return; } - clientChannel.presence.enter('Test client data (enter0)', function (err) { + whenPromiseSettles(clientChannel.presence.enter('Test client data (enter0)'), function (err) { cb(err, clientRealtime); }); }); @@ -168,11 +169,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterWithoutAttach', function (done) { var channelName = 'enterWithoutAttach'; var enterWithoutAttach = function (cb) { - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.presence.enter('Test client data (enterWithoutAttach)', function (err) { + whenPromiseSettles(clientChannel.presence.enter('Test client data (enterWithoutAttach)'), function (err) { cb(err, clientRealtime); }); }); @@ -188,9 +189,9 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterWithoutConnect', function (done) { var channelName = 'enterWithoutConnect'; var enterWithoutConnect = function (cb) { - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.presence.enter('Test client data (enterWithoutConnect)', function (err) { + whenPromiseSettles(clientChannel.presence.enter('Test client data (enterWithoutConnect)'), function (err) { cb(err, clientRealtime); }); monitorConnection(done, clientRealtime); @@ -218,7 +219,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); listenerFor('enter', testClientId)(presenceChannel, function () { if (!raceFinished) { @@ -230,19 +231,19 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.attach(function (err) { + whenPromiseSettles(clientChannel.attach(), function (err) { if (err) { closeAndFinish(done, [listenerRealtime, clientRealtime], err); return; } - clientChannel.detach(function (err) { + whenPromiseSettles(clientChannel.detach(), function (err) { if (err) { closeAndFinish(done, [listenerRealtime, clientRealtime], err); return; } }); }); - clientChannel.presence.enter('Test client data (enter3)', function (err) { + whenPromiseSettles(clientChannel.presence.enter('Test client data (enter3)'), function (err) { // Note: either an error (pending messages failed to send due to detach) // or a success (pending messages were pushed out before the detach) // is an acceptable result. Throwing an uncaught exception (the behaviour @@ -270,16 +271,16 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelName = 'enterWithCallback'; var enterWithCallback = function (cb) { /* set up authenticated connection */ - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.attach(function (err) { + whenPromiseSettles(clientChannel.attach(), function (err) { if (err) { cb(err, clientRealtime); return; } - clientChannel.presence.enter(function (err) { + whenPromiseSettles(clientChannel.presence.enter(), function (err) { cb(err, clientRealtime); }); }); @@ -296,11 +297,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterWithNothing', function (done) { var channelName = 'enterWithNothing'; var enterWithNothing = function (cb) { - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.attach(function (err) { + whenPromiseSettles(clientChannel.attach(), function (err) { if (err) { cb(err, clientRealtime); return; @@ -321,11 +322,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterWithData', function (done) { var channelName = 'enterWithData'; var enterWithData = function (cb) { - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.attach(function (err) { + whenPromiseSettles(clientChannel.attach(), function (err) { if (err) { cb(err, clientRealtime); return; @@ -345,7 +346,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async * has valid action string */ it('presenceMessageAction', function (done) { - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); var channelName = 'presenceMessageAction'; var clientChannel = clientRealtime.channels.get(channelName); var presence = clientChannel.presence; @@ -385,24 +386,24 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channel.presence.subscribe(presenceHandler); }; var enterDetachEnter = function (cb) { - var clientRealtime = helper.AblyRealtime({ + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken, transports: [helper.bestTransport], }); // NB remove besttransport in 1.1 spec, see attachdetach0 var clientChannel = clientRealtime.channels.get(channelName); clientRealtime.connection.once('connected', function () { - clientChannel.presence.enter('first', function (err) { + whenPromiseSettles(clientChannel.presence.enter('first'), function (err) { if (err) { cb(err, clientRealtime); return; } - clientChannel.detach(function (err) { + whenPromiseSettles(clientChannel.detach(), function (err) { if (err) { cb(err, clientRealtime); return; } - clientChannel.presence.enter('second', function (err) { + whenPromiseSettles(clientChannel.presence.enter('second'), function (err) { cb(err, clientRealtime); }); }); @@ -420,10 +421,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterInvalid', function (done) { var clientRealtime; try { - clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); var clientChannel = clientRealtime.channels.get(''); clientRealtime.connection.once('connected', function () { - clientChannel.presence.enter('clientId', function (err) { + whenPromiseSettles(clientChannel.presence.enter('clientId'), function (err) { if (err) { try { expect(err.code).to.equal(40010, 'Correct error code'); @@ -449,22 +450,22 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterAndLeave', function (done) { var channelName = 'enterAndLeave'; var enterAndLeave = function (cb) { - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.attach(function (err) { + whenPromiseSettles(clientChannel.attach(), function (err) { if (err) { cb(err, clientRealtime); return; } - clientChannel.presence.enter('Test client data (leave0)', function (err) { + whenPromiseSettles(clientChannel.presence.enter('Test client data (leave0)'), function (err) { if (err) { cb(err, clientRealtime); return; } }); - clientChannel.presence.leave(function (err) { + whenPromiseSettles(clientChannel.presence.leave(), function (err) { cb(err, clientRealtime); }); }); @@ -498,20 +499,20 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channel.presence.subscribe(presenceHandler); }; var enterUpdate = function (cb) { - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.attach(function (err) { + whenPromiseSettles(clientChannel.attach(), function (err) { if (err) { cb(err, clientRealtime); return; } - clientChannel.presence.enter('Original data', function (err) { + whenPromiseSettles(clientChannel.presence.enter('Original data'), function (err) { if (err) { cb(err, clientRealtime); return; } - clientChannel.presence.update(newData, function (err) { + whenPromiseSettles(clientChannel.presence.update(newData), function (err) { cb(err, clientRealtime); }); }); @@ -532,7 +533,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var eventListener = function (channel, callback) { var presenceHandler = function () { /* Should be ENTER, but may be PRESENT in a race */ - channel.presence.get(function (err, presenceMembers) { + whenPromiseSettles(channel.presence.get(), function (err, presenceMembers) { if (err) { callback(err); return; @@ -551,16 +552,16 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channel.presence.subscribe(presenceHandler); }; var enterGet = function (cb) { - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.attach(function (err) { + whenPromiseSettles(clientChannel.attach(), function (err) { if (err) { cb(err, clientRealtime); return; } - clientChannel.presence.enter(testData, function (err) { + whenPromiseSettles(clientChannel.presence.enter(testData), function (err) { cb(err, clientRealtime); }); }); @@ -576,7 +577,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('presenceSubscribeUnattached', function (done) { var channelName = 'subscribeUnattached'; - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); var clientRealtime2; clientRealtime.connection.on('connected', function () { var clientChannel = clientRealtime.channels.get(channelName); @@ -590,7 +591,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async closeAndFinish(done, [clientRealtime, clientRealtime2]); }); /* Technically a race, but c2 connecting and attaching should take longer than c1 attaching */ - clientRealtime2 = helper.AblyRealtime({ clientId: testClientId2, tokenDetails: authToken2 }); + clientRealtime2 = helper.AblyRealtimePromise({ clientId: testClientId2, tokenDetails: authToken2 }); clientRealtime2.connection.on('connected', function () { var clientChannel2 = clientRealtime2.channels.get(channelName); clientChannel2.presence.enter('data'); @@ -605,20 +606,20 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceGetUnattached', function (done) { var channelName = 'getUnattached'; var testData = 'some data'; - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.presence.enter(testData, function (err) { + whenPromiseSettles(clientChannel.presence.enter(testData), function (err) { if (err) { closeAndFinish(done, clientRealtime, err); return; } - var clientRealtime2 = helper.AblyRealtime({ clientId: testClientId2, tokenDetails: authToken2 }); + var clientRealtime2 = helper.AblyRealtimePromise({ clientId: testClientId2, tokenDetails: authToken2 }); clientRealtime2.connection.on('connected', function () { var clientChannel2 = clientRealtime2.channels.get(channelName); /* GET without attaching */ - clientChannel2.presence.get(function (err, presenceMembers) { + whenPromiseSettles(clientChannel2.presence.get(), function (err, presenceMembers) { if (err) { closeAndFinish(done, [clientRealtime, clientRealtime2], err); return; @@ -649,7 +650,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var presenceHandler = function () { // Ignore the first (enter) event if (this.event == 'leave') { - channel.presence.get(function (err, presenceMembers) { + whenPromiseSettles(channel.presence.get(), function (err, presenceMembers) { if (err) { callback(err); return; @@ -668,21 +669,21 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channel.presence.subscribe(presenceHandler); }; var enterLeaveGet = function (cb) { - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.attach(function (err) { + whenPromiseSettles(clientChannel.attach(), function (err) { if (err) { cb(err, clientRealtime); return; } - clientChannel.presence.enter('testClientData', function (err) { + whenPromiseSettles(clientChannel.presence.enter('testClientData'), function (err) { if (err) { cb(err, clientRealtime); return; } - clientChannel.presence.leave(function (err) { + whenPromiseSettles(clientChannel.presence.leave(), function (err) { cb(err, clientRealtime); }); }); @@ -702,7 +703,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelName = 'history'; var testClientData = 'Test client data (history0)'; var queryPresenceHistory = function (channel) { - channel.presence.history(function (err, resultPage) { + whenPromiseSettles(channel.presence.history(), function (err, resultPage) { if (err) { closeAndFinish(done, clientRealtime, err); return; @@ -725,26 +726,26 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }; try { /* set up authenticated connection */ - clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); - clientChannel.attach(function (err) { + whenPromiseSettles(clientChannel.attach(), function (err) { if (err) { closeAndFinish(done, clientRealtime, err); return; } - clientChannel.presence.enter(testClientData, function (err) { + whenPromiseSettles(clientChannel.presence.enter(testClientData), function (err) { if (err) { closeAndFinish(done, clientRealtime, err); return; } - clientChannel.presence.leave(function (err) { + whenPromiseSettles(clientChannel.presence.leave(), function (err) { if (err) { closeAndFinish(done, clientRealtime, err); return; } - clientChannel.detach(function (err) { + whenPromiseSettles(clientChannel.detach(), function (err) { if (err) { closeAndFinish(done, clientRealtime, err); return; @@ -774,23 +775,23 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelName = 'secondConnection'; try { /* set up authenticated connection */ - clientRealtime1 = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + clientRealtime1 = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime1.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel1 = clientRealtime1.channels.get(channelName); - clientChannel1.attach(function (err) { + whenPromiseSettles(clientChannel1.attach(), function (err) { if (err) { closeAndFinish(done, clientRealtime1, err); return; } - clientChannel1.presence.enter('Test client data (attach0)', function (err) { + whenPromiseSettles(clientChannel1.presence.enter('Test client data (attach0)'), function (err) { if (err) { closeAndFinish(done, clientRealtime1, err); return; } }); clientChannel1.presence.subscribe('enter', function () { - clientChannel1.presence.get(function (err, presenceMembers1) { + whenPromiseSettles(clientChannel1.presence.get(), function (err, presenceMembers1) { if (err) { closeAndFinish(done, clientRealtime1, err); return; @@ -803,18 +804,18 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } /* now set up second connection and attach */ /* set up authenticated connection */ - clientRealtime2 = helper.AblyRealtime({ clientId: testClientId2, tokenDetails: authToken2 }); + clientRealtime2 = helper.AblyRealtimePromise({ clientId: testClientId2, tokenDetails: authToken2 }); clientRealtime2.connection.on('connected', function () { /* get channel, attach */ var clientChannel2 = clientRealtime2.channels.get(channelName); - clientChannel2.attach(function (err) { + whenPromiseSettles(clientChannel2.attach(), function (err) { if (err) { closeAndFinish(done, [clientRealtime1, clientRealtime2], err); return; } clientChannel2.presence.subscribe('present', function () { /* get the channel members and verify testclient is there */ - clientChannel2.presence.get(function (err, presenceMembers2) { + whenPromiseSettles(clientChannel2.presence.get(), function (err, presenceMembers2) { if (err) { closeAndFinish(done, [clientRealtime1, clientRealtime2], err); return; @@ -858,16 +859,16 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async [ function (cb1) { var data = 'Test client data (member0-1)'; - clientRealtime1 = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + clientRealtime1 = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); clientRealtime1.connection.on('connected', function () { /* get channel, attach, and enter */ clientChannel1 = clientRealtime1.channels.get(channelName); - clientChannel1.attach(function (err) { + whenPromiseSettles(clientChannel1.attach(), function (err) { if (err) { cb1(err); return; } - clientChannel1.presence.enter(data, function (err) { + whenPromiseSettles(clientChannel1.presence.enter(data), function (err) { if (err) { cb1(err); return; @@ -880,17 +881,17 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }, function (cb2) { var data = 'Test client data (member0-2)'; - clientRealtime2 = helper.AblyRealtime({ clientId: testClientId2, tokenDetails: authToken2 }); + clientRealtime2 = helper.AblyRealtimePromise({ clientId: testClientId2, tokenDetails: authToken2 }); clientRealtime2.connection.on('connected', function () { /* get channel, attach */ clientChannel2 = clientRealtime2.channels.get(channelName); - clientChannel2.attach(function (err) { + whenPromiseSettles(clientChannel2.attach(), function (err) { if (err) { cb2(err); return; } var enterPresence = function (onEnterCB) { - clientChannel2.presence.enter(data, function (err) { + whenPromiseSettles(clientChannel2.presence.enter(data), function (err) { if (err) { cb2(err); return; @@ -934,7 +935,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async [ /* First test: no filters */ function (cb) { - clientChannel2.presence.get(function (err, members) { + whenPromiseSettles(clientChannel2.presence.get(), function (err, members) { if (err) { return cb(err); } @@ -953,7 +954,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }, /* Second test: filter by clientId */ function (cb) { - clientChannel2.presence.get({ clientId: testClientId }, function (err, members) { + whenPromiseSettles(clientChannel2.presence.get({ clientId: testClientId }), function (err, members) { if (err) { return cb(err); } @@ -969,25 +970,28 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }, /* Third test: filter by connectionId */ function (cb) { - clientChannel2.presence.get({ connectionId: clientRealtime1.connection.id }, function (err, members) { - if (err) { - return cb(err); - } - try { - expect(members.length).to.equal( - 1, - 'Verify only one member present when filtered by connectionId' - ); - expect(members[0].connectionId).to.equal( - clientRealtime1.connection.id, - 'Verify connectionId filter works' - ); - } catch (err) { - cb(err); - return; + whenPromiseSettles( + clientChannel2.presence.get({ connectionId: clientRealtime1.connection.id }), + function (err, members) { + if (err) { + return cb(err); + } + try { + expect(members.length).to.equal( + 1, + 'Verify only one member present when filtered by connectionId' + ); + expect(members[0].connectionId).to.equal( + clientRealtime1.connection.id, + 'Verify connectionId filter works' + ); + } catch (err) { + cb(err); + return; + } + cb(); } - cb(); - }); + ); }, ], function (err) { @@ -1021,11 +1025,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channel.presence.subscribe(presenceHandler); }; var enterAfterClose = function (cb) { - var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); var clientChannel = clientRealtime.channels.get(channelName); clientRealtime.connection.once('connected', function () { /* get channel and enter (should automatically attach) */ - clientChannel.presence.enter('first', function (err) { + whenPromiseSettles(clientChannel.presence.enter('first'), function (err) { if (err) { cb(err, clientRealtime); return; @@ -1034,7 +1038,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async clientRealtime.connection.whenState('closed', function () { clientRealtime.connection.once('connected', function () { //Should automatically reattach - clientChannel.presence.enter('second', function (err) { + whenPromiseSettles(clientChannel.presence.enter('second'), function (err) { cb(err, clientRealtime); }); }); @@ -1055,11 +1059,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var clientRealtime; var channelName = 'enterClosed'; try { - clientRealtime = helper.AblyRealtime(); + clientRealtime = helper.AblyRealtimePromise(); var clientChannel = clientRealtime.channels.get(channelName); clientRealtime.connection.on('connected', function () { clientRealtime.close(); - clientChannel.presence.enterClient('clientId', function (err) { + whenPromiseSettles(clientChannel.presence.enterClient('clientId'), function (err) { try { expect(err.code).to.equal(80017, 'presence enter failed with correct code'); expect(err.statusCode).to.equal(400, 'presence enter failed with correct statusCode'); @@ -1081,7 +1085,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('presenceClientIdIsImplicit', function (done) { var clientId = 'implicitClient', - client = helper.AblyRealtime({ clientId: clientId }); + client = helper.AblyRealtimePromise({ clientId: clientId }); var channel = client.channels.get('presenceClientIdIsImplicit'), presence = channel.presence; @@ -1097,17 +1101,17 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async originalSendPresence.apply(channel, arguments); }; - presence.enter(null, function (err) { + whenPromiseSettles(presence.enter(null), function (err) { if (err) { closeAndFinish(done, client, err); return; } - presence.update(null, function (err) { + whenPromiseSettles(presence.update(null), function (err) { if (err) { closeAndFinish(done, client, err); return; } - presence.leave(null, function (err) { + whenPromiseSettles(presence.leave(null), function (err) { if (err) { closeAndFinish(done, client, err); return; @@ -1131,8 +1135,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async transports: [helper.bestTransport], }; - var realtimeBin = helper.AblyRealtime(utils.mixin(options, { useBinaryProtocol: true })); - var realtimeJson = helper.AblyRealtime(utils.mixin(options, { useBinaryProtocol: false })); + var realtimeBin = helper.AblyRealtimePromise(utils.mixin(options, { useBinaryProtocol: true })); + var realtimeJson = helper.AblyRealtimePromise(utils.mixin(options, { useBinaryProtocol: false })); var runTest = function (realtime, callback) { realtime.connection.connectionManager.once('transport.active', function (transport) { @@ -1188,7 +1192,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelName = 'enter_inherited_clientid'; var authCallback = function (tokenParams, callback) { - rest.auth.requestToken({ clientId: testClientId }, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { if (err) { done(err); return; @@ -1198,7 +1202,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }; var enterInheritedClientId = function (cb) { - var realtime = helper.AblyRealtime({ authCallback: authCallback }); + var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); var channel = realtime.channels.get(channelName); realtime.connection.on('connected', function () { try { @@ -1207,7 +1211,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async cb(err); return; } - channel.presence.enter('test data', function (err) { + whenPromiseSettles(channel.presence.enter('test data'), function (err) { cb(err, realtime); }); }); @@ -1226,12 +1230,12 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelName = 'enter_before_know_clientid'; var enterInheritedClientId = function (cb) { - rest.auth.requestToken({ clientId: testClientId }, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { if (err) { done(err); return; } - var realtime = helper.AblyRealtime({ token: tokenDetails.token, autoConnect: false }); + var realtime = helper.AblyRealtimePromise({ token: tokenDetails.token, autoConnect: false }); var channel = realtime.channels.get(channelName); try { expect(realtime.auth.clientId).to.equal(undefined, 'no clientId when entering'); @@ -1239,7 +1243,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async closeAndFinish(done, realtime, err); return; } - channel.presence.enter('test data', function (err) { + whenPromiseSettles(channel.presence.enter('test data'), function (err) { try { expect(realtime.auth.clientId).to.equal(testClientId, 'clientId has been set by the time we entered'); } catch (err) { @@ -1262,8 +1266,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('presence_refresh_on_detach', function (done) { var channelName = 'presence_refresh_on_detach'; - var realtime = helper.AblyRealtime(); - var observer = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); + var observer = helper.AblyRealtimePromise(); var realtimeChannel = realtime.channels.get(channelName); var observerChannel = observer.channels.get(channelName); @@ -1287,10 +1291,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async async.parallel( [ function (enterCb) { - realtimeChannel.presence.enterClient('one', enterCb); + whenPromiseSettles(realtimeChannel.presence.enterClient('one'), enterCb); }, function (enterCb) { - realtimeChannel.presence.enterClient('two', enterCb); + whenPromiseSettles(realtimeChannel.presence.enterClient('two'), enterCb); }, ], cb @@ -1298,7 +1302,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } function checkPresence(first, second, cb) { - observerChannel.presence.get(function (err, presenceMembers) { + whenPromiseSettles(observerChannel.presence.get(), function (err, presenceMembers) { var clientIds = utils .arrMap(presenceMembers, function (msg) { return msg.clientId; @@ -1320,10 +1324,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async async.parallel( [ function (innerCb) { - realtimeChannel.presence.leaveClient('two', innerCb); + whenPromiseSettles(realtimeChannel.presence.leaveClient('two'), innerCb); }, function (innerCb) { - realtimeChannel.presence.enterClient('three', innerCb); + whenPromiseSettles(realtimeChannel.presence.enterClient('three'), innerCb); }, ], cb @@ -1350,17 +1354,17 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async [ waitForBothConnect, function (cb) { - realtimeChannel.attach(cb); + whenPromiseSettles(realtimeChannel.attach(), cb); }, enterOneAndTwo, function (cb) { - observerChannel.attach(cb); + whenPromiseSettles(observerChannel.attach(), cb); }, function (cb) { checkPresence('one', 'two', cb); }, function (cb) { - observerChannel.detach(cb); + whenPromiseSettles(observerChannel.detach(), cb); }, swapTwoForThree, attachAndListen, @@ -1376,8 +1380,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presence_detach_during_sync', function (done) { var channelName = 'presence_detach_during_sync'; - var enterer = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); - var detacher = helper.AblyRealtime(); + var enterer = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var detacher = helper.AblyRealtimePromise(); var entererChannel = enterer.channels.get(channelName); var detacherChannel = detacher.channels.get(channelName); @@ -1401,13 +1405,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async [ waitForBothConnect, function (cb) { - entererChannel.presence.enter(cb); + whenPromiseSettles(entererChannel.presence.enter(), cb); }, function (cb) { - detacherChannel.attach(cb); + whenPromiseSettles(detacherChannel.attach(), cb); }, function (cb) { - detacherChannel.detach(cb); + whenPromiseSettles(detacherChannel.detach(), cb); }, function (cb) { try { @@ -1432,7 +1436,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async * presence set */ it('presence_auto_reenter', function (done) { var channelName = 'presence_auto_reenter'; - var realtime = helper.AblyRealtime(); + var realtime = helper.AblyRealtimePromise(); var channel = realtime.channels.get(channelName); async.series( @@ -1443,7 +1447,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.attach(cb); + whenPromiseSettles(channel.attach(), cb); }, function (cb) { if (!channel.presence.syncComplete) { @@ -1512,7 +1516,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.presence.get(function (err, results) { + whenPromiseSettles(channel.presence.get(), function (err, results) { if (err) { cb(err); return; @@ -1551,20 +1555,20 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* Request a token without the capabilities to be in the presence set */ var tokenParams = { clientId: 'me', capability: {} }; tokenParams.capability[channelName] = ['publish', 'subscribe']; - rest.auth.requestToken(tokenParams, function (err, tokenDetails) { + whenPromiseSettles(rest.auth.requestToken(tokenParams), function (err, tokenDetails) { token = tokenDetails; cb(err); }); }, function (cb) { - realtime = helper.AblyRealtime({ tokenDetails: token }); + realtime = helper.AblyRealtimePromise({ tokenDetails: token }); channel = realtime.channels.get(channelName); realtime.connection.once('connected', function () { cb(); }); }, function (cb) { - channel.attach(cb); + whenPromiseSettles(channel.attach(), cb); }, function (cb) { if (!channel.presence.syncComplete) { @@ -1574,7 +1578,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } }, function (cb) { - channel.presence.get(function (err, members) { + whenPromiseSettles(channel.presence.get(), function (err, members) { try { expect(members.length).to.equal(0, 'Check no-one in presence set'); } catch (err) { @@ -1616,7 +1620,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.presence.get(function (err, members) { + whenPromiseSettles(channel.presence.get(), function (err, members) { try { expect(members.length).to.equal(0, 'Check no-one in presence set'); } catch (err) { @@ -1636,7 +1640,7 @@ 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) { /* single transport to avoid upgrade stalling due to the stubbed attachImpl */ - var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), channel = realtime.channels.get('multiple_pending'), originalAttachImpl = channel.attachImpl; @@ -1667,7 +1671,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.presence.get(function (err, results) { + whenPromiseSettles(channel.presence.get(), function (err, results) { try { expect(results.length).to.equal(10, 'Check all ten clients are there'); } catch (err) { @@ -1688,10 +1692,10 @@ 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 realtime = helper.AblyRealtimePromise({ transports: helper.availableTransports }), continuousClientId = 'continuous', goneClientId = 'gone', - continuousRealtime = helper.AblyRealtime({ clientId: continuousClientId }), + continuousRealtime = helper.AblyRealtimePromise({ clientId: continuousClientId }), channelName = 'leave_published_for_member_missing_from_sync', channel = realtime.channels.get(channelName), continuousChannel = continuousRealtime.channels.get(channelName); @@ -1706,10 +1710,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - continuousChannel.attach(cb); + whenPromiseSettles(continuousChannel.attach(), cb); }, function (cb) { - continuousChannel.presence.enter(cb); + whenPromiseSettles(continuousChannel.presence.enter(), cb); }, function (cb) { realtime.connection.whenState('connected', function () { @@ -1717,10 +1721,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.attach(cb); + whenPromiseSettles(channel.attach(), cb); }, function (cb) { - channel.presence.get({ waitForSync: true }, function (err, members) { + whenPromiseSettles(channel.presence.get({ waitForSync: true }), function (err, members) { try { expect(members && members.length).to.equal(1, 'Check one member present'); } catch (err) { @@ -1753,7 +1757,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.presence.get(function (err, members) { + whenPromiseSettles(channel.presence.get(), function (err, members) { try { expect(members && members.length).to.equal(2, 'Check two members present'); } catch (err) { @@ -1778,7 +1782,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channel.sync(); }, function (cb) { - channel.presence.get({ waitForSync: true }, function (err, members) { + whenPromiseSettles(channel.presence.get({ waitForSync: true }), function (err, members) { try { expect(members && members.length).to.equal(1, 'Check back to one member present'); expect(members && members[0] && members[0].clientId).to.equal( @@ -1803,7 +1807,7 @@ 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 realtime = helper.AblyRealtimePromise(), channelName = 'leave_published_for_members_on_presenceless_attached', channel = realtime.channels.get(channelName), fakeClientId = 'faker'; @@ -1817,7 +1821,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.attach(cb); + whenPromiseSettles(channel.attach(), cb); }, function (cb) { /* Inject a member locally */ @@ -1842,7 +1846,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.presence.get(function (err, members) { + whenPromiseSettles(channel.presence.get(), function (err, members) { try { expect(members && members.length).to.equal(1, 'Check one member present'); } catch (err) { @@ -1873,7 +1877,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async ); }, function (cb) { - channel.presence.get(function (err, members) { + whenPromiseSettles(channel.presence.get(), function (err, members) { try { expect(members && members.length).to.equal(0, 'Check no members present'); } catch (err) { @@ -1895,9 +1899,9 @@ 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', logLevel: 4 }), - continuousRealtime = helper.AblyRealtime({ clientId: 'continuous', logLevel: 4 }), - leavesRealtime = helper.AblyRealtime({ clientId: 'leaves', logLevel: 4 }), + var mainRealtime = helper.AblyRealtimePromise({ clientId: 'main', logLevel: 4 }), + continuousRealtime = helper.AblyRealtimePromise({ clientId: 'continuous', logLevel: 4 }), + leavesRealtime = helper.AblyRealtimePromise({ clientId: 'leaves', logLevel: 4 }), channelName = 'suspended_preserves_presence', mainChannel = mainRealtime.channels.get(channelName); @@ -1914,10 +1918,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.attach(cb); + whenPromiseSettles(channel.attach(), cb); }, function (cb) { - channel.presence.enter(cb); + whenPromiseSettles(channel.presence.enter(), cb); }, ], outerCb @@ -1946,7 +1950,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async async.parallel([waitFor('leaves'), enter(leavesRealtime)], cb); }, function (cb) { - mainChannel.presence.get(function (err, members) { + whenPromiseSettles(mainChannel.presence.get(), function (err, members) { try { expect(members.length).to.equal(3, 'Check all three expected members here'); } catch (err) { @@ -1960,7 +1964,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async helper.becomeSuspended(mainRealtime, cb); }, function (cb) { - mainChannel.presence.get(function (err) { + whenPromiseSettles(mainChannel.presence.get(), function (err) { /* Check RTP11d: get() returns an error by default */ try { expect(err, 'Check error returned by get() while suspended').to.be.ok; @@ -1973,7 +1977,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - mainChannel.presence.get({ waitForSync: false }, function (err, members) { + whenPromiseSettles(mainChannel.presence.get({ waitForSync: false }), function (err, members) { /* Check RTP11d: get() works while suspended if waitForSync: false */ try { expect(!err, 'Check no error returned by get() while suspended if waitForSync: false').to.be.ok; @@ -2010,7 +2014,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async setTimeout(cb, 1000); }, function (cb) { - mainChannel.presence.get(function (err, members) { + whenPromiseSettles(mainChannel.presence.get(), function (err, members) { try { expect(members && members.length).to.equal(3, 'Check three expected members here'); } catch (err) { @@ -2033,13 +2037,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async * comparisons. */ it('presence_many_updates', function (done) { - var client = helper.AblyRealtime({ clientId: testClientId }); + var client = helper.AblyRealtimePromise({ clientId: testClientId }); var channel = client.channels.get('presence_many_updates'), presence = channel.presence, numUpdates = 0; - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, client, err); } @@ -2050,7 +2054,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async async.timesSeries( 15, function (i, cb) { - presence.update(i.toString(), cb); + whenPromiseSettles(presence.update(i.toString()), cb); }, function (err) { if (err) { @@ -2077,7 +2081,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var options = { clientId: testClientId, internal: { promises: true } }; it('enter_get', function (done) { - var client = helper.AblyRealtime(options); + var client = helper.AblyRealtimePromise(options); var channel = client.channels.get('presence_promise_get'); var testData = 'test_presence_data'; @@ -2106,7 +2110,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('update', function (done) { - var client = helper.AblyRealtime(options); + var client = helper.AblyRealtimePromise(options); var channel = client.channels.get('presence_promise_update'); var testData1 = 'test_presence_data1'; var testData2 = 'test_presence_data2'; @@ -2158,7 +2162,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('enterClient_leaveClient', function (done) { - var client = helper.AblyRealtime(options); + var client = helper.AblyRealtimePromise(options); var channel = client.channels.get('presence_promise_leaveClient'); var idx = 0; @@ -2208,7 +2212,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('history', function (done) { - var client = helper.AblyRealtime(options); + var client = helper.AblyRealtimePromise(options); var channel = client.channels.get('presence_promise_history'); channel.presence .history() @@ -2222,7 +2226,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('subscribe', function (done) { - var client = helper.AblyRealtime(options); + var client = helper.AblyRealtimePromise(options); var channel = client.channels.get('presence_promise_subscribe'); channel.presence .subscribe(function () {}) diff --git a/test/realtime/reauth.test.js b/test/realtime/reauth.test.js index de5f1ab36d..87b44ab77d 100644 --- a/test/realtime/reauth.test.js +++ b/test/realtime/reauth.test.js @@ -6,6 +6,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { var rest; var mixin = helper.Utils.mixin; var displayError = helper.displayError; + var whenPromiseSettles = helper.whenPromiseSettles; describe('realtime/reauth', function () { this.timeout(60 * 1000); @@ -16,7 +17,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { done(err); return; } - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); done(); }); }); @@ -25,7 +26,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { function getToken(tokenParams) { return function (state, callback) { - rest.auth.requestToken(tokenParams, null, function (err, token) { + whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, token) { callback(err, mixin(state, { token: token })); }); }; @@ -43,7 +44,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { function connectWithToken() { return function (state, callback) { - var realtime = helper.AblyRealtime(mixin({ token: state.token }, state.realtimeOpts)); + var realtime = helper.AblyRealtimePromise(mixin({ token: state.token }, state.realtimeOpts)); realtime.connection.once('connected', function () { callback(null, mixin(state, { realtime: realtime })); }); @@ -72,7 +73,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { async.parallel( [ function (cb) { - state.realtime.auth.authorize(null, { token: state.token }, cb); + whenPromiseSettles(state.realtime.auth.authorize(null, { token: state.token }), cb); }, function (cb) { state.realtime.connection.on('update', function (stateChange) { @@ -90,7 +91,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { function attach(channelName) { return function (state, callback) { var channel = state.realtime.channels.get(channelName); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { callback(err, state); }); }; @@ -146,7 +147,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { function checkCantAttach(channelName) { return function (state, callback) { var channel = state.realtime.channels.get(channelName); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err && err.code === 40160) { callback(null, state); } else { @@ -159,7 +160,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { function checkCanPublish(channelName) { return function (state, callback) { var channel = state.realtime.channels.get(channelName); - channel.publish(null, null, function (err) { + whenPromiseSettles(channel.publish(null, null), function (err) { callback(err, state); }); }; @@ -168,7 +169,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { function checkCantPublish(channelName) { return function (state, callback) { var channel = state.realtime.channels.get(channelName); - channel.publish(null, null, function (err) { + whenPromiseSettles(channel.publish(null, null), function (err) { if (err && err.code === 40160) { callback(null, state); } else { diff --git a/test/realtime/resume.test.js b/test/realtime/resume.test.js index 31b1dab3c6..1c0e96ce32 100644 --- a/test/realtime/resume.test.js +++ b/test/realtime/resume.test.js @@ -6,6 +6,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { var simulateDroppedConnection = helper.simulateDroppedConnection; var testOnAllTransports = helper.testOnAllTransports; var bestTransport = helper.bestTransport; + var whenPromiseSettles = helper.whenPromiseSettles; describe('realtime/resume', function () { this.timeout(120 * 1000); @@ -31,7 +32,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { receivingChannel.unsubscribe(event); callback(); }); - sendingChannel.publish(event, message, function (err) { + whenPromiseSettles(sendingChannel.publish(event, message), function (err) { if (err) callback(err); }); } @@ -43,15 +44,15 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { function resume_inactive(done, channelName, txOpts, rxOpts) { var count = 5; - var txRest = helper.AblyRest(mixin(txOpts)); - var rxRealtime = helper.AblyRealtime(mixin(rxOpts)); + var txRest = helper.AblyRestPromise(mixin(txOpts)); + var rxRealtime = helper.AblyRealtimePromise(mixin(rxOpts)); var rxChannel = rxRealtime.channels.get(channelName); var txChannel = txRest.channels.get(channelName); var rxCount = 0; function phase0(callback) { - rxChannel.attach(callback); + whenPromiseSettles(rxChannel.attach(), callback); } function phase1(callback) { @@ -154,15 +155,15 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { function resume_active(done, channelName, txOpts, rxOpts) { var count = 5; - var txRest = helper.AblyRest(mixin(txOpts)); - var rxRealtime = helper.AblyRealtime(mixin(rxOpts)); + var txRest = helper.AblyRestPromise(mixin(txOpts)); + var rxRealtime = helper.AblyRealtimePromise(mixin(rxOpts)); var rxChannel = rxRealtime.channels.get(channelName); var txChannel = txRest.channels.get(channelName); var rxCount = 0; function phase0(callback) { - rxChannel.attach(callback); + whenPromiseSettles(rxChannel.attach(), callback); } function phase1(callback) { @@ -188,7 +189,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { var txCount = 0; function ph2TxOnce() { - txChannel.publish('sentWhileDisconnected', 'phase 2, message ' + txCount, function (err) { + whenPromiseSettles(txChannel.publish('sentWhileDisconnected', 'phase 2, message ' + txCount), function (err) { if (err) callback(err); }); if (++txCount == count) { @@ -275,7 +276,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { 'resume_lost_continuity', function (realtimeOpts) { return function (done) { - var realtime = helper.AblyRealtime(realtimeOpts), + var realtime = helper.AblyRealtimePromise(realtimeOpts), connection = realtime.connection, attachedChannelName = 'resume_lost_continuity_attached', suspendedChannelName = 'resume_lost_continuity_suspended', @@ -291,7 +292,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { }, function (cb) { suspendedChannel.state = 'suspended'; - attachedChannel.attach(cb); + whenPromiseSettles(attachedChannel.attach(), cb); }, function (cb) { /* Sabotage the resume */ @@ -341,7 +342,7 @@ 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 realtime = helper.AblyRealtimePromise(mixin(realtimeOpts, { useTokenAuth: true })), badtoken, connection = realtime.connection; @@ -353,7 +354,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { }); }, function (cb) { - realtime.auth.requestToken({ ttl: 1 }, null, function (err, token) { + whenPromiseSettles(realtime.auth.requestToken({ ttl: 1 }, null), function (err, token) { badtoken = token; cb(err); }); @@ -394,7 +395,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { 'resume_fatal_error', function (realtimeOpts) { return function (done) { - var realtime = helper.AblyRealtime(realtimeOpts), + var realtime = helper.AblyRealtimePromise(realtimeOpts), connection = realtime.connection; async.series( @@ -444,7 +445,7 @@ 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 realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), realtimeTwo, recoveryKey, connection = realtime.connection, @@ -475,7 +476,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { helper.becomeSuspended(realtime, cb); }, function (cb) { - realtimeTwo = helper.AblyRealtime({ recover: recoveryKey }); + realtimeTwo = helper.AblyRealtimePromise({ recover: recoveryKey }); realtimeTwo.connection.once('connected', function (stateChange) { if (stateChange.reason) { cb(stateChange.reason); @@ -508,7 +509,7 @@ 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 realtime = helper.AblyRealtimePromise(), connection = realtime.connection, channelName = 'no_resume_once_suspended'; @@ -547,7 +548,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { */ it('no_resume_last_activity', function (done) { /* Specify a best transport so that upgrade activity doesn't reset the last activity timer */ - var realtime = helper.AblyRealtime({ transports: [bestTransport] }), + var realtime = helper.AblyRealtimePromise({ transports: [bestTransport] }), connection = realtime.connection, connectionManager = connection.connectionManager; @@ -573,11 +574,11 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { var testName = 'resume_rewind_1'; var testMessage = { foo: 'bar', count: 1, status: 'active' }; try { - var sender_realtime = helper.AblyRealtime(); + var sender_realtime = helper.AblyRealtimePromise(); var sender_channel = sender_realtime.channels.get(testName); sender_channel.subscribe(function (message) { - var receiver_realtime = helper.AblyRealtime(); + var receiver_realtime = helper.AblyRealtimePromise(); var receiver_channel = receiver_realtime.channels.get(testName, { params: { rewind: 1 } }); receiver_channel.subscribe(function (message) { @@ -591,7 +592,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { return; } - var resumed_receiver_realtime = helper.AblyRealtime(); + var resumed_receiver_realtime = helper.AblyRealtimePromise(); var connectionManager = resumed_receiver_realtime.connection.connectionManager; var sendOrig = connectionManager.send; @@ -629,8 +630,8 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { it('recover multiple channels', function (done) { const NUM_MSGS = 5; - const txRest = helper.AblyRest(); - const rxRealtime = helper.AblyRealtime( + const txRest = helper.AblyRestPromise(); + const rxRealtime = helper.AblyRealtimePromise( { transports: [helper.bestTransport], }, @@ -643,7 +644,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { const rxChannels = channelNames.map((name) => rxRealtime.channels.get(name)); function attachChannels(callback) { - async.each(rxChannels, (channel, cb) => channel.attach(cb), callback); + async.each(rxChannels, (channel, cb) => whenPromiseSettles(channel.attach(), cb), callback); } function publishSubscribeWhileConnectedOnce(callback) { @@ -673,7 +674,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { channelNames, (name, cb) => { const tx = txRest.channels.get(name); - tx.publish('sentWhileDisconnected', null, cb); + whenPromiseSettles(tx.publish('sentWhileDisconnected', null), cb); }, callback ); @@ -738,7 +739,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { return; } - rxRealtimeRecover = helper.AblyRealtime({ recover: recoveryKey }); + rxRealtimeRecover = helper.AblyRealtimePromise({ recover: recoveryKey }); rxRecoverChannels = channelNames.map((name) => rxRealtimeRecover.channels.get(name)); subscribeRecoveredMessages(function (err) { diff --git a/test/realtime/sync.test.js b/test/realtime/sync.test.js index 5f62dabe98..2359fd830e 100644 --- a/test/realtime/sync.test.js +++ b/test/realtime/sync.test.js @@ -7,6 +7,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var closeAndFinish = helper.closeAndFinish; var createPM = Ably.Realtime.ProtocolMessage.fromDeserialized; var monitorConnection = helper.monitorConnection; + var whenPromiseSettles = helper.whenPromiseSettles; describe('realtime/sync', function () { this.timeout(60 * 1000); @@ -43,7 +44,7 @@ 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 realtime = helper.AblyRealtimePromise({ autoConnect: false }), channelName = 'syncexistingset', channel = realtime.channels.get(channelName); @@ -92,7 +93,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.presence.get(function (err, results) { + whenPromiseSettles(channel.presence.get(), function (err, results) { try { expect(results.length).to.equal(2, 'Check correct number of results'); expect(channel.presence.syncComplete, 'Check in sync').to.be.ok; @@ -135,7 +136,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - channel.presence.get(function (err, results) { + whenPromiseSettles(channel.presence.get(), function (err, results) { try { expect(results.length).to.equal(2, 'Check correct number of results'); expect(channel.presence.syncComplete, 'Check in sync').to.be.ok; @@ -163,7 +164,7 @@ 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 realtime = helper.AblyRealtimePromise({ autoConnect: false }), channelName = 'sync_member_arrives_in_middle', channel = realtime.channels.get(channelName); @@ -240,7 +241,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async err ? reject(err) : resolve(); }; - channel.presence.get(function (err, results) { + whenPromiseSettles(channel.presence.get(), function (err, results) { if (err) { closeAndFinish(done, realtime, err); return; @@ -265,7 +266,7 @@ 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 realtime = helper.AblyRealtimePromise({ autoConnect: false }), channelName = 'sync_member_arrives_normally_after_came_in_sync', channel = realtime.channels.get(channelName); @@ -326,7 +327,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async err ? reject(err) : resolve(); }; - channel.presence.get(function (err, results) { + whenPromiseSettles(channel.presence.get(), function (err, results) { if (err) { closeAndFinish(done, realtime, err); return; @@ -348,7 +349,7 @@ 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 realtime = helper.AblyRealtimePromise({ autoConnect: false }), channelName = 'sync_member_arrives_normally_before_comes_in_sync', channel = realtime.channels.get(channelName); @@ -409,7 +410,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async err ? reject(err) : resolve(); }; - channel.presence.get(function (err, results) { + whenPromiseSettles(channel.presence.get(), function (err, results) { if (err) { closeAndFinish(done, realtime, err); return; @@ -432,7 +433,7 @@ 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 realtime = helper.AblyRealtimePromise({ autoConnect: false }), channelName = 'sync_ordering', channel = realtime.channels.get(channelName); @@ -561,7 +562,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var done = function (err) { err ? reject(err) : resolve(); }; - channel.presence.get(function (err, results) { + whenPromiseSettles(channel.presence.get(), function (err, results) { if (err) { closeAndFinish(done, realtime, err); return; @@ -588,8 +589,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presence_sync_interruptus', function (done) { var channelName = 'presence_sync_interruptus'; var interrupterClientId = 'dark_horse'; - var enterer = helper.AblyRealtime(); - var syncer = helper.AblyRealtime(); + var enterer = helper.AblyRealtimePromise(); + var syncer = helper.AblyRealtimePromise(); var entererChannel = enterer.channels.get(channelName); var syncerChannel = syncer.channels.get(channelName); @@ -613,13 +614,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async [ waitForBothConnect, function (cb) { - entererChannel.attach(cb); + whenPromiseSettles(entererChannel.attach(), cb); }, function (cb) { async.times( 110, function (i, presCb) { - entererChannel.presence.enterClient(i.toString(), null, presCb); + whenPromiseSettles(entererChannel.presence.enterClient(i.toString(), null), presCb); }, cb ); @@ -645,10 +646,10 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); } }; - syncerChannel.attach(cb); + whenPromiseSettles(syncerChannel.attach(), cb); }, function (cb) { - syncerChannel.presence.get(function (err, presenceSet) { + whenPromiseSettles(syncerChannel.presence.get(), function (err, presenceSet) { try { expect(presenceSet && presenceSet.length).to.equal(111, 'Check everyone’s in presence set'); } catch (err) { diff --git a/test/realtime/upgrade.test.js b/test/realtime/upgrade.test.js index 08c785e4b5..674035ad47 100644 --- a/test/realtime/upgrade.test.js +++ b/test/realtime/upgrade.test.js @@ -18,6 +18,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai var closeAndFinish = helper.closeAndFinish; var monitorConnection = helper.monitorConnection; var bestTransport = helper.bestTransport; + var whenPromiseSettles = helper.whenPromiseSettles; if (bestTransport === 'web_socket') { describe('realtime/upgrade', function () { @@ -29,7 +30,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai done(err); return; } - rest = helper.AblyRest(); + rest = helper.AblyRestPromise(); done(); }); }); @@ -42,13 +43,13 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('publishpreupgrade', function (done) { var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtime(transportOpts); + var realtime = helper.AblyRealtimePromise(transportOpts); /* connect and attach */ realtime.connection.on('connected', function () { //console.log('publishpreupgrade: connected'); var testMsg = 'Hello world'; var rtChannel = realtime.channels.get('publishpreupgrade'); - rtChannel.attach(function (err) { + whenPromiseSettles(rtChannel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -67,7 +68,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai /* publish event */ var restChannel = rest.channels.get('publishpreupgrade'); - restChannel.publish('event0', testMsg, function (err) { + whenPromiseSettles(restChannel.publish('event0', testMsg), function (err) { if (err) { closeAndFinish(done, realtime, err); } @@ -86,7 +87,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('publishpostupgrade0', function (done) { var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtime(transportOpts); + var realtime = helper.AblyRealtimePromise(transportOpts); /* subscribe to event */ var rtChannel = realtime.channels.get('publishpostupgrade0'); @@ -113,7 +114,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai if (transport.toString().match(/wss?\:/)) { if (rtChannel.state == 'attached') { //console.log('*** publishpostupgrade0: publishing (channel attached on transport active) ...'); - restChannel.publish('event0', testMsg, function (err) { + whenPromiseSettles(restChannel.publish('event0', testMsg), function (err) { //console.log('publishpostupgrade0: publish returned err = ' + displayError(err)); if (err) { closeAndFinish(done, realtime, err); @@ -122,7 +123,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai } else { rtChannel.on('attached', function () { //console.log('*** publishpostupgrade0: publishing (channel attached after wait) ...'); - restChannel.publish('event0', testMsg, function (err) { + whenPromiseSettles(restChannel.publish('event0', testMsg), function (err) { //console.log('publishpostupgrade0: publish returned err = ' + displayError(err)); if (err) { closeAndFinish(done, realtime, err); @@ -144,7 +145,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('publishpostupgrade1', function (done) { var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtime(transportOpts); + var realtime = helper.AblyRealtimePromise(transportOpts); /* subscribe to event */ var rtChannel = realtime.channels.get('publishpostupgrade1'); @@ -219,7 +220,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai checkFinish(); }; var transportOpts = { useBinaryProtocol: false, transports: helper.availableTransports }; - var realtime = helper.AblyRealtime(transportOpts); + var realtime = helper.AblyRealtimePromise(transportOpts); var channel = realtime.channels.get('upgradepublish0'); /* subscribe to event */ channel.subscribe( @@ -253,7 +254,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai checkFinish(); }; var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; - var realtime = helper.AblyRealtime(transportOpts); + var realtime = helper.AblyRealtimePromise(transportOpts); var channel = realtime.channels.get('upgradepublish1'); /* subscribe to event */ channel.subscribe( @@ -278,7 +279,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; var cometDeactivated = false; try { - var realtime = helper.AblyRealtime(transportOpts); + var realtime = helper.AblyRealtimePromise(transportOpts); /* check that we see the transport we're interested in get activated, * and that we see the comet transport deactivated */ var failTimer = setTimeout(function () { @@ -320,7 +321,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('upgradeheartbeat0', function (done) { var transportOpts = { useBinaryProtocol: false, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtime(transportOpts); + var realtime = helper.AblyRealtimePromise(transportOpts); /* when we see the transport we're interested in get activated, * listen for the heartbeat event */ @@ -353,7 +354,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('upgradeheartbeat1', function (done) { var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtime(transportOpts); + var realtime = helper.AblyRealtimePromise(transportOpts); /* when we see the transport we're interested in get activated, * listen for the heartbeat event */ @@ -386,7 +387,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('upgradeheartbeat2', function (done) { var transportOpts = { useBinaryProtocol: false, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtime(transportOpts); + var realtime = helper.AblyRealtimePromise(transportOpts); /* when we see the transport we're interested in get activated, * listen for the heartbeat event */ @@ -432,7 +433,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('upgradeheartbeat3', function (done) { var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtime(transportOpts); + var realtime = helper.AblyRealtimePromise(transportOpts); /* when we see the transport we're interested in get activated, * listen for the heartbeat event */ @@ -479,7 +480,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai try { /* on base transport active */ - realtime = helper.AblyRealtime({ transports: helper.availableTransports }); + realtime = helper.AblyRealtimePromise({ transports: helper.availableTransports }); realtime.connection.connectionManager.once('transport.active', function (transport) { expect( transport.toString().indexOf('/comet/') > -1, @@ -512,7 +513,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai /* Check events not still paused */ var channel = realtime.channels.get('unrecoverableUpgrade'); - channel.attach(function (err) { + whenPromiseSettles(channel.attach(), function (err) { if (err) { closeAndFinish(done, realtime, err); return; @@ -534,7 +535,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai * seamlessly transferred to the websocket transport and published there */ it('message_timeout_stalling_upgrade', function (done) { - var realtime = helper.AblyRealtime({ transports: helper.availableTransports, httpRequestTimeout: 3000 }), + var realtime = helper.AblyRealtimePromise({ transports: helper.availableTransports, httpRequestTimeout: 3000 }), channel = realtime.channels.get('timeout1'), connectionManager = realtime.connection.connectionManager; @@ -557,7 +558,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai }); }, function (cb) { - channel.publish('event', null, function (err) { + whenPromiseSettles(channel.publish('event', null), function (err) { try { expect(!err, 'Successfully published message').to.be.ok; } catch (err) { @@ -580,7 +581,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai * and subsequent connections do not upgrade */ it('persist_transport_prefs', function (done) { - var realtime = helper.AblyRealtime({ transports: helper.availableTransports }), + var realtime = helper.AblyRealtimePromise({ transports: helper.availableTransports }), connection = realtime.connection, connectionManager = connection.connectionManager; @@ -642,7 +643,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai * Check that upgrades succeed even if the original transport dies before the sync */ it('upgrade_original_transport_dies', function (done) { - var realtime = helper.AblyRealtime({ transports: helper.availableTransports }), + var realtime = helper.AblyRealtimePromise({ transports: helper.availableTransports }), connection = realtime.connection, connectionManager = connection.connectionManager; From 45b9c3bc652502a8cd84aba6fcb11fcce5517e6f Mon Sep 17 00:00:00 2001 From: Lawrence Forooghian Date: Thu, 22 Jun 2023 09:59:10 -0300 Subject: [PATCH 29/30] Remove obsolete Promise-based Realtime tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit No longer needed as of 43a2d1d. I’ve kept the tests for EventEmitter (since, as mentioned in aforementioned commit, the main body of the tests uses the callback-based API), and also for init.test.js, which tests the result of `require('../../promises')`. --- test/realtime/connection.test.js | 26 ----- test/realtime/message.test.js | 45 --------- test/realtime/presence.test.js | 165 ------------------------------- 3 files changed, 236 deletions(-) diff --git a/test/realtime/connection.test.js b/test/realtime/connection.test.js index 3922e745fb..d0923de040 100644 --- a/test/realtime/connection.test.js +++ b/test/realtime/connection.test.js @@ -283,31 +283,5 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); monitorConnection(done, realtime); }); - - if (typeof Promise !== 'undefined') { - describe('connection_promise', function () { - it('ping', function (done) { - var client = helper.AblyRealtimePromise({ internal: { promises: true } }); - - client.connection - .once('connected') - .then(function () { - client.connection - .ping() - .then(function (responseTime) { - expect(typeof responseTime).to.equal('number', 'check that a responseTime returned'); - expect(responseTime > 0, 'check that responseTime was positive').to.be.ok; - closeAndFinish(done, client); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - }); - }); - } }); }); diff --git a/test/realtime/message.test.js b/test/realtime/message.test.js index c5463cb692..623f1c0946 100644 --- a/test/realtime/message.test.js +++ b/test/realtime/message.test.js @@ -1151,51 +1151,6 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }); - if (typeof Promise !== 'undefined') { - it('publishpromise', function (done) { - var realtime = helper.AblyRealtimePromise({ internal: { promises: true } }); - var channel = realtime.channels.get('publishpromise'); - - var publishPromise = realtime.connection - .once('connected') - .then(function (connectionStateChange) { - expect(connectionStateChange.current).to.equal( - 'connected', - 'Check promise is resolved with a connectionStateChange' - ); - return channel.attach(); - }) - .then(function () { - return channel.publish('name', 'data'); - }) - ['catch'](function (err) { - closeAndFinish(done, realtime, err); - }); - - var subscribePromise; - var messagePromise = new Promise(function (msgResolve) { - subscribePromise = channel.subscribe('name', function (msg) { - msgResolve(); - }); - }); - - var channelFailedPromise = realtime.channels - .get(':invalid') - .attach() - ['catch'](function (err) { - expect(err.code).to.equal(40010, 'Check err passed through correctly'); - }); - - Promise.all([publishPromise, subscribePromise, messagePromise, channelFailedPromise]) - .then(function () { - closeAndFinish(done, realtime); - }) - ['catch'](function (err) { - closeAndFinish(done, realtime, err); - }); - }); - } - it('subscribes to filtered channel', function (done) { var testData = [ { diff --git a/test/realtime/presence.test.js b/test/realtime/presence.test.js index 0f5d08bbfb..4324c8f333 100644 --- a/test/realtime/presence.test.js +++ b/test/realtime/presence.test.js @@ -2075,170 +2075,5 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async ); }); }); - - if (typeof Promise !== 'undefined') { - describe('presence_promise', function () { - var options = { clientId: testClientId, internal: { promises: true } }; - - it('enter_get', function (done) { - var client = helper.AblyRealtimePromise(options); - var channel = client.channels.get('presence_promise_get'); - var testData = 'test_presence_data'; - - channel.presence - .subscribe(function () { - channel.presence - .get() - .then(function (members) { - expect(members.length).to.equal(1, 'Expect test client to be the only member present'); - expect(members[0].clientId).to.equal(testClientId, 'Expected test clientId to be correct'); - expect(members[0].data).to.equal(testData, 'Expected data to be correct'); - closeAndFinish(done, client); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - }) - .then(function () { - channel.presence.enter(testData)['catch'](function (err) { - closeAndFinish(done, client, err); - }); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - }); - - it('update', function (done) { - var client = helper.AblyRealtimePromise(options); - var channel = client.channels.get('presence_promise_update'); - var testData1 = 'test_presence_data1'; - var testData2 = 'test_presence_data2'; - var idx = 0; - - channel.presence - .subscribe(function () { - if (idx === 0) { - idx++; - channel.presence - .get() - .then(function (members) { - expect(members.length).to.equal(1, 'Expect test client to be the only member present'); - expect(members[0].clientId).to.equal(testClientId, 'Expected test clientId to be correct'); - expect(members[0].data).to.equal(testData1, 'Expected data to be correct'); - channel.presence.update(testData2)['catch'](function (err) { - // If idx == 2 this means the update was succesful but the connection was closed before it was ACKed - if (idx !== 2) { - closeAndFinish(done, client, err); - } - }); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - } else { - idx++; - channel.presence - .get() - .then(function (members) { - expect(members.length).to.equal(1, 'Expect test client to be the only member present'); - expect(members[0].clientId).to.equal(testClientId, 'Expected test clientId to be correct'); - expect(members[0].data).to.equal(testData2, 'Expected data to be correct'); - closeAndFinish(done, client); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - } - }) - .then(function () { - channel.presence.enter(testData1)['catch'](function (err) { - closeAndFinish(done, client, err); - }); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - }); - - it('enterClient_leaveClient', function (done) { - var client = helper.AblyRealtimePromise(options); - var channel = client.channels.get('presence_promise_leaveClient'); - var idx = 0; - - channel.presence - .subscribe(function () { - if (idx === 0) { - idx++; - channel.presence - .get() - .then(function (members) { - expect(members.length).to.equal(1, 'Expect test client to be the only member present'); - expect(members[0].clientId).to.equal(testClientId, 'Expected test clientId to be correct'); - channel.presence.leaveClient(testClientId)['catch'](function (err) { - // If idx == 2 this means the leave was succesful but the connection was closed before it was ACKed - if (idx !== 2) { - closeAndFinish(done, client, err); - } - }); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - } else { - idx++; - channel.presence - .get() - .then(function (members) { - expect(members.length).to.equal(0, 'Expect test client to no longer be present'); - closeAndFinish(done, client); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - } - }) - .then(function () { - channel.presence - .enterClient(testClientId) - .then(function () {}) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - }); - - it('history', function (done) { - var client = helper.AblyRealtimePromise(options); - var channel = client.channels.get('presence_promise_history'); - channel.presence - .history() - .then(function (page) { - // Tests for promisified PaginatedResource exist elsewhere in the repo so are omitted here - closeAndFinish(done, client); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - }); - - it('subscribe', function (done) { - var client = helper.AblyRealtimePromise(options); - var channel = client.channels.get('presence_promise_subscribe'); - channel.presence - .subscribe(function () {}) - .then(function () { - expect(channel.state).to.equal('attached'); - closeAndFinish(done, client); - }) - ['catch'](function (err) { - closeAndFinish(done, client, err); - }); - }); - }); - } }); }); From d0f034ecc0f1d63fda1893a3f7208da75b2955d2 Mon Sep 17 00:00:00 2001 From: Lawrence Forooghian Date: Mon, 19 Jun 2023 16:28:18 -0300 Subject: [PATCH 30/30] Remove "Promise" from name of Ably*Promise helpers Thus replacing the (unused as of 6fe4914) callback versions. --- test/browser/connection.test.js | 32 +++---- test/browser/http.test.js | 2 +- test/browser/simple.test.js | 2 +- test/common/modules/client_module.js | 10 --- test/common/modules/shared_helper.js | 6 +- test/realtime/auth.test.js | 126 +++++++++++++-------------- test/realtime/channel.test.js | 76 ++++++++-------- test/realtime/connection.test.js | 12 +-- test/realtime/connectivity.test.js | 17 ++-- test/realtime/crypto.test.js | 30 +++---- test/realtime/delta.test.js | 10 +-- test/realtime/encoding.test.js | 8 +- test/realtime/event_emitter.test.js | 34 ++++---- test/realtime/failure.test.js | 22 ++--- test/realtime/history.test.js | 4 +- test/realtime/init.test.js | 26 +++--- test/realtime/message.test.js | 58 ++++++------ test/realtime/presence.test.js | 92 +++++++++---------- test/realtime/reauth.test.js | 4 +- test/realtime/resume.test.js | 34 ++++---- test/realtime/sync.test.js | 14 +-- test/realtime/upgrade.test.js | 30 +++---- test/rest/auth.test.js | 26 +++--- test/rest/capability.test.js | 2 +- test/rest/fallbacks.test.js | 4 +- test/rest/history.test.js | 2 +- test/rest/http.test.js | 2 +- test/rest/init.test.js | 14 +-- test/rest/message.test.js | 18 ++-- test/rest/presence.test.js | 2 +- test/rest/push.test.js | 26 +++--- test/rest/request.test.js | 6 +- test/rest/stats.test.js | 2 +- test/rest/status.test.js | 2 +- test/rest/time.test.js | 2 +- 35 files changed, 368 insertions(+), 389 deletions(-) diff --git a/test/browser/connection.test.js b/test/browser/connection.test.js index 3ae2abdba3..d615c133c8 100644 --- a/test/browser/connection.test.js +++ b/test/browser/connection.test.js @@ -51,7 +51,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('device_going_offline_causes_disconnected_state', function (done) { - var realtime = helper.AblyRealtimePromise(), + var realtime = helper.AblyRealtime(), connection = realtime.connection, offlineEvent = new Event('offline', { bubbles: true }); @@ -94,7 +94,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { it('device_going_online_causes_disconnected_connection_to_reconnect_immediately', function (done) { /* Give up trying to connect fairly quickly */ - var realtime = helper.AblyRealtimePromise({ realtimeRequestTimeout: 1000 }), + var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 1000 }), connection = realtime.connection, onlineEvent = new Event('online', { bubbles: true }); @@ -139,7 +139,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { it('device_going_online_causes_suspended_connection_to_reconnect_immediately', function (done) { /* move to suspended state after 2s of being disconnected */ - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ disconnectedRetryTimeout: 500, realtimeRequestTimeout: 500, connectionStateTtl: 2000, @@ -183,7 +183,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('device_going_online_causes_connecting_connection_to_retry_attempt', function (done) { - var realtime = helper.AblyRealtimePromise({}), + var realtime = helper.AblyRealtime({}), connection = realtime.connection, onlineEvent = new Event('online', { bubbles: true }), oldTransport, @@ -223,7 +223,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { cb(true); }, }, - realtime = helper.AblyRealtimePromise(realtimeOpts), + realtime = helper.AblyRealtime(realtimeOpts), refreshEvent = new Event('beforeunload', { bubbles: true }); monitorConnection(done, realtime); @@ -242,7 +242,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { return; } - var newRealtime = helper.AblyRealtimePromise(realtimeOpts); + var newRealtime = helper.AblyRealtime(realtimeOpts); newRealtime.connection.once('connected', function () { try { expect( @@ -264,7 +264,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { cb(false); }, }; - var realtime = helper.AblyRealtimePromise(realtimeOpts), + var realtime = helper.AblyRealtime(realtimeOpts), refreshEvent = new Event('beforeunload', { bubbles: true }); monitorConnection(done, realtime); @@ -283,7 +283,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { return; } - var newRealtime = helper.AblyRealtimePromise(realtimeOpts); + var newRealtime = helper.AblyRealtime(realtimeOpts); newRealtime.connection.once('connected', function () { try { expect( @@ -301,7 +301,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('page_refresh_with_close_on_unload', function (done) { - var realtime = helper.AblyRealtimePromise({ closeOnUnload: true }), + var realtime = helper.AblyRealtime({ closeOnUnload: true }), refreshEvent = new Event('beforeunload', { bubbles: true }); monitorConnection(done, realtime); @@ -321,7 +321,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('page_refresh_with_manual_recovery', function (done) { - var realtime = helper.AblyRealtimePromise({ closeOnUnload: false }), + var realtime = helper.AblyRealtime({ closeOnUnload: false }), refreshEvent = new Event('beforeunload', { bubbles: true }); monitorConnection(done, realtime); @@ -342,7 +342,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { return; } - var newRealtime = helper.AblyRealtimePromise({ recover: recoveryKey }); + var newRealtime = helper.AblyRealtime({ recover: recoveryKey }); newRealtime.connection.once('connected', function () { try { expect( @@ -359,7 +359,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('persist_preferred_transport', function (done) { - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); realtime.connection.connectionManager.on(function (transport) { if (this.event === 'transport.active' && transport.shortName === 'web_socket') { @@ -381,7 +381,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { var transportPreferenceName = 'ably-transport-preference'; window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: 'web_socket' })); - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); realtime.connection.connectionManager.on(function (transport) { if (this.event === 'transport.active') { @@ -400,7 +400,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { it('use_persisted_transport1', function (done) { window.localStorage.setItem(transportPreferenceName, JSON.stringify({ value: 'xhr_streaming' })); - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); realtime.connection.connectionManager.on(function (transport) { if (this.event === 'transport.active') { @@ -417,7 +417,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('browser_transports', function (done) { - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); try { expect(realtime.connection.connectionManager.baseTransport).to.equal('xhr_polling'); expect(realtime.connection.connectionManager.upgradeTransports).to.deep.equal([ @@ -437,7 +437,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { * realtime) */ it('connection behaviour with a proxy through which streaming is broken', function (done) { - const realtime = helper.AblyRealtimePromise({ + const realtime = helper.AblyRealtime({ transportParams: { simulateNoStreamingProxy: true, maxStreamDuration: 7500, diff --git a/test/browser/http.test.js b/test/browser/http.test.js index 8c810f04b0..5db5ea7894 100644 --- a/test/browser/http.test.js +++ b/test/browser/http.test.js @@ -12,7 +12,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { initialXhrSupported = Ably.Rest.Platform.Config.xhrSupported; Ably.Rest.Platform.Config.xhrSupported = false; helper.setupApp(function () { - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); done(); }); }); diff --git a/test/browser/simple.test.js b/test/browser/simple.test.js index e4ca140ec1..bfc22014d7 100644 --- a/test/browser/simple.test.js +++ b/test/browser/simple.test.js @@ -23,7 +23,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { function realtimeConnection(transports) { var options = {}; if (transports) options.transports = transports; - return helper.AblyRealtimePromise(options); + return helper.AblyRealtime(options); } function failWithin(timeInSeconds, done, ably, description) { diff --git a/test/common/modules/client_module.js b/test/common/modules/client_module.js index df26c74cff..d0806d6d4b 100644 --- a/test/common/modules/client_module.js +++ b/test/common/modules/client_module.js @@ -23,26 +23,16 @@ define(['ably', 'globals', 'test/common/modules/testapp_module'], function (Ably } function ablyRest(options) { - return new Ably.Rest(ablyClientOptions(options)); - } - - function ablyRestPromise(options) { return new Ably.Rest.Promise(ablyClientOptions(options)); } function ablyRealtime(options) { - return new Ably.Realtime(ablyClientOptions(options)); - } - - function ablyRealtimePromise(options) { return new Ably.Realtime.Promise(ablyClientOptions(options)); } return (module.exports = { Ably: Ably, AblyRest: ablyRest, - AblyRestPromise: ablyRestPromise, AblyRealtime: ablyRealtime, - AblyRealtimePromise: ablyRealtimePromise, }); }); diff --git a/test/common/modules/shared_helper.js b/test/common/modules/shared_helper.js index 8af3164629..0790322075 100644 --- a/test/common/modules/shared_helper.js +++ b/test/common/modules/shared_helper.js @@ -164,10 +164,10 @@ define([ function restTestOnJsonMsgpack(name, testFn, skip) { var itFn = skip ? it.skip : it; itFn(name + ' with binary protocol', async function () { - await testFn(new clientModule.AblyRestPromise({ useBinaryProtocol: true }), name + '_binary'); + await testFn(new clientModule.AblyRest({ useBinaryProtocol: true }), name + '_binary'); }); itFn(name + ' with text protocol', async function () { - await testFn(new clientModule.AblyRestPromise({ useBinaryProtocol: false }), name + '_text'); + await testFn(new clientModule.AblyRest({ useBinaryProtocol: false }), name + '_text'); }); } @@ -226,9 +226,7 @@ define([ Ably: clientModule.Ably, AblyRest: clientModule.AblyRest, - AblyRestPromise: clientModule.AblyRestPromise, AblyRealtime: clientModule.AblyRealtime, - AblyRealtimePromise: clientModule.AblyRealtimePromise, Utils: utils, loadTestData: testAppManager.loadJsonData, diff --git a/test/realtime/auth.test.js b/test/realtime/auth.test.js index b36ca70159..92dde3019a 100644 --- a/test/realtime/auth.test.js +++ b/test/realtime/auth.test.js @@ -40,7 +40,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var rest = helper.AblyRestPromise({ queryTime: true }); + var rest = helper.AblyRest({ queryTime: true }); whenPromiseSettles(rest.time(), function (err, time) { if (err) { done(err); @@ -64,7 +64,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async * Base token generation case */ it('authbase0', function (done) { - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); whenPromiseSettles(realtime.auth.requestToken(), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); @@ -88,7 +88,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthUrl_json', function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); @@ -97,7 +97,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var authPath = echoServer + '/?type=json&body=' + encodeURIComponent(JSON.stringify(tokenDetails)); - realtime = helper.AblyRealtimePromise({ authUrl: authPath }); + realtime = helper.AblyRealtime({ authUrl: authPath }); realtime.connection.on('connected', function () { closeAndFinish(done, realtime); @@ -113,7 +113,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthUrl_post_json', function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); @@ -122,7 +122,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var authUrl = echoServer + '/?type=json&'; - realtime = helper.AblyRealtimePromise({ authUrl: authUrl, authMethod: 'POST', authParams: tokenDetails }); + realtime = helper.AblyRealtime({ authUrl: authUrl, authMethod: 'POST', authParams: tokenDetails }); realtime.connection.on('connected', function () { closeAndFinish(done, realtime); @@ -138,7 +138,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthUrl_plainText', function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); @@ -147,7 +147,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var authPath = echoServer + '/?type=text&body=' + tokenDetails['token']; - realtime = helper.AblyRealtimePromise({ authUrl: authPath }); + realtime = helper.AblyRealtime({ authUrl: authPath }); realtime.connection.on('connected', function () { closeAndFinish(done, realtime); @@ -163,7 +163,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthCallback_tokenRequestResponse', function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); var authCallback = function (tokenParams, callback) { whenPromiseSettles(rest.auth.createTokenRequest(tokenParams, null), function (err, tokenRequest) { if (err) { @@ -179,7 +179,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); + realtime = helper.AblyRealtime({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { @@ -200,7 +200,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthCallback_tokenDetailsResponse', function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { @@ -218,7 +218,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtimePromise({ authCallback: authCallback, clientId: clientId }); + realtime = helper.AblyRealtime({ authCallback: authCallback, clientId: clientId }); realtime.connection.on('connected', function () { try { @@ -237,7 +237,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthCallback_tokenStringResponse', function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); var authCallback = function (tokenParams, callback) { whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { if (err) { @@ -253,7 +253,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); + realtime = helper.AblyRealtime({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { @@ -275,7 +275,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('auth_useAuthUrl_mixed_authParams_qsParams', function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); whenPromiseSettles(rest.auth.createTokenRequest(null, null), function (err, tokenRequest) { if (err) { closeAndFinish(done, realtime, err); @@ -296,7 +296,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }; var authPath = echoServer + '/qs_to_body' + utils.toQueryString(lowerPrecedenceTokenRequestParts); - realtime = helper.AblyRealtimePromise({ authUrl: authPath, authParams: higherPrecedenceTokenRequestParts }); + realtime = helper.AblyRealtime({ authUrl: authPath, authParams: higherPrecedenceTokenRequestParts }); realtime.connection.on('connected', function () { closeAndFinish(done, realtime); @@ -310,7 +310,7 @@ 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.AblyRestPromise(), + var rest = helper.AblyRest(), testClientId = 'testClientId'; var authCallback = function (tokenParams, callback) { whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { @@ -322,7 +322,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); + var realtime = helper.AblyRealtime({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { @@ -350,13 +350,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('auth_clientid_inheritance2', function (done) { var clientRealtime, testClientId = 'test client id'; - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { if (err) { done(err); return; } - clientRealtime = helper.AblyRealtimePromise({ token: tokenDetails, clientId: 'WRONG' }); + clientRealtime = helper.AblyRealtime({ token: tokenDetails, clientId: 'WRONG' }); clientRealtime.connection.once('failed', function (stateChange) { try { expect(stateChange.reason.code).to.equal(40102); @@ -376,13 +376,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('auth_clientid_inheritance3', function (done) { var realtime, testClientId = 'test client id'; - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken({ clientId: '*' }), function (err, tokenDetails) { if (err) { done(err); return; } - realtime = helper.AblyRealtimePromise({ token: tokenDetails.token, clientId: 'test client id' }); + realtime = helper.AblyRealtime({ token: tokenDetails.token, clientId: 'test client id' }); realtime.connection.on('connected', function () { try { expect(realtime.auth.clientId).to.equal(testClientId); @@ -404,13 +404,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('auth_clientid_inheritance4', function (done) { var realtime, testClientId = 'test client id'; - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken({ clientId: '*' }), function (err, tokenDetails) { if (err) { done(err); return; } - realtime = helper.AblyRealtimePromise({ token: tokenDetails, clientId: 'test client id' }); + realtime = helper.AblyRealtime({ token: tokenDetails, clientId: 'test client id' }); realtime.connection.on('connected', function () { try { expect(realtime.auth.clientId).to.equal(testClientId); @@ -432,13 +432,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('auth_clientid_inheritance5', function (done) { var clientRealtime, testClientId = 'test client id'; - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { if (err) { done(err); return; } - clientRealtime = helper.AblyRealtimePromise({ token: tokenDetails.token }); + clientRealtime = helper.AblyRealtime({ token: tokenDetails.token }); clientRealtime.connection.on('connected', function () { try { expect(clientRealtime.auth.clientId).to.equal(testClientId); @@ -457,7 +457,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ function authCallback_failures(realtimeOptions, expectFailure) { return function (done) { - var realtime = helper.AblyRealtimePromise(realtimeOptions); + var realtime = helper.AblyRealtime(realtimeOptions); realtime.connection.on(function (stateChange) { if (stateChange.previous !== 'initialized') { try { @@ -607,7 +607,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('authUrl_403_previously_active', function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken(null, null), function (err, tokenDetails) { if (err) { closeAndFinish(done, realtime, err); @@ -616,7 +616,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var authPath = echoServer + '/?type=json&body=' + encodeURIComponent(JSON.stringify(tokenDetails)); - realtime = helper.AblyRealtimePromise({ authUrl: authPath }); + realtime = helper.AblyRealtime({ authUrl: authPath }); realtime.connection.on('connected', function () { /* replace the authUrl and reauth */ @@ -649,16 +649,14 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('auth_token_expires', function (realtimeOpts) { return function (done) { var clientRealtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken({ ttl: 5000 }, null), function (err, tokenDetails) { if (err) { done(err); return; } - clientRealtime = helper.AblyRealtimePromise( - mixin(realtimeOpts, { tokenDetails: tokenDetails, queryTime: true }) - ); + clientRealtime = helper.AblyRealtime(mixin(realtimeOpts, { tokenDetails: tokenDetails, queryTime: true })); clientRealtime.connection.on('failed', function () { closeAndFinish(done, clientRealtime, new Error('Failed to connect before token expired')); @@ -685,7 +683,7 @@ 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.AblyRestPromise({ queryTime: true }), + var rest = helper.AblyRest({ queryTime: true }), timeRequestCount = 0, originalTime = rest.time; @@ -743,7 +741,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('auth_tokenDetails_expiry_with_authcallback', function (realtimeOpts) { return function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { tokenParams.ttl = 5000; @@ -756,7 +754,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtimePromise(mixin(realtimeOpts, { authCallback: authCallback, clientId: clientId })); + realtime = helper.AblyRealtime(mixin(realtimeOpts, { authCallback: authCallback, clientId: clientId })); monitorConnection(done, realtime); realtime.connection.once('connected', function () { realtime.connection.once('disconnected', function (stateChange) { @@ -784,7 +782,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('auth_token_string_expiry_with_authcallback', function (realtimeOpts) { return function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); var clientId = 'test clientid'; var authCallback = function (tokenParams, callback) { tokenParams.ttl = 5000; @@ -797,7 +795,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtimePromise(mixin(realtimeOpts, { authCallback: authCallback, clientId: clientId })); + realtime = helper.AblyRealtime(mixin(realtimeOpts, { authCallback: authCallback, clientId: clientId })); monitorConnection(done, realtime); realtime.connection.once('connected', function () { realtime.connection.once('disconnected', function (stateChange) { @@ -824,7 +822,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('auth_token_string_expiry_with_token', function (realtimeOpts) { return function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); var clientId = 'test clientid'; whenPromiseSettles( rest.auth.requestToken({ ttl: 5000, clientId: clientId }, null), @@ -833,9 +831,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async closeAndFinish(done, realtime, err); return; } - realtime = helper.AblyRealtimePromise( - mixin(realtimeOpts, { token: tokenDetails.token, clientId: clientId }) - ); + realtime = helper.AblyRealtime(mixin(realtimeOpts, { token: tokenDetails.token, clientId: clientId })); realtime.connection.once('connected', function () { realtime.connection.once('disconnected', function (stateChange) { try { @@ -867,7 +863,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('auth_expired_token_string', function (realtimeOpts) { return function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); var clientId = 'test clientid'; whenPromiseSettles(rest.auth.requestToken({ ttl: 1, clientId: clientId }, null), function (err, tokenDetails) { if (err) { @@ -875,9 +871,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } setTimeout(function () { - realtime = helper.AblyRealtimePromise( - mixin(realtimeOpts, { token: tokenDetails.token, clientId: clientId }) - ); + realtime = helper.AblyRealtime(mixin(realtimeOpts, { token: tokenDetails.token, clientId: clientId })); realtime.connection.once('failed', function (stateChange) { try { expect(stateChange.reason.code).to.equal(40171, 'Verify correct failure code'); @@ -908,7 +902,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports.skip('reauth_authCallback', function (realtimeOpts) { return function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); var firstTime = true; var authCallback = function (tokenParams, callback) { tokenParams.clientId = '*'; @@ -923,7 +917,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }; - realtime = helper.AblyRealtimePromise(mixin(realtimeOpts, { authCallback: authCallback })); + realtime = helper.AblyRealtime(mixin(realtimeOpts, { authCallback: authCallback })); realtime.connection.once('connected', function () { var channel = realtime.channels.get('right'); whenPromiseSettles(channel.attach(), function (err) { @@ -960,7 +954,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* RSA10j */ it('authorize_updates_stored_details', function (done) { - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ autoConnect: false, defaultTokenParams: { version: 1 }, token: '1', @@ -991,7 +985,7 @@ 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.AblyRestPromise(), + var rest = helper.AblyRest(), authCallback = function (tokenParams, callback) { // Request a token (should happen twice) whenPromiseSettles(rest.auth.requestToken(tokenParams, null), function (err, tokenDetails) { @@ -1002,7 +996,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async callback(null, tokenDetails); }); }, - realtime = helper.AblyRealtimePromise({ authCallback: authCallback, transports: [helper.bestTransport] }); + realtime = helper.AblyRealtime({ authCallback: authCallback, transports: [helper.bestTransport] }); realtime.connection.once('connected', function () { var transport = realtime.connection.connectionManager.activeProtocol.transport, @@ -1038,7 +1032,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async getJWT(params, callback); }; - var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); + var realtime = helper.AblyRealtime({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { @@ -1071,7 +1065,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async getJWT(params, callback); }; - var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); + var realtime = helper.AblyRealtime({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { @@ -1102,7 +1096,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async getJWT(params, callback); }; - var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); + var realtime = helper.AblyRealtime({ authCallback: authCallback }); realtime.connection.once('connected', function () { var channel = realtime.channels.get(jwtTestChannelName); whenPromiseSettles(channel.publish('greeting', 'Hello World!'), function (err) { @@ -1131,7 +1125,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var publishEvent = 'publishEvent', messageData = 'Hello World!'; - var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); + var realtime = helper.AblyRealtime({ authCallback: authCallback }); realtime.connection.once('connected', function () { var channel = realtime.channels.get(jwtTestChannelName); channel.subscribe(publishEvent, function (msg) { @@ -1158,7 +1152,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async getJWT(params, callback); }; - var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); + var realtime = helper.AblyRealtime({ authCallback: authCallback }); realtime.connection.once('connected', function () { realtime.connection.once('disconnected', function (stateChange) { try { @@ -1185,7 +1179,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async getJWT(params, callback); }; - var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); + var realtime = helper.AblyRealtime({ authCallback: authCallback }); realtime.connection.once('connected', function () { var originalToken = realtime.auth.tokenDetails.token; realtime.connection.once('update', function () { @@ -1212,7 +1206,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async done(err); return; } - var realtime = helper.AblyRealtimePromise({ token: token }); + var realtime = helper.AblyRealtime({ token: token }); realtime.connection.once('connected', function () { try { expect(token).to.equal(realtime.auth.tokenDetails.token, 'Verify that token is the same'); @@ -1228,7 +1222,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* RTN14b */ it('reauth_consistently_expired_token', function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken({ ttl: 1 }), function (err, token) { if (err) { done(err); @@ -1241,7 +1235,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }; /* Wait a few ms to ensure token is expired */ setTimeout(function () { - realtime = helper.AblyRealtimePromise({ authCallback: authCallback, disconnectedRetryTimeout: 15000 }); + realtime = helper.AblyRealtime({ authCallback: authCallback, disconnectedRetryTimeout: 15000 }); /* Wait 5s, expect to have seen two attempts to get a token -- so the * authCallback called twice -- and the connection to now be sitting in * the disconnected state */ @@ -1261,7 +1255,7 @@ 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, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken(), function (err, token) { if (err) { done(err); @@ -1274,7 +1268,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async authCallbackCallCount++; callback(null, token); }; - realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); + realtime = helper.AblyRealtime({ authCallback: authCallback }); realtime.connection.on('connected', function () { try { expect(authCallbackCallCount).to.equal(1, 'Check we did not autoremove an expired token ourselves'); @@ -1289,7 +1283,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* RSA4b1 second case */ it('expired_token_autoremove_when_have_servertime', function (done) { var realtime, - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken(), function (err, token) { if (err) { done(err); @@ -1302,7 +1296,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async authCallbackCallCount++; callback(null, token); }; - realtime = helper.AblyRealtimePromise({ authCallback: authCallback, autoConnect: false }); + realtime = helper.AblyRealtime({ authCallback: authCallback, autoConnect: false }); /* Set the server time offset */ whenPromiseSettles(realtime.time(), function () { realtime.connect(); @@ -1323,7 +1317,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* Check that only the last authorize matters */ it('multiple_concurrent_authorize', function (done) { - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ logLevel: 4, useTokenAuth: true, defaultTokenParams: { capability: { wrong: ['*'] } }, @@ -1368,7 +1362,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('authorize_immediately_after_init', function (realtimeOpts) { return function (done) { - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ useTokenAuth: true, defaultTokenParams: { capability: { wrong: ['*'] } }, }); diff --git a/test/realtime/channel.test.js b/test/realtime/channel.test.js index 9447865aa6..aee99ab380 100644 --- a/test/realtime/channel.test.js +++ b/test/realtime/channel.test.js @@ -177,7 +177,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelinit0', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { try { /* set options on init */ @@ -210,7 +210,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattach0', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { var channel0 = realtime.channels.get('channelattach0'); whenPromiseSettles(channel0.attach(), function (err) { @@ -233,7 +233,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattach2', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); var channel2 = realtime.channels.get('channelattach2'); whenPromiseSettles(channel2.attach(), function (err) { if (err) { @@ -257,7 +257,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { var channel0 = realtime.channels.get('channelattach3'); whenPromiseSettles(channel0.attach(), function (err) { @@ -295,7 +295,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattachempty', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { var channel0 = realtime.channels.get(''); whenPromiseSettles(channel0.attach(), function (err) { @@ -327,7 +327,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattachinvalid', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { var channel = realtime.channels.get(':hell'); whenPromiseSettles(channel.attach(), function (err) { @@ -365,7 +365,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('publish_no_attach', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { whenPromiseSettles(realtime.channels.get('publish_no_attach').publish(), function (err) { if (err) { @@ -388,7 +388,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattach_publish_invalid', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { whenPromiseSettles(realtime.channels.get(':hell').publish(), function (err) { if (err) { @@ -417,7 +417,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('channelattach_invalid_twice', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { whenPromiseSettles(realtime.channels.get(':hell').attach(), function (err) { if (err) { @@ -453,7 +453,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('channelattachOnceOrIfAfter', function (done) { try { - var realtime = helper.AblyRealtimePromise(), + var realtime = helper.AblyRealtime(), channel = realtime.channels.get('channelattachOnceOrIf'), firedImmediately = false; @@ -479,7 +479,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('channelattachOnceOrIfBefore', function (done) { try { - var realtime = helper.AblyRealtimePromise(), + var realtime = helper.AblyRealtime(), channel = realtime.channels.get('channelattachOnceOrIf'), firedImmediately = false; @@ -504,7 +504,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'attachWithChannelParamsBasicChannelsGet'; try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { var params = { modes: 'subscribe', @@ -528,7 +528,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var testRealtime = helper.AblyRealtimePromise(); + var testRealtime = helper.AblyRealtime(); testRealtime.connection.on('connected', function () { var testChannel = testRealtime.channels.get(testName); async.series( @@ -557,7 +557,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'attachWithChannelParamsBasicSetOptions'; try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { var params = { modes: 'subscribe', @@ -577,7 +577,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async expect(channel.params).to.deep.equal(params, 'Check result params'); expect(channel.modes).to.deep.equal(['subscribe'], 'Check result modes'); - var testRealtime = helper.AblyRealtimePromise(); + var testRealtime = helper.AblyRealtime(); testRealtime.connection.on('connected', function () { var testChannel = testRealtime.channels.get(testName); async.series( @@ -606,7 +606,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'subscribeAfterSetOptions'; try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { var channel = realtime.channels.get(testName); channel.setOptions({ @@ -635,7 +635,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('channelGetShouldThrowWhenWouldCauseReattach', function (done) { var testName = 'channelGetShouldThrowWhenWouldCauseReattach'; try { - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); realtime.connection.on('connected', function () { var params = { modes: 'subscribe', @@ -676,7 +676,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'setOptionsCallbackBehaviour'; try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { var params = { modes: 'subscribe', @@ -752,7 +752,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'attachWithChannelParamsModesAndChannelModes'; try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { var paramsModes = ['presence', 'subscribe']; var params = { @@ -777,7 +777,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var testRealtime = helper.AblyRealtimePromise(); + var testRealtime = helper.AblyRealtime(); testRealtime.connection.on('connected', function () { var testChannel = testRealtime.channels.get(testName); async.series( @@ -806,7 +806,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'attachWithChannelModes'; try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { var modes = ['publish', 'presence_subscribe']; var channelOptions = { @@ -826,7 +826,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var testRealtime = helper.AblyRealtimePromise(); + var testRealtime = helper.AblyRealtime(); testRealtime.connection.on('connected', function () { var testChannel = testRealtime.channels.get(testName); async.series( @@ -855,7 +855,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var testName = 'attachWithChannelParamsDeltaAndModes'; try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.on('connected', function () { var modes = ['publish', 'subscribe', 'presence_subscribe']; var channelOptions = { @@ -877,7 +877,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var testRealtime = helper.AblyRealtimePromise(); + var testRealtime = helper.AblyRealtime(); testRealtime.connection.on('connected', function () { var testChannel = testRealtime.channels.get(testName); async.series( @@ -906,7 +906,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var testName = 'attachWithInvalidChannelParams'; var defaultChannelModes = 'presence,publish,subscribe,presence_subscribe'; try { - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); realtime.connection.on('connected', function () { var channel = realtime.channels.get(testName); async.series( @@ -1012,7 +1012,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('channelsubscribe0', function (done) { try { - var realtime = helper.AblyRealtimePromise({ useBinaryProtocol: true }); + var realtime = helper.AblyRealtime({ useBinaryProtocol: true }); realtime.connection.on('connected', function () { var channel6 = realtime.channels.get('channelsubscribe0'); whenPromiseSettles(channel6.attach(), function (err) { @@ -1048,7 +1048,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var messagesReceived = 0; try { - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); var channelByEvent, channelByListener, channelAll; var unsubscribeTest = function () { @@ -1123,7 +1123,7 @@ 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.AblyRealtimePromise({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channelName = 'server_sent_detached', channel = realtime.channels.get(channelName); @@ -1174,7 +1174,7 @@ 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.AblyRealtimePromise({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channelName = 'server_sent_detached_while_attaching', channel = realtime.channels.get(channelName); @@ -1214,7 +1214,7 @@ 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.AblyRealtimePromise({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channelName = 'server_sent_error', channel = realtime.channels.get(channelName); @@ -1251,7 +1251,7 @@ 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.AblyRealtimePromise(), + var realtime = helper.AblyRealtime(), channelName = 'server_sent_attached_err', channel = realtime.channels.get(channelName); @@ -1295,7 +1295,7 @@ 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.AblyRealtimePromise({ queueMessages: false }), + var realtime = helper.AblyRealtime({ queueMessages: false }), channel = realtime.channels.get('publish_no_queueing'); /* try a publish while not yet connected */ @@ -1314,7 +1314,7 @@ 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.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport], realtimeRequestTimeout: 2000, channelRetryTimeout: 100, @@ -1362,7 +1362,7 @@ 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.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport], channelRetryTimeout: 1010, suspendedRetryTimeout: 1100, @@ -1430,7 +1430,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* RTL5i */ it('attached_while_detaching', function (done) { - var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channelName = 'server_sent_detached', channel = realtime.channels.get(channelName); @@ -1473,7 +1473,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async // RTL5j it('detaching from suspended channel transitions channel to detached state', function (done) { - var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }); + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); var channelName = 'detach_from_suspended'; var channel = realtime.channels.get(channelName); @@ -1489,7 +1489,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async // RTL5b it('detaching from failed channel results in error', function (done) { - var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }); + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); var channelName = 'detach_from_failed'; var channel = realtime.channels.get(channelName); @@ -1505,7 +1505,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('rewind works on channel after reattaching', function (done) { - var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }); + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }); var channelName = 'rewind_after_detach'; var channel = realtime.channels.get(channelName); var channelOpts = { params: { rewind: '1' } }; diff --git a/test/realtime/connection.test.js b/test/realtime/connection.test.js index d0923de040..16f13c65ac 100644 --- a/test/realtime/connection.test.js +++ b/test/realtime/connection.test.js @@ -23,7 +23,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('connectionPing', function (done) { var realtime; try { - realtime = helper.AblyRealtimePromise(); + realtime = helper.AblyRealtime(); realtime.connection.on('connected', function () { try { realtime.connection.ping(); @@ -41,7 +41,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('connectionPingWithCallback', function (done) { var realtime; try { - realtime = helper.AblyRealtimePromise(); + realtime = helper.AblyRealtime(); realtime.connection.on('connected', function () { whenPromiseSettles(realtime.connection.ping(), function (err, responseTime) { if (err) { @@ -66,7 +66,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('connectionAttributes', function (done) { var realtime; try { - realtime = helper.AblyRealtimePromise({ logLevel: 4 }); + realtime = helper.AblyRealtime({ logLevel: 4 }); realtime.connection.on('connected', function () { try { const recoveryContext = JSON.parse(realtime.connection.recoveryKey); @@ -131,7 +131,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channelSerials: {}, }); try { - realtime = helper.AblyRealtimePromise({ recover: fakeRecoveryKey }); + realtime = helper.AblyRealtime({ recover: fakeRecoveryKey }); realtime.connection.on('connected', function (stateChange) { try { expect(stateChange.reason.code).to.equal( @@ -167,7 +167,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async * without being merged with new messages) */ it('connectionQueuing', function (done) { - var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channel = realtime.channels.get('connectionQueuing'), connectionManager = realtime.connection.connectionManager; @@ -248,7 +248,7 @@ 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.AblyRealtimePromise(), + var realtime = helper.AblyRealtime(), connectionManager = realtime.connection.connectionManager; realtime.connection.once('connected', function () { connectionManager.once('connectiondetails', function (details) { diff --git a/test/realtime/connectivity.test.js b/test/realtime/connectivity.test.js index ca3cfd4949..ea4edc9177 100644 --- a/test/realtime/connectivity.test.js +++ b/test/realtime/connectivity.test.js @@ -47,7 +47,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { } it('succeeds with scheme', function (done) { - new helper.AblyRealtimePromise(options(urlScheme + successUrl)).http.checkConnectivity(function (err, res) { + new helper.AblyRealtime(options(urlScheme + successUrl)).http.checkConnectivity(function (err, res) { try { expect(res && !err, 'Connectivity check completed ' + (err && utils.inspectError(err))).to.be.ok; } catch (err) { @@ -59,7 +59,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('fails with scheme', function (done) { - new helper.AblyRealtimePromise(options(urlScheme + failUrl)).http.checkConnectivity(function (err, res) { + new helper.AblyRealtime(options(urlScheme + failUrl)).http.checkConnectivity(function (err, res) { try { expect(!res, 'Connectivity check expected to return false').to.be.ok; done(); @@ -70,7 +70,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('succeeds with querystring', function (done) { - new helper.AblyRealtimePromise(options(successUrl)).http.checkConnectivity(function (err, res) { + new helper.AblyRealtime(options(successUrl)).http.checkConnectivity(function (err, res) { try { expect(res && !err, 'Connectivity check completed ' + (err && utils.inspectError(err))).to.be.ok; done(); @@ -81,7 +81,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('fails with querystring', function (done) { - new helper.AblyRealtimePromise(options(failUrl)).http.checkConnectivity(function (err, res) { + new helper.AblyRealtime(options(failUrl)).http.checkConnectivity(function (err, res) { try { expect(!res, 'Connectivity check expected to return false').to.be.ok; done(); @@ -92,10 +92,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('succeeds with plain url', function (done) { - new helper.AblyRealtimePromise(options('sandbox-rest.ably.io/time')).http.checkConnectivity(function ( - err, - res - ) { + new helper.AblyRealtime(options('sandbox-rest.ably.io/time')).http.checkConnectivity(function (err, res) { try { expect(res && !err, 'Connectivity check completed ' + (err && utils.inspectError(err))).to.be.ok; done(); @@ -106,7 +103,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('fails with plain url', function (done) { - new helper.AblyRealtimePromise(options('echo.ably.io')).http.checkConnectivity(function (err, res) { + new helper.AblyRealtime(options('echo.ably.io')).http.checkConnectivity(function (err, res) { try { expect(!res, 'Connectivity check expected to return false').to.be.ok; done(); @@ -118,7 +115,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('disable_connectivity_check', function (done) { - new helper.AblyRealtimePromise({ + new helper.AblyRealtime({ connectivityCheckUrl: 'notarealhost', disableConnectivityCheck: true, }).http.checkConnectivity(function (err, res) { diff --git a/test/realtime/crypto.test.js b/test/realtime/crypto.test.js index a430aefa23..ba8f8d13bb 100644 --- a/test/realtime/crypto.test.js +++ b/test/realtime/crypto.test.js @@ -62,7 +62,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async done(new Error('Unable to get test assets; err = ' + displayError(err))); return; } - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); var key = BufferUtils.base64Decode(testData.key); var iv = BufferUtils.base64Decode(testData.iv); var channel = realtime.channels.get(channelName, { cipher: { key: key, iv: iv } }); @@ -409,7 +409,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* For single_send tests we test the 'shortcut' way of setting the cipher * in channels.get. No callback, but that's ok even for node which has * async iv generation since the publish is on an attach cb */ - var realtime = helper.AblyRealtimePromise(realtimeOpts), + var realtime = helper.AblyRealtime(realtimeOpts), channel = realtime.channels.get('single_send', { cipher: { key: key } }), messageText = 'Test message for single_send - ' + JSON.stringify(realtimeOpts); @@ -459,7 +459,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var realtime = helper.AblyRealtimePromise({ useBinaryProtocol: !text }); + var realtime = helper.AblyRealtime({ useBinaryProtocol: !text }); var channelName = 'multiple_send_' + (text ? 'text_' : 'binary_') + iterations + '_' + delay, channel = realtime.channels.get(channelName), messageText = 'Test message (' + channelName + ')'; @@ -527,8 +527,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtimePromise(txOpts), - rxRealtime = helper.AblyRealtimePromise(rxOpts), + var txRealtime = helper.AblyRealtime(txOpts), + rxRealtime = helper.AblyRealtime(rxOpts), channelName = 'single_send_separate_realtimes'; var messageText = 'Test message for single_send_separate_realtimes', txChannel = txRealtime.channels.get(channelName), @@ -603,8 +603,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtimePromise(), - rxRealtime = helper.AblyRealtimePromise(), + var txRealtime = helper.AblyRealtime(), + rxRealtime = helper.AblyRealtime(), channelName = 'publish_immediately', messageText = 'Test message'; @@ -645,8 +645,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtimePromise(); - var rxRealtime = helper.AblyRealtimePromise(); + var txRealtime = helper.AblyRealtime(); + var rxRealtime = helper.AblyRealtime(); var channelName = 'single_send_key_mismatch', txChannel = txRealtime.channels.get(channelName), messageText = 'Test message (' + channelName + ')', @@ -711,8 +711,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtimePromise(); - var rxRealtime = helper.AblyRealtimePromise(); + var txRealtime = helper.AblyRealtime(); + var rxRealtime = helper.AblyRealtime(); var channelName = 'single_send_unencrypted', txChannel = txRealtime.channels.get(channelName), messageText = 'Test message (' + channelName + ')', @@ -754,8 +754,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtimePromise(); - var rxRealtime = helper.AblyRealtimePromise(); + var txRealtime = helper.AblyRealtime(); + var rxRealtime = helper.AblyRealtime(); var channelName = 'single_send_encrypted_unhandled', txChannel = txRealtime.channels.get(channelName), messageText = 'Test message (' + channelName + ')', @@ -798,8 +798,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var txRealtime = helper.AblyRealtimePromise(); - var rxRealtime = helper.AblyRealtimePromise(); + var txRealtime = helper.AblyRealtime(); + var rxRealtime = helper.AblyRealtime(); var channelName = 'set_cipher_params', txChannel = txRealtime.channels.get(channelName), messageText = 'Test message (' + channelName + ')', diff --git a/test/realtime/delta.test.js b/test/realtime/delta.test.js index b66d5951c5..006133c26d 100644 --- a/test/realtime/delta.test.js +++ b/test/realtime/delta.test.js @@ -44,7 +44,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (helper, v var testName = 'deltaPlugin'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ plugins: { vcdiff: testVcdiffDecoder, }, @@ -93,7 +93,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (helper, v var testName = 'unusedPlugin'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ plugins: { vcdiff: testVcdiffDecoder, }, @@ -133,7 +133,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (helper, v var testName = 'lastMessageNotFoundRecovery'; try { var testVcdiffDecoder = getTestVcdiffDecoder(); - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ plugins: { vcdiff: testVcdiffDecoder, }, @@ -201,7 +201,7 @@ define(['shared_helper', 'vcdiff-decoder', 'async', 'chai'], function (helper, v }, }; - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ plugins: { vcdiff: failingTestVcdiffDecoder, }, @@ -246,7 +246,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) { try { - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); var channel = realtime.channels.get('noPlugin', { params: { delta: 'vcdiff' } }); whenPromiseSettles(channel.attach(), function (err) { diff --git a/test/realtime/encoding.test.js b/test/realtime/encoding.test.js index b7837a8ab5..f7c9e49c10 100644 --- a/test/realtime/encoding.test.js +++ b/test/realtime/encoding.test.js @@ -32,8 +32,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async done(err); return; } - var realtime = helper.AblyRealtimePromise({ useBinaryProtocol: false }), - binaryrealtime = helper.AblyRealtimePromise({ useBinaryProtocol: true }), + var realtime = helper.AblyRealtime({ useBinaryProtocol: false }), + binaryrealtime = helper.AblyRealtime({ useBinaryProtocol: true }), channelName = 'message_decoding', channelPath = '/channels/' + channelName + '/messages', channel = realtime.channels.get(channelName), @@ -133,8 +133,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async done(new Error('Unable to get test assets; err = ' + displayError(err))); return; } - var realtime = helper.AblyRealtimePromise({ useBinaryProtocol: false }), - binaryrealtime = helper.AblyRealtimePromise({ useBinaryProtocol: true }), + var realtime = helper.AblyRealtime({ useBinaryProtocol: false }), + binaryrealtime = helper.AblyRealtime({ useBinaryProtocol: true }), channelName = 'message_encoding', channelPath = '/channels/' + channelName + '/messages', channel = realtime.channels.get(channelName), diff --git a/test/realtime/event_emitter.test.js b/test/realtime/event_emitter.test.js index 36043e2b7d..4575594f21 100644 --- a/test/realtime/event_emitter.test.js +++ b/test/realtime/event_emitter.test.js @@ -28,7 +28,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { /* Note: realtime now sends an ATTACHED post-upgrade, which can race with * the DETACHED if the DETACH is only sent just after upgrade. Remove * bestTransport with 1.1 spec which has IDs in ATTACHs */ - var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), index, expectedConnectionEvents = ['connecting', 'connected', 'closing', 'closed'], expectedChannelEvents = ['attaching', 'attached', 'detaching', 'detached']; @@ -74,7 +74,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('emitCallsAllCallbacksIgnoringExceptions', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = false, eventEmitter = realtime.connection; @@ -99,7 +99,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('onceCalledOnlyOnce', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), onCallbackCalled = 0, onceCallbackCalled = 0, eventEmitter = realtime.connection; @@ -127,7 +127,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('onceCallbackDoesNotImpactOnCallback', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -153,7 +153,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('offRemovesAllMatchingListeners', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -182,7 +182,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('offRemovesAllListeners', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -211,7 +211,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('offRemovesAllMatchingEventListeners', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -240,7 +240,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('offRemovesAllMatchingEvents', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -276,7 +276,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { * for each previously registered event name */ it('offRemovesEmptyEventNameListeners', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection; var callback = function () {}; @@ -304,7 +304,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('arrayOfEvents', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -343,7 +343,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('arrayOfEventsWithOnce', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), callbackCalled = 0, eventEmitter = realtime.connection; @@ -370,7 +370,7 @@ 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.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection, firstCbCalled = false, secondCbCalled = false; @@ -397,7 +397,7 @@ 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.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection, onCbCalledTimes = 0, onceCbCalledTimes = 0, @@ -442,7 +442,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { if (typeof Promise !== 'undefined') { describe('event_emitter_promise', function () { it('whenState', function (done) { - var realtime = helper.AblyRealtimePromise({ internal: { promises: true } }); + var realtime = helper.AblyRealtime({ internal: { promises: true } }); var eventEmitter = realtime.connection; eventEmitter @@ -456,7 +456,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('once', function (done) { - var realtime = helper.AblyRealtimePromise({ internal: { promises: true } }); + var realtime = helper.AblyRealtime({ internal: { promises: true } }); var eventEmitter = realtime.connection; eventEmitter @@ -470,7 +470,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('anyEventsWithOnce', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), eventEmitter = realtime.connection; const p = eventEmitter.once(); @@ -483,7 +483,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { }); it('arrayOfEventsWithOnce', function (done) { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var 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 c8576e578d..6e2339434c 100644 --- a/test/realtime/failure.test.js +++ b/test/realtime/failure.test.js @@ -29,7 +29,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { var failure_test = function (transports) { return function (cb) { - var realtime = helper.AblyRealtimePromise({ key: 'this.is:wrong', transports: transports }); + var realtime = helper.AblyRealtime({ key: 'this.is:wrong', transports: transports }); realtime.connection.on('failed', function (connectionStateChange) { try { expect(realtime.connection.errorReason.code).to.equal(40400, 'wrong error reason code on connection.'); @@ -78,7 +78,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { var break_test = function (transports) { return function (cb) { - var realtime = helper.AblyRealtimePromise({ transports: transports }); + var realtime = helper.AblyRealtime({ transports: transports }); realtime.connection.once('connected', function () { realtime.connection.once('disconnected', function () { cb(null, realtime); @@ -117,7 +117,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var lifecycleTest = function (transports) { return function (cb) { var connectionEvents = []; - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ transports: transports, realtimeHost: 'invalid', restHost: 'invalid', @@ -189,7 +189,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async utils.arrForEach(availableTransports, function (transport) { it('disconnected_backoff_' + transport, function (done) { var disconnectedRetryTimeout = 150; - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ disconnectedRetryTimeout: disconnectedRetryTimeout, realtimeHost: 'invalid', restHost: 'invalid', @@ -220,7 +220,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) { - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); var failChan; var channelFailedCode = 90001; @@ -326,7 +326,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('attach_timeout', function (done) { - var realtime = helper.AblyRealtimePromise({ realtimeRequestTimeout: 2000, channelRetryTimeout: 1000 }), + var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000, channelRetryTimeout: 1000 }), channel = realtime.channels.get('failed_attach'), originalProcessMessage = channel.processMessage.bind(channel); @@ -362,7 +362,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async utils.arrForEach(availableTransports, function (transport) { it('channel_backoff_' + transport, function (done) { var channelRetryTimeout = 150; - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ channelRetryTimeout: channelRetryTimeout, transports: [transport], }), @@ -423,7 +423,7 @@ 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.AblyRealtimePromise({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channel = realtime.channels.get('nack_on_connection_failure'); async.series( @@ -508,7 +508,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async ); it('idle_transport_timeout', function (done) { - var realtime = helper.AblyRealtimePromise({ realtimeRequestTimeout: 2000 }), + var realtime = helper.AblyRealtime({ realtimeRequestTimeout: 2000 }), originalOnProtocolMessage; realtime.connection.connectionManager.on('transport.pending', function (transport) { @@ -546,7 +546,7 @@ 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.AblyRealtimePromise(utils.mixin({ fallbackHosts: ['echo.ably.io'] }, realtimeOpts)), + var realtime = helper.AblyRealtime(utils.mixin({ fallbackHosts: ['echo.ably.io'] }, realtimeOpts)), connection = realtime.connection, connectionManager = connection.connectionManager; @@ -586,7 +586,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var testMessage2 = { foo: 'bar', count: 2, status: 'active' }; try { - var sender_realtime = helper.AblyRealtimePromise(); + var sender_realtime = helper.AblyRealtime(); var sender_channel = sender_realtime.channels.get(testName); var messageReceived = false; diff --git a/test/realtime/history.test.js b/test/realtime/history.test.js index 73112e343f..a32ad2c72a 100644 --- a/test/realtime/history.test.js +++ b/test/realtime/history.test.js @@ -47,8 +47,8 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { }); it('history_until_attach', function (done) { - var rest = helper.AblyRestPromise(); - var realtime = helper.AblyRealtimePromise(); + var rest = helper.AblyRest(); + var realtime = helper.AblyRealtime(); var restChannel = rest.channels.get('persisted:history_until_attach'); /* first, send a number of events to this channel before attaching */ diff --git a/test/realtime/init.test.js b/test/realtime/init.test.js index e494f2708e..998a1c2623 100644 --- a/test/realtime/init.test.js +++ b/test/realtime/init.test.js @@ -29,7 +29,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('initbase0', function (done) { var realtime; try { - realtime = helper.AblyRealtimePromise({ transports: ['web_socket', 'xhr_streaming'] }); + realtime = helper.AblyRealtime({ transports: ['web_socket', 'xhr_streaming'] }); realtime.connection.on('connected', function () { /* check api version */ var transport = realtime.connection.connectionManager.activeProtocol.transport; @@ -73,7 +73,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('init_token_string', function (done) { try { /* first generate a token ... */ - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; whenPromiseSettles(rest.auth.requestToken(null, testKeyOpts), function (err, tokenDetails) { @@ -103,7 +103,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; - realtime = helper.AblyRealtimePromise({ key: keyStr, useTokenAuth: true }); + realtime = helper.AblyRealtime({ key: keyStr, useTokenAuth: true }); expect(realtime.options.key).to.equal(keyStr); expect(realtime.auth.method).to.equal('token'); expect(realtime.auth.clientId).to.equal(undefined); @@ -128,7 +128,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; - realtime = helper.AblyRealtimePromise({ + realtime = helper.AblyRealtime({ key: keyStr, useTokenAuth: true, defaultTokenParams: { clientId: '*', ttl: 123456 }, @@ -156,7 +156,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; - realtime = helper.AblyRealtimePromise({ + realtime = helper.AblyRealtime({ key: keyStr, useTokenAuth: true, defaultTokenParams: { clientId: 'test' }, @@ -182,7 +182,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { var realtime; try { var keyStr = helper.getTestApp().keys[0].keyStr; - realtime = helper.AblyRealtimePromise({ + realtime = helper.AblyRealtime({ key: keyStr, useTokenAuth: true, clientId: 'yes', @@ -235,7 +235,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { /* check changing the default timeouts */ it('init_timeouts', function (done) { try { - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ key: 'not_a.real:key', disconnectedRetryTimeout: 123, suspendedRetryTimeout: 456, @@ -268,7 +268,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { /* check changing the default fallback hosts and changing httpMaxRetryCount */ it('init_fallbacks', function (done) { try { - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ key: 'not_a.real:key', restHost: 'a', httpMaxRetryCount: 2, @@ -316,7 +316,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('node_transports', function (done) { var realtime; try { - realtime = helper.AblyRealtimePromise({ transports: helper.availableTransports }); + realtime = helper.AblyRealtime({ transports: helper.availableTransports }); expect(realtime.connection.connectionManager.baseTransport).to.equal('comet'); expect(realtime.connection.connectionManager.upgradeTransports).to.deep.equal(['web_socket']); closeAndFinish(done, realtime); @@ -331,7 +331,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('init_and_connection_details', function (done) { try { var keyStr = helper.getTestApp().keys[0].keyStr; - var realtime = helper.AblyRealtimePromise({ key: keyStr, useTokenAuth: true }); + var realtime = helper.AblyRealtime({ key: keyStr, useTokenAuth: true }); realtime.connection.connectionManager.once('transport.pending', function (state) { var transport = realtime.connection.connectionManager.pendingTransports[0], originalOnProtocolMessage = transport.onProtocolMessage; @@ -370,7 +370,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('init_fallbacks_once_connected', function (done) { - var realtime = helper.AblyRealtimePromise({ + var realtime = helper.AblyRealtime({ httpMaxRetryCount: 3, fallbackHosts: ['a', 'b', 'c'], }); @@ -390,8 +390,8 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('init_fallbacks_once_connected_2', function (done) { - var goodHost = helper.AblyRestPromise().options.realtimeHost; - var realtime = helper.AblyRealtimePromise({ + var goodHost = helper.AblyRest().options.realtimeHost; + var realtime = helper.AblyRealtime({ httpMaxRetryCount: 3, restHost: 'a', fallbackHosts: [goodHost, 'b', 'c'], diff --git a/test/realtime/message.test.js b/test/realtime/message.test.js index 623f1c0946..bcc4aa9128 100644 --- a/test/realtime/message.test.js +++ b/test/realtime/message.test.js @@ -39,8 +39,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('publishonce', function (done) { try { /* set up realtime */ - var realtime = helper.AblyRealtimePromise(); - var rest = helper.AblyRestPromise(); + var realtime = helper.AblyRealtime(); + var rest = helper.AblyRest(); /* connect and attach */ realtime.connection.on('connected', function () { @@ -80,7 +80,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async testOnAllTransports('publishfast', function (realtimeOpts) { return function (done) { try { - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); realtime.connection.once('connected', function () { var channel = realtime.channels.get('publishfast_' + String(Math.random()).substr(2)); whenPromiseSettles(channel.attach(), function (err) { @@ -144,8 +144,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return function (done) { var txRealtime, rxRealtime; try { - txRealtime = helper.AblyRealtimePromise(utils.mixin(realtimeOpts, { autoConnect: false })); - rxRealtime = helper.AblyRealtimePromise(); + txRealtime = helper.AblyRealtime(utils.mixin(realtimeOpts, { autoConnect: false })); + rxRealtime = helper.AblyRealtime(); var txChannel = txRealtime.channels.get('publishQueued_' + String(Math.random()).substr(2)); var rxChannel = rxRealtime.channels.get(txChannel.name); @@ -232,8 +232,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('publishEcho', function (done) { // set up two realtimes - var rtNoEcho = helper.AblyRealtimePromise({ echoMessages: false }), - rtEcho = helper.AblyRealtimePromise({ echoMessages: true }), + var rtNoEcho = helper.AblyRealtime({ echoMessages: false }), + rtEcho = helper.AblyRealtime({ echoMessages: true }), rtNoEchoChannel = rtNoEcho.channels.get('publishecho'), rtEchoChannel = rtEcho.channels.get('publishecho'), testMsg1 = 'Hello', @@ -323,8 +323,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { /* set up realtime */ - realtime = helper.AblyRealtimePromise(); - var rest = helper.AblyRestPromise(); + realtime = helper.AblyRealtime(); + var rest = helper.AblyRest(); /* connect and attach */ realtime.connection.on('connected', function () { @@ -429,8 +429,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { /* set up realtime */ - var realtime = helper.AblyRealtimePromise(); - var rest = helper.AblyRestPromise(); + var realtime = helper.AblyRealtime(); + var rest = helper.AblyRest(); /* connect and attach */ realtime.connection.on('connected', function () { @@ -483,8 +483,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { /* set up realtime */ - var realtime = helper.AblyRealtimePromise(); - var rest = helper.AblyRestPromise(); + var realtime = helper.AblyRealtime(); + var rest = helper.AblyRest(); /* connect and attach */ realtime.connection.on('connected', function () { @@ -565,8 +565,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('restpublish', function (done) { var count = 10; - var rest = helper.AblyRestPromise(); - var realtime = helper.AblyRealtimePromise(); + var rest = helper.AblyRest(); + var realtime = helper.AblyRealtime(); var messagesSent = []; var sendchannel = rest.channels.get('restpublish'); var recvchannel = realtime.channels.get('restpublish'); @@ -604,7 +604,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async --cbCount; checkFinish(); }; - var realtime = helper.AblyRealtimePromise(realtimeOpts); + var realtime = helper.AblyRealtime(realtimeOpts); var channel = realtime.channels.get('publish ' + JSON.stringify(realtimeOpts)); /* subscribe to event */ channel.subscribe( @@ -627,7 +627,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async and is implicitly added when published */ it('implicit_client_id_0', function (done) { var clientId = 'implicit_client_id_0', - realtime = helper.AblyRealtimePromise({ clientId: clientId }); + realtime = helper.AblyRealtime({ clientId: clientId }); realtime.connection.once('connected', function () { var transport = realtime.connection.connectionManager.activeProtocol.transport, @@ -666,7 +666,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('explicit_client_id_0', function (done) { var clientId = 'explicit_client_id_0', /* Use a fixed transport as intercepting transport.send */ - realtime = helper.AblyRealtimePromise({ clientId: clientId, transports: [helper.bestTransport] }); + realtime = helper.AblyRealtime({ clientId: clientId, transports: [helper.bestTransport] }); realtime.connection.once('connected', function () { var transport = realtime.connection.connectionManager.activeProtocol.transport, @@ -728,7 +728,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('explicit_client_id_1', function (done) { var clientId = 'explicit_client_id_1', invalidClientId = 'invalid', - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken({ clientId: clientId }), function (err, token) { if (err) { @@ -743,7 +743,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } /* Use a fixed transport as intercepting transport.send */ - var realtime = helper.AblyRealtimePromise({ token: token.token, transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtime({ token: token.token, transports: [helper.bestTransport] }), channel = realtime.channels.get('explicit_client_id_1'); // Publish before authentication to ensure the client library does not reject the message as the clientId is not known @@ -783,7 +783,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('subscribe_with_event_array', function (done) { - var realtime = helper.AblyRealtimePromise(), + var realtime = helper.AblyRealtime(), channel = realtime.channels.get('subscribe_with_event_array'); async.series( @@ -839,7 +839,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('subscribe_with_filter_object', function (done) { - const realtime = helper.AblyRealtimePromise(); + const realtime = helper.AblyRealtime(); const channel = realtime.channels.get('subscribe_with_filter_object'); function send(cb) { @@ -919,7 +919,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('unsubscribe_with_filter_object', function (done) { - const realtime = helper.AblyRealtimePromise(); + const realtime = helper.AblyRealtime(); const channel = realtime.channels.get('unsubscribe_with_filter_object'); function send(cb) { @@ -977,7 +977,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('extras_field', function (done) { - var realtime = helper.AblyRealtimePromise(), + var realtime = helper.AblyRealtime(), channel = realtime.channels.get('extras_field'), extras = { headers: { some: 'metadata' } }; @@ -1022,7 +1022,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async /* TO3l8; CD2C; RSL1i */ it('maxMessageSize', function (done) { - var realtime = helper.AblyRealtimePromise(), + var realtime = helper.AblyRealtime(), connectionManager = realtime.connection.connectionManager, channel = realtime.channels.get('maxMessageSize'); @@ -1056,7 +1056,7 @@ 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.AblyRealtimePromise({ maxMessageSize: 256, autoConnect: false }), + var realtime = helper.AblyRealtime({ maxMessageSize: 256, autoConnect: false }), channelOne = realtime.channels.get('bundlingOne'), channelTwo = realtime.channels.get('bundlingTwo'); @@ -1118,7 +1118,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('idempotentRealtimePublishing', function (done) { - var realtime = helper.AblyRealtimePromise(), + var realtime = helper.AblyRealtime(), channel = realtime.channels.get('idempotentRealtimePublishing'); whenPromiseSettles(channel.attach(), function (err) { @@ -1206,8 +1206,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async try { /* set up realtime */ - var realtime = helper.AblyRealtimePromise({ key: helper.getTestApp().keys[5].keyStr }); - var rest = helper.AblyRestPromise(); + var realtime = helper.AblyRealtime({ key: helper.getTestApp().keys[5].keyStr }); + var rest = helper.AblyRest(); realtime.connection.on('connected', function () { var rtFilteredChannel = realtime.channels.getDerived('chan', filterOption); diff --git a/test/realtime/presence.test.js b/test/realtime/presence.test.js index 4324c8f333..3ee5e48846 100644 --- a/test/realtime/presence.test.js +++ b/test/realtime/presence.test.js @@ -29,7 +29,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var createListenerChannel = function (channelName, callback) { var channel, realtime; try { - realtime = helper.AblyRealtimePromise(); + realtime = helper.AblyRealtime(); realtime.connection.on('connected', function () { channel = realtime.channels.get(channelName); whenPromiseSettles(channel.attach(), function (err) { @@ -101,7 +101,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } // Create authTokens associated with specific clientIds try { - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); whenPromiseSettles(rest.auth.requestToken({ clientId: testClientId }), function (err, tokenDetails) { if (err) { done(err); @@ -143,7 +143,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelName = 'attachAndEnter'; var attachAndEnter = function (cb) { /* set up authenticated connection */ - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); @@ -169,7 +169,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterWithoutAttach', function (done) { var channelName = 'enterWithoutAttach'; var enterWithoutAttach = function (cb) { - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); @@ -189,7 +189,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterWithoutConnect', function (done) { var channelName = 'enterWithoutConnect'; var enterWithoutConnect = function (cb) { - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var clientChannel = clientRealtime.channels.get(channelName); whenPromiseSettles(clientChannel.presence.enter('Test client data (enterWithoutConnect)'), function (err) { cb(err, clientRealtime); @@ -219,7 +219,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async return; } - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); listenerFor('enter', testClientId)(presenceChannel, function () { if (!raceFinished) { @@ -271,7 +271,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelName = 'enterWithCallback'; var enterWithCallback = function (cb) { /* set up authenticated connection */ - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); @@ -297,7 +297,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterWithNothing', function (done) { var channelName = 'enterWithNothing'; var enterWithNothing = function (cb) { - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); @@ -322,7 +322,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterWithData', function (done) { var channelName = 'enterWithData'; var enterWithData = function (cb) { - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); @@ -346,7 +346,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async * has valid action string */ it('presenceMessageAction', function (done) { - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var channelName = 'presenceMessageAction'; var clientChannel = clientRealtime.channels.get(channelName); var presence = clientChannel.presence; @@ -386,7 +386,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channel.presence.subscribe(presenceHandler); }; var enterDetachEnter = function (cb) { - var clientRealtime = helper.AblyRealtimePromise({ + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken, transports: [helper.bestTransport], @@ -421,7 +421,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterInvalid', function (done) { var clientRealtime; try { - clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var clientChannel = clientRealtime.channels.get(''); clientRealtime.connection.once('connected', function () { whenPromiseSettles(clientChannel.presence.enter('clientId'), function (err) { @@ -450,7 +450,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceEnterAndLeave', function (done) { var channelName = 'enterAndLeave'; var enterAndLeave = function (cb) { - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); @@ -499,7 +499,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channel.presence.subscribe(presenceHandler); }; var enterUpdate = function (cb) { - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { var clientChannel = clientRealtime.channels.get(channelName); whenPromiseSettles(clientChannel.attach(), function (err) { @@ -552,7 +552,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channel.presence.subscribe(presenceHandler); }; var enterGet = function (cb) { - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); @@ -577,7 +577,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('presenceSubscribeUnattached', function (done) { var channelName = 'subscribeUnattached'; - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var clientRealtime2; clientRealtime.connection.on('connected', function () { var clientChannel = clientRealtime.channels.get(channelName); @@ -591,7 +591,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async closeAndFinish(done, [clientRealtime, clientRealtime2]); }); /* Technically a race, but c2 connecting and attaching should take longer than c1 attaching */ - clientRealtime2 = helper.AblyRealtimePromise({ clientId: testClientId2, tokenDetails: authToken2 }); + clientRealtime2 = helper.AblyRealtime({ clientId: testClientId2, tokenDetails: authToken2 }); clientRealtime2.connection.on('connected', function () { var clientChannel2 = clientRealtime2.channels.get(channelName); clientChannel2.presence.enter('data'); @@ -606,7 +606,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presenceGetUnattached', function (done) { var channelName = 'getUnattached'; var testData = 'some data'; - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); @@ -615,7 +615,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async closeAndFinish(done, clientRealtime, err); return; } - var clientRealtime2 = helper.AblyRealtimePromise({ clientId: testClientId2, tokenDetails: authToken2 }); + var clientRealtime2 = helper.AblyRealtime({ clientId: testClientId2, tokenDetails: authToken2 }); clientRealtime2.connection.on('connected', function () { var clientChannel2 = clientRealtime2.channels.get(channelName); /* GET without attaching */ @@ -669,7 +669,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channel.presence.subscribe(presenceHandler); }; var enterLeaveGet = function (cb) { - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); @@ -726,7 +726,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }; try { /* set up authenticated connection */ - clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel = clientRealtime.channels.get(channelName); @@ -775,7 +775,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var channelName = 'secondConnection'; try { /* set up authenticated connection */ - clientRealtime1 = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + clientRealtime1 = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime1.connection.on('connected', function () { /* get channel, attach, and enter */ var clientChannel1 = clientRealtime1.channels.get(channelName); @@ -804,7 +804,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } /* now set up second connection and attach */ /* set up authenticated connection */ - clientRealtime2 = helper.AblyRealtimePromise({ clientId: testClientId2, tokenDetails: authToken2 }); + clientRealtime2 = helper.AblyRealtime({ clientId: testClientId2, tokenDetails: authToken2 }); clientRealtime2.connection.on('connected', function () { /* get channel, attach */ var clientChannel2 = clientRealtime2.channels.get(channelName); @@ -859,7 +859,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async [ function (cb1) { var data = 'Test client data (member0-1)'; - clientRealtime1 = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + clientRealtime1 = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); clientRealtime1.connection.on('connected', function () { /* get channel, attach, and enter */ clientChannel1 = clientRealtime1.channels.get(channelName); @@ -881,7 +881,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }, function (cb2) { var data = 'Test client data (member0-2)'; - clientRealtime2 = helper.AblyRealtimePromise({ clientId: testClientId2, tokenDetails: authToken2 }); + clientRealtime2 = helper.AblyRealtime({ clientId: testClientId2, tokenDetails: authToken2 }); clientRealtime2.connection.on('connected', function () { /* get channel, attach */ clientChannel2 = clientRealtime2.channels.get(channelName); @@ -1025,7 +1025,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async channel.presence.subscribe(presenceHandler); }; var enterAfterClose = function (cb) { - var clientRealtime = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); + var clientRealtime = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); var clientChannel = clientRealtime.channels.get(channelName); clientRealtime.connection.once('connected', function () { /* get channel and enter (should automatically attach) */ @@ -1059,7 +1059,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var clientRealtime; var channelName = 'enterClosed'; try { - clientRealtime = helper.AblyRealtimePromise(); + clientRealtime = helper.AblyRealtime(); var clientChannel = clientRealtime.channels.get(channelName); clientRealtime.connection.on('connected', function () { clientRealtime.close(); @@ -1085,7 +1085,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('presenceClientIdIsImplicit', function (done) { var clientId = 'implicitClient', - client = helper.AblyRealtimePromise({ clientId: clientId }); + client = helper.AblyRealtime({ clientId: clientId }); var channel = client.channels.get('presenceClientIdIsImplicit'), presence = channel.presence; @@ -1135,8 +1135,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async transports: [helper.bestTransport], }; - var realtimeBin = helper.AblyRealtimePromise(utils.mixin(options, { useBinaryProtocol: true })); - var realtimeJson = helper.AblyRealtimePromise(utils.mixin(options, { useBinaryProtocol: false })); + var realtimeBin = helper.AblyRealtime(utils.mixin(options, { useBinaryProtocol: true })); + var realtimeJson = helper.AblyRealtime(utils.mixin(options, { useBinaryProtocol: false })); var runTest = function (realtime, callback) { realtime.connection.connectionManager.once('transport.active', function (transport) { @@ -1202,7 +1202,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }; var enterInheritedClientId = function (cb) { - var realtime = helper.AblyRealtimePromise({ authCallback: authCallback }); + var realtime = helper.AblyRealtime({ authCallback: authCallback }); var channel = realtime.channels.get(channelName); realtime.connection.on('connected', function () { try { @@ -1235,7 +1235,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async done(err); return; } - var realtime = helper.AblyRealtimePromise({ token: tokenDetails.token, autoConnect: false }); + var realtime = helper.AblyRealtime({ token: tokenDetails.token, autoConnect: false }); var channel = realtime.channels.get(channelName); try { expect(realtime.auth.clientId).to.equal(undefined, 'no clientId when entering'); @@ -1266,8 +1266,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async */ it('presence_refresh_on_detach', function (done) { var channelName = 'presence_refresh_on_detach'; - var realtime = helper.AblyRealtimePromise(); - var observer = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); + var observer = helper.AblyRealtime(); var realtimeChannel = realtime.channels.get(channelName); var observerChannel = observer.channels.get(channelName); @@ -1380,8 +1380,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presence_detach_during_sync', function (done) { var channelName = 'presence_detach_during_sync'; - var enterer = helper.AblyRealtimePromise({ clientId: testClientId, tokenDetails: authToken }); - var detacher = helper.AblyRealtimePromise(); + var enterer = helper.AblyRealtime({ clientId: testClientId, tokenDetails: authToken }); + var detacher = helper.AblyRealtime(); var entererChannel = enterer.channels.get(channelName); var detacherChannel = detacher.channels.get(channelName); @@ -1436,7 +1436,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async * presence set */ it('presence_auto_reenter', function (done) { var channelName = 'presence_auto_reenter'; - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); var channel = realtime.channels.get(channelName); async.series( @@ -1561,7 +1561,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); }, function (cb) { - realtime = helper.AblyRealtimePromise({ tokenDetails: token }); + realtime = helper.AblyRealtime({ tokenDetails: token }); channel = realtime.channels.get(channelName); realtime.connection.once('connected', function () { cb(); @@ -1640,7 +1640,7 @@ 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) { /* single transport to avoid upgrade stalling due to the stubbed attachImpl */ - var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), channel = realtime.channels.get('multiple_pending'), originalAttachImpl = channel.attachImpl; @@ -1692,10 +1692,10 @@ 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.AblyRealtimePromise({ transports: helper.availableTransports }), + var realtime = helper.AblyRealtime({ transports: helper.availableTransports }), continuousClientId = 'continuous', goneClientId = 'gone', - continuousRealtime = helper.AblyRealtimePromise({ clientId: continuousClientId }), + continuousRealtime = helper.AblyRealtime({ clientId: continuousClientId }), channelName = 'leave_published_for_member_missing_from_sync', channel = realtime.channels.get(channelName), continuousChannel = continuousRealtime.channels.get(channelName); @@ -1807,7 +1807,7 @@ 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.AblyRealtimePromise(), + var realtime = helper.AblyRealtime(), channelName = 'leave_published_for_members_on_presenceless_attached', channel = realtime.channels.get(channelName), fakeClientId = 'faker'; @@ -1899,9 +1899,9 @@ 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.AblyRealtimePromise({ clientId: 'main', logLevel: 4 }), - continuousRealtime = helper.AblyRealtimePromise({ clientId: 'continuous', logLevel: 4 }), - leavesRealtime = helper.AblyRealtimePromise({ clientId: 'leaves', logLevel: 4 }), + var mainRealtime = helper.AblyRealtime({ clientId: 'main', logLevel: 4 }), + continuousRealtime = helper.AblyRealtime({ clientId: 'continuous', logLevel: 4 }), + leavesRealtime = helper.AblyRealtime({ clientId: 'leaves', logLevel: 4 }), channelName = 'suspended_preserves_presence', mainChannel = mainRealtime.channels.get(channelName); @@ -2037,7 +2037,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async * comparisons. */ it('presence_many_updates', function (done) { - var client = helper.AblyRealtimePromise({ clientId: testClientId }); + var client = helper.AblyRealtime({ clientId: testClientId }); var channel = client.channels.get('presence_many_updates'), presence = channel.presence, diff --git a/test/realtime/reauth.test.js b/test/realtime/reauth.test.js index 87b44ab77d..137d35a9b2 100644 --- a/test/realtime/reauth.test.js +++ b/test/realtime/reauth.test.js @@ -17,7 +17,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { done(err); return; } - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); done(); }); }); @@ -44,7 +44,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { function connectWithToken() { return function (state, callback) { - var realtime = helper.AblyRealtimePromise(mixin({ token: state.token }, state.realtimeOpts)); + var realtime = helper.AblyRealtime(mixin({ token: state.token }, state.realtimeOpts)); realtime.connection.once('connected', function () { callback(null, mixin(state, { realtime: realtime })); }); diff --git a/test/realtime/resume.test.js b/test/realtime/resume.test.js index 1c0e96ce32..26104d9aa2 100644 --- a/test/realtime/resume.test.js +++ b/test/realtime/resume.test.js @@ -44,8 +44,8 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { function resume_inactive(done, channelName, txOpts, rxOpts) { var count = 5; - var txRest = helper.AblyRestPromise(mixin(txOpts)); - var rxRealtime = helper.AblyRealtimePromise(mixin(rxOpts)); + var txRest = helper.AblyRest(mixin(txOpts)); + var rxRealtime = helper.AblyRealtime(mixin(rxOpts)); var rxChannel = rxRealtime.channels.get(channelName); var txChannel = txRest.channels.get(channelName); @@ -155,8 +155,8 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { function resume_active(done, channelName, txOpts, rxOpts) { var count = 5; - var txRest = helper.AblyRestPromise(mixin(txOpts)); - var rxRealtime = helper.AblyRealtimePromise(mixin(rxOpts)); + var txRest = helper.AblyRest(mixin(txOpts)); + var rxRealtime = helper.AblyRealtime(mixin(rxOpts)); var rxChannel = rxRealtime.channels.get(channelName); var txChannel = txRest.channels.get(channelName); @@ -276,7 +276,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { 'resume_lost_continuity', function (realtimeOpts) { return function (done) { - var realtime = helper.AblyRealtimePromise(realtimeOpts), + var realtime = helper.AblyRealtime(realtimeOpts), connection = realtime.connection, attachedChannelName = 'resume_lost_continuity_attached', suspendedChannelName = 'resume_lost_continuity_suspended', @@ -342,7 +342,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { 'resume_token_error', function (realtimeOpts) { return function (done) { - var realtime = helper.AblyRealtimePromise(mixin(realtimeOpts, { useTokenAuth: true })), + var realtime = helper.AblyRealtime(mixin(realtimeOpts, { useTokenAuth: true })), badtoken, connection = realtime.connection; @@ -395,7 +395,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { 'resume_fatal_error', function (realtimeOpts) { return function (done) { - var realtime = helper.AblyRealtimePromise(realtimeOpts), + var realtime = helper.AblyRealtime(realtimeOpts), connection = realtime.connection; async.series( @@ -445,7 +445,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { * TODO: enable once realtime supports this */ it('channel_resumed_flag', function (done) { - var realtime = helper.AblyRealtimePromise({ transports: [helper.bestTransport] }), + var realtime = helper.AblyRealtime({ transports: [helper.bestTransport] }), realtimeTwo, recoveryKey, connection = realtime.connection, @@ -476,7 +476,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { helper.becomeSuspended(realtime, cb); }, function (cb) { - realtimeTwo = helper.AblyRealtimePromise({ recover: recoveryKey }); + realtimeTwo = helper.AblyRealtime({ recover: recoveryKey }); realtimeTwo.connection.once('connected', function (stateChange) { if (stateChange.reason) { cb(stateChange.reason); @@ -509,7 +509,7 @@ 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.AblyRealtimePromise(), + var realtime = helper.AblyRealtime(), connection = realtime.connection, channelName = 'no_resume_once_suspended'; @@ -548,7 +548,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { */ it('no_resume_last_activity', function (done) { /* Specify a best transport so that upgrade activity doesn't reset the last activity timer */ - var realtime = helper.AblyRealtimePromise({ transports: [bestTransport] }), + var realtime = helper.AblyRealtime({ transports: [bestTransport] }), connection = realtime.connection, connectionManager = connection.connectionManager; @@ -574,11 +574,11 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { var testName = 'resume_rewind_1'; var testMessage = { foo: 'bar', count: 1, status: 'active' }; try { - var sender_realtime = helper.AblyRealtimePromise(); + var sender_realtime = helper.AblyRealtime(); var sender_channel = sender_realtime.channels.get(testName); sender_channel.subscribe(function (message) { - var receiver_realtime = helper.AblyRealtimePromise(); + var receiver_realtime = helper.AblyRealtime(); var receiver_channel = receiver_realtime.channels.get(testName, { params: { rewind: 1 } }); receiver_channel.subscribe(function (message) { @@ -592,7 +592,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { return; } - var resumed_receiver_realtime = helper.AblyRealtimePromise(); + var resumed_receiver_realtime = helper.AblyRealtime(); var connectionManager = resumed_receiver_realtime.connection.connectionManager; var sendOrig = connectionManager.send; @@ -630,8 +630,8 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { it('recover multiple channels', function (done) { const NUM_MSGS = 5; - const txRest = helper.AblyRestPromise(); - const rxRealtime = helper.AblyRealtimePromise( + const txRest = helper.AblyRest(); + const rxRealtime = helper.AblyRealtime( { transports: [helper.bestTransport], }, @@ -739,7 +739,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { return; } - rxRealtimeRecover = helper.AblyRealtimePromise({ recover: recoveryKey }); + rxRealtimeRecover = helper.AblyRealtime({ recover: recoveryKey }); rxRecoverChannels = channelNames.map((name) => rxRealtimeRecover.channels.get(name)); subscribeRecoveredMessages(function (err) { diff --git a/test/realtime/sync.test.js b/test/realtime/sync.test.js index 2359fd830e..3c306d9bcc 100644 --- a/test/realtime/sync.test.js +++ b/test/realtime/sync.test.js @@ -44,7 +44,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async * different presence set */ it('sync_existing_set', async function () { - var realtime = helper.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'syncexistingset', channel = realtime.channels.get(channelName); @@ -164,7 +164,7 @@ 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.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_member_arrives_in_middle', channel = realtime.channels.get(channelName); @@ -266,7 +266,7 @@ 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.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_member_arrives_normally_after_came_in_sync', channel = realtime.channels.get(channelName); @@ -349,7 +349,7 @@ 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.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_member_arrives_normally_before_comes_in_sync', channel = realtime.channels.get(channelName); @@ -433,7 +433,7 @@ 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.AblyRealtimePromise({ autoConnect: false }), + var realtime = helper.AblyRealtime({ autoConnect: false }), channelName = 'sync_ordering', channel = realtime.channels.get(channelName); @@ -589,8 +589,8 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('presence_sync_interruptus', function (done) { var channelName = 'presence_sync_interruptus'; var interrupterClientId = 'dark_horse'; - var enterer = helper.AblyRealtimePromise(); - var syncer = helper.AblyRealtimePromise(); + var enterer = helper.AblyRealtime(); + var syncer = helper.AblyRealtime(); var entererChannel = enterer.channels.get(channelName); var syncerChannel = syncer.channels.get(channelName); diff --git a/test/realtime/upgrade.test.js b/test/realtime/upgrade.test.js index 674035ad47..3ae14f839c 100644 --- a/test/realtime/upgrade.test.js +++ b/test/realtime/upgrade.test.js @@ -30,7 +30,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai done(err); return; } - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); done(); }); }); @@ -43,7 +43,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('publishpreupgrade', function (done) { var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtimePromise(transportOpts); + var realtime = helper.AblyRealtime(transportOpts); /* connect and attach */ realtime.connection.on('connected', function () { //console.log('publishpreupgrade: connected'); @@ -87,7 +87,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('publishpostupgrade0', function (done) { var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtimePromise(transportOpts); + var realtime = helper.AblyRealtime(transportOpts); /* subscribe to event */ var rtChannel = realtime.channels.get('publishpostupgrade0'); @@ -145,7 +145,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('publishpostupgrade1', function (done) { var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtimePromise(transportOpts); + var realtime = helper.AblyRealtime(transportOpts); /* subscribe to event */ var rtChannel = realtime.channels.get('publishpostupgrade1'); @@ -220,7 +220,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai checkFinish(); }; var transportOpts = { useBinaryProtocol: false, transports: helper.availableTransports }; - var realtime = helper.AblyRealtimePromise(transportOpts); + var realtime = helper.AblyRealtime(transportOpts); var channel = realtime.channels.get('upgradepublish0'); /* subscribe to event */ channel.subscribe( @@ -254,7 +254,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai checkFinish(); }; var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; - var realtime = helper.AblyRealtimePromise(transportOpts); + var realtime = helper.AblyRealtime(transportOpts); var channel = realtime.channels.get('upgradepublish1'); /* subscribe to event */ channel.subscribe( @@ -279,7 +279,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; var cometDeactivated = false; try { - var realtime = helper.AblyRealtimePromise(transportOpts); + var realtime = helper.AblyRealtime(transportOpts); /* check that we see the transport we're interested in get activated, * and that we see the comet transport deactivated */ var failTimer = setTimeout(function () { @@ -321,7 +321,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('upgradeheartbeat0', function (done) { var transportOpts = { useBinaryProtocol: false, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtimePromise(transportOpts); + var realtime = helper.AblyRealtime(transportOpts); /* when we see the transport we're interested in get activated, * listen for the heartbeat event */ @@ -354,7 +354,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('upgradeheartbeat1', function (done) { var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtimePromise(transportOpts); + var realtime = helper.AblyRealtime(transportOpts); /* when we see the transport we're interested in get activated, * listen for the heartbeat event */ @@ -387,7 +387,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('upgradeheartbeat2', function (done) { var transportOpts = { useBinaryProtocol: false, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtimePromise(transportOpts); + var realtime = helper.AblyRealtime(transportOpts); /* when we see the transport we're interested in get activated, * listen for the heartbeat event */ @@ -433,7 +433,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai it('upgradeheartbeat3', function (done) { var transportOpts = { useBinaryProtocol: true, transports: helper.availableTransports }; try { - var realtime = helper.AblyRealtimePromise(transportOpts); + var realtime = helper.AblyRealtime(transportOpts); /* when we see the transport we're interested in get activated, * listen for the heartbeat event */ @@ -480,7 +480,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai try { /* on base transport active */ - realtime = helper.AblyRealtimePromise({ transports: helper.availableTransports }); + realtime = helper.AblyRealtime({ transports: helper.availableTransports }); realtime.connection.connectionManager.once('transport.active', function (transport) { expect( transport.toString().indexOf('/comet/') > -1, @@ -535,7 +535,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai * seamlessly transferred to the websocket transport and published there */ it('message_timeout_stalling_upgrade', function (done) { - var realtime = helper.AblyRealtimePromise({ transports: helper.availableTransports, httpRequestTimeout: 3000 }), + var realtime = helper.AblyRealtime({ transports: helper.availableTransports, httpRequestTimeout: 3000 }), channel = realtime.channels.get('timeout1'), connectionManager = realtime.connection.connectionManager; @@ -581,7 +581,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai * and subsequent connections do not upgrade */ it('persist_transport_prefs', function (done) { - var realtime = helper.AblyRealtimePromise({ transports: helper.availableTransports }), + var realtime = helper.AblyRealtime({ transports: helper.availableTransports }), connection = realtime.connection, connectionManager = connection.connectionManager; @@ -643,7 +643,7 @@ define(['shared_helper', 'async', 'chai', 'ably'], function (helper, async, chai * Check that upgrades succeed even if the original transport dies before the sync */ it('upgrade_original_transport_dies', function (done) { - var realtime = helper.AblyRealtimePromise({ transports: helper.availableTransports }), + var realtime = helper.AblyRealtime({ transports: helper.availableTransports }), connection = realtime.connection, connectionManager = connection.connectionManager; diff --git a/test/rest/auth.test.js b/test/rest/auth.test.js index e1a9825be1..c1aed009bd 100644 --- a/test/rest/auth.test.js +++ b/test/rest/auth.test.js @@ -12,7 +12,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as before(function (done) { helper.setupApp(function () { - rest = helper.AblyRestPromise({ queryTime: true }); + rest = helper.AblyRest({ queryTime: true }); rest .time() .then(function (time) { @@ -46,7 +46,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as it('Generate token and init library with it', async function () { var tokenDetails = await rest.auth.requestToken(); expect(tokenDetails.token, 'Verify token value').to.be.ok; - helper.AblyRestPromise({ token: tokenDetails.token }); + helper.AblyRest({ token: tokenDetails.token }); }); it('Token generation with explicit timestamp', async function () { @@ -179,7 +179,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as }); it('Token generation with defaultTokenParams set and no tokenParams passed in', async function () { - var rest1 = helper.AblyRestPromise({ defaultTokenParams: { ttl: 123, clientId: 'foo' } }); + var rest1 = helper.AblyRest({ defaultTokenParams: { ttl: 123, clientId: 'foo' } }); var tokenDetails = await rest1.auth.requestToken(); expect(tokenDetails.token, 'Verify token value').to.be.ok; expect(tokenDetails.clientId).to.equal('foo', 'Verify client id from defaultTokenParams used'); @@ -187,7 +187,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 () { - var rest1 = helper.AblyRestPromise({ defaultTokenParams: { ttl: 123, clientId: 'foo' } }); + var rest1 = helper.AblyRest({ defaultTokenParams: { ttl: 123, clientId: 'foo' } }); var tokenDetails = await rest1.auth.requestToken({ clientId: 'bar' }, null); expect(tokenDetails.clientId).to.equal( 'bar', @@ -289,10 +289,10 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var authParams = utils.mixin(keys, params); var authUrl = echoServer + '/createJWT' + utils.toQueryString(authParams); - var restJWTRequester = helper.AblyRestPromise({ authUrl: authUrl }); + var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); var tokenDetails = await restJWTRequester.auth.requestToken(); - var restClient = helper.AblyRestPromise({ token: tokenDetails.token }); + var restClient = helper.AblyRest({ token: tokenDetails.token }); await restClient.stats(); }); } @@ -315,10 +315,10 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as it('JWT request with invalid key', async function () { var keys = { keyName: 'invalid.invalid', keySecret: 'invalidinvalid' }; var authUrl = echoServer + '/createJWT' + utils.toQueryString(keys); - var restJWTRequester = helper.AblyRestPromise({ authUrl: authUrl }); + var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); var tokenDetails = await restJWTRequester.auth.requestToken(); - var restClient = helper.AblyRestPromise({ token: tokenDetails.token }); + var restClient = helper.AblyRest({ token: tokenDetails.token }); try { var stats = await restClient.stats(); } catch (err) { @@ -336,7 +336,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as var currentKey = helper.getTestApp().keys[0]; var keys = { keyName: currentKey.keyName, keySecret: currentKey.keySecret }; var authUrl = echoServer + '/createJWT' + utils.toQueryString(keys); - var restJWTRequester = helper.AblyRestPromise({ authUrl: authUrl }); + var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); var authCallback = function (tokenParams, callback) { restJWTRequester.auth.requestToken().then(function (tokenDetails) { @@ -344,7 +344,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as }); }; - var restClient = helper.AblyRestPromise({ authCallback: authCallback }); + var restClient = helper.AblyRest({ authCallback: authCallback }); var stats = await restClient.stats(); }); @@ -354,7 +354,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as it('Rest JWT with authCallback and invalid keys', async function () { var keys = { keyName: 'invalid.invalid', keySecret: 'invalidinvalid' }; var authUrl = echoServer + '/createJWT' + utils.toQueryString(keys); - var restJWTRequester = helper.AblyRestPromise({ authUrl: authUrl }); + var restJWTRequester = helper.AblyRest({ authUrl: authUrl }); var authCallback = function (tokenParams, callback) { restJWTRequester.auth.requestToken().then(function (tokenDetails) { @@ -362,7 +362,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as }); }; - var restClient = helper.AblyRestPromise({ authCallback: authCallback }); + var restClient = helper.AblyRest({ authCallback: authCallback }); try { await restClient.stats(); } catch (err) { @@ -383,7 +383,7 @@ define(['chai', 'shared_helper', 'async', 'globals'], function (chai, helper, as } /* Example client-side using the token */ - var restClient = helper.AblyRestPromise({ authCallback: authCallback }); + var restClient = helper.AblyRest({ authCallback: authCallback }); var channel = restClient.channels.get('auth_concurrent'); await Promise.all([channel.history(), channel.history()]); diff --git a/test/rest/capability.test.js b/test/rest/capability.test.js index 0c88b94bfc..6684cce8b4 100644 --- a/test/rest/capability.test.js +++ b/test/rest/capability.test.js @@ -20,7 +20,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { before(function (done) { helper.setupApp(function () { - rest = helper.AblyRestPromise({ queryTime: true }); + rest = helper.AblyRest({ queryTime: true }); testApp = helper.getTestApp(); rest .time() diff --git a/test/rest/fallbacks.test.js b/test/rest/fallbacks.test.js index df716ecede..209b519291 100644 --- a/test/rest/fallbacks.test.js +++ b/test/rest/fallbacks.test.js @@ -14,14 +14,14 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { done(err); return; } - goodHost = helper.AblyRestPromise().options.restHost; + goodHost = helper.AblyRest().options.restHost; done(); }); }); /* RSC15f */ it('Store working fallback', async function () { - var rest = helper.AblyRestPromise({ + var rest = helper.AblyRest({ restHost: helper.unroutableHost, fallbackHosts: [goodHost], httpRequestTimeout: 3000, diff --git a/test/rest/history.test.js b/test/rest/history.test.js index 98eab3e5ab..34b7778445 100644 --- a/test/rest/history.test.js +++ b/test/rest/history.test.js @@ -22,7 +22,7 @@ define(['shared_helper', 'async', 'chai'], function (helper, async, chai) { before(function (done) { helper.setupApp(function () { - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); done(); }); }); diff --git a/test/rest/http.test.js b/test/rest/http.test.js index ff363d3b19..315f751551 100644 --- a/test/rest/http.test.js +++ b/test/rest/http.test.js @@ -9,7 +9,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { this.timeout(60 * 1000); before(function (done) { helper.setupApp(function () { - rest = helper.AblyRestPromise({ + rest = helper.AblyRest({ agents: { 'custom-agent': '0.1.2', }, diff --git a/test/rest/init.test.js b/test/rest/init.test.js index 11f9b5a11d..f4debf54f4 100644 --- a/test/rest/init.test.js +++ b/test/rest/init.test.js @@ -25,7 +25,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { it('Init with token string', async function () { /* first generate a token ... */ - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); var testKeyOpts = { key: helper.getTestApp().keys[1].keyStr }; var tokenDetails = await rest.auth.requestToken(null, testKeyOpts); @@ -36,30 +36,30 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) { }); it('Init with tls: false', function () { - var rest = helper.AblyRestPromise({ tls: false, port: 123, tlsPort: 456 }); + 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 () { - var rest = helper.AblyRestPromise({ tls: true, port: 123, tlsPort: 456 }); + 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 () { - var rest = helper.AblyRestPromise({ port: 123, tlsPort: 456 }); + 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 () { expect(function () { - var rest = helper.AblyRestPromise({ clientId: '*' }); + var rest = helper.AblyRest({ clientId: '*' }); }, 'Check can’t init library with a wildcard clientId').to.throw; expect(function () { - var rest = helper.AblyRestPromise({ clientId: 123 }); + var rest = helper.AblyRest({ clientId: 123 }); }, 'Check can’t init library with a numerical clientId').to.throw; expect(function () { - var rest = helper.AblyRestPromise({ clientId: false }); + var rest = helper.AblyRest({ clientId: false }); }, 'Check can’t init library with a boolean clientId').to.throw; }); diff --git a/test/rest/message.test.js b/test/rest/message.test.js index bb62a52791..389e0b7d74 100644 --- a/test/rest/message.test.js +++ b/test/rest/message.test.js @@ -20,7 +20,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async and is implicitly added when published */ it('Should implicitly send clientId when authenticated with clientId', async function () { var clientId = 'implicit_client_id_0', - rest = helper.AblyRestPromise({ clientId: clientId, useBinaryProtocol: false }), + rest = helper.AblyRest({ clientId: clientId, useBinaryProtocol: false }), channel = rest.channels.get('rest_implicit_client_id_0'); var originalPublish = channel._publish; @@ -42,7 +42,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async and ensure it is published */ it('Should publish clientId when provided explicitly in message', async function () { var clientId = 'explicit_client_id_0', - rest = helper.AblyRestPromise({ clientId: clientId, useBinaryProtocol: false }), + rest = helper.AblyRest({ clientId: clientId, useBinaryProtocol: false }), channel = rest.channels.get('rest_explicit_client_id_0'); var originalPublish = channel._publish; @@ -68,11 +68,11 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async var clientId = 'explicit_client_id_0', invalidClientId = 'invalid'; - var token = await helper.AblyRestPromise().auth.requestToken({ clientId: clientId }); + var token = await helper.AblyRest().auth.requestToken({ clientId: clientId }); expect(token.clientId === clientId, 'client ID is present in the Token').to.be.ok; // REST client uses a token string so is unaware of the clientId so cannot reject before communicating with Ably - var rest = helper.AblyRestPromise({ token: token.token, useBinaryProtocol: false }), + var rest = helper.AblyRest({ token: token.token, useBinaryProtocol: false }), channel = rest.channels.get('rest_explicit_client_id_1'); var originalPublish = channel._publish; @@ -99,7 +99,7 @@ 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.AblyRestPromise({ internal: { maxMessageSize: 64 } }), + var realtime = helper.AblyRest({ internal: { maxMessageSize: 64 } }), channel = realtime.channels.get('maxMessageSize'); try { @@ -114,7 +114,7 @@ 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.AblyRestPromise({ idempotentRestPublishing: false, useBinaryProtocol: false }), + var rest = helper.AblyRest({ idempotentRestPublishing: false, useBinaryProtocol: false }), channel = rest.channels.get('idempotent_rest_publishing'), message = { name: 'test', id: 'idempotent-msg-id:0' }; @@ -128,11 +128,11 @@ 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.AblyRestPromise(), + var 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 */ - rest = helper.AblyRestPromise({ + rest = helper.AblyRest({ idempotentRestPublishing: true, useBinaryProtocol: false, fallbackHosts: [host, host, host], @@ -180,7 +180,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('Rest publish params', async function () { - var rest = helper.AblyRestPromise(), + var 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 7e7f519084..1c9640631f 100644 --- a/test/rest/presence.test.js +++ b/test/rest/presence.test.js @@ -25,7 +25,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async before(function (done) { helper.setupApp(function () { - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); cipherConfig = helper.getTestApp().cipherConfig; done(); }); diff --git a/test/rest/push.test.js b/test/rest/push.test.js index 5bfe1eb4e0..9d251ffe68 100644 --- a/test/rest/push.test.js +++ b/test/rest/push.test.js @@ -51,13 +51,13 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } subsByChannel[sub.channel].push(sub); - var rest = helper.AblyRestPromise({ clientId: sub.clientId }); + var rest = helper.AblyRest({ clientId: sub.clientId }); subscribes.push(() => rest.push.admin.channelSubscriptions.save(sub)); deletes.push(() => rest.push.admin.channelSubscriptions.remove(sub)); })(i); } - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); await Promise.all(subscribes.map((sub) => sub())); @@ -72,7 +72,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async it('Publish', async function () { try { - var realtime = helper.AblyRealtimePromise(); + var realtime = helper.AblyRealtime(); var channel = realtime.channels.get('pushenabled:foo'); await channel.attach(); @@ -108,7 +108,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('deviceRegistrations save', async function () { - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); var saved = await rest.push.admin.deviceRegistrations.save(testDevice); var got = await rest.push.admin.deviceRegistrations.get(testDevice.id); @@ -162,7 +162,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async devices.push(device); devices_withoutSecret.push(device_withoutSecret); - var rest = helper.AblyRestPromise({ clientId: device.clientId }); + var rest = helper.AblyRest({ clientId: device.clientId }); registrations.push(function () { return rest.push.admin.deviceRegistrations.save(device); }); @@ -172,7 +172,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async })(i); } - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); var res0 = await Promise.all(registrations.map((x) => x())); var res1 = await rest.push.admin.deviceRegistrations.list(null); @@ -195,7 +195,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('deviceRegistrations remove removeWhere', async function () { - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); await rest.push.admin.deviceRegistrations.save(testDevice); await rest.push.admin.deviceRegistrations.remove(testDevice.id); @@ -219,7 +219,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('channelSubscriptions save', async function () { - var rest = helper.AblyRestPromise({ clientId: 'testClient' }); + var rest = helper.AblyRest({ clientId: 'testClient' }); var subscription = { clientId: 'testClient', channel: 'pushenabled:foo' }; var saved = await rest.push.admin.channelSubscriptions.save(subscription); @@ -245,7 +245,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async } subsByChannel[sub.channel].push(sub); - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); subscribes.push(function () { return rest.push.admin.channelSubscriptions.save(sub); }); @@ -255,7 +255,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async })(i); } - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); await Promise.all(subscribes.map((x) => x())); @@ -269,7 +269,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async }); it('push_channelSubscriptions_remove', async function () { - var rest = helper.AblyRestPromise({ clientId: 'testClient' }); + var rest = helper.AblyRest({ clientId: 'testClient' }); var subscription = { clientId: 'testClient', channel: 'pushenabled:foo' }; await rest.push.admin.channelSubscriptions.save(subscription); @@ -282,7 +282,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async for (var i = 0; i < 5; i++) { (function (i) { var sub = { channel: 'pushenabled:listChannels' + ((i % 2) + 1), clientId: 'testClient' + ((i % 3) + 1) }; - var rest = helper.AblyRestPromise({ clientId: sub.clientId }); + var rest = helper.AblyRest({ clientId: sub.clientId }); subscribes.push(function (callback) { return rest.push.admin.channelSubscriptions.save(sub); }); @@ -292,7 +292,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async })(i); } - var rest = helper.AblyRestPromise(); + var rest = helper.AblyRest(); await Promise.all(subscribes.map((x) => x())); diff --git a/test/rest/request.test.js b/test/rest/request.test.js index 844d7f75cd..7055f46191 100644 --- a/test/rest/request.test.js +++ b/test/rest/request.test.js @@ -17,7 +17,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async done(err); return; } - rest = helper.AblyRestPromise({ useBinaryProtocol: false }); + rest = helper.AblyRest({ useBinaryProtocol: false }); done(); }); }); @@ -68,7 +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 () { - rest = helper.AblyRestPromise({ restHost: helper.unroutableAddress }); + rest = helper.AblyRest({ restHost: helper.unroutableAddress }); try { var res = await rest.request('get', '/time', Defaults.protocolVersion, null, null, null); } catch (err) { @@ -168,7 +168,7 @@ define(['ably', 'shared_helper', 'async', 'chai'], function (Ably, helper, async utils.arrForEach(['put', 'patch', 'delete'], function (method) { it('check' + method, async function () { - var restEcho = helper.AblyRestPromise({ useBinaryProtocol: false, restHost: echoServerHost, tls: true }); + 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 b733be0c45..bda82edfb5 100644 --- a/test/rest/stats.test.js +++ b/test/rest/stats.test.js @@ -64,7 +64,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 helper.setupApp(true, function () { - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); helper.createStats(helper.getTestApp(), statsFixtures, function (err) { if (err) { done(err); diff --git a/test/rest/status.test.js b/test/rest/status.test.js index 91063551e0..45e4ee144f 100644 --- a/test/rest/status.test.js +++ b/test/rest/status.test.js @@ -15,7 +15,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { done(err); return; } - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); done(); }); }); diff --git a/test/rest/time.test.js b/test/rest/time.test.js index 62fba2c66b..71d0ee28ab 100644 --- a/test/rest/time.test.js +++ b/test/rest/time.test.js @@ -12,7 +12,7 @@ define(['shared_helper', 'chai'], function (helper, chai) { done(err); return; } - rest = helper.AblyRestPromise(); + rest = helper.AblyRest(); done(); }); });