multiclient.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. // Tests of MultiClient, copied from test/client.js with modifications of
  2. // expected connection counts.
  3. const VError = require('verror');
  4. const http2 = require('http2');
  5. const debug = require('debug')('apn');
  6. const credentials = require('../lib/credentials')({
  7. logger: debug,
  8. });
  9. const TEST_PORT = 30939;
  10. const LOAD_TEST_BATCH_SIZE = 2000;
  11. const config = require('../lib/config')({
  12. logger: debug,
  13. prepareCertificate: () => ({}), // credentials.certificate,
  14. prepareToken: credentials.token,
  15. prepareCA: credentials.ca,
  16. });
  17. const Client = require('../lib/client')({
  18. logger: debug,
  19. config,
  20. http2,
  21. });
  22. const MultiClient = require('../lib/multiclient')({
  23. Client,
  24. });
  25. debug.log = console.log.bind(console);
  26. // function builtNotification() {
  27. // return {
  28. // headers: {},
  29. // body: JSON.stringify({ aps: { badge: 1 } }),
  30. // };
  31. // }
  32. // function FakeStream(deviceId, statusCode, response) {
  33. // const fakeStream = new stream.Transform({
  34. // transform: sinon.spy(function(chunk, encoding, callback) {
  35. // expect(this.headers).to.be.calledOnce;
  36. //
  37. // const headers = this.headers.firstCall.args[0];
  38. // expect(headers[":path"].substring(10)).to.equal(deviceId);
  39. //
  40. // this.emit("headers", {
  41. // ":status": statusCode
  42. // });
  43. // callback(null, Buffer.from(JSON.stringify(response) || ""));
  44. // })
  45. // });
  46. // fakeStream.headers = sinon.stub();
  47. //
  48. // return fakeStream;
  49. // }
  50. // XXX these may be flaky in CI due to being sensitive to timing,
  51. // and if a test case crashes, then others may get stuck.
  52. //
  53. // Try to fix this if any issues come up.
  54. describe('MultiClient', () => {
  55. let server;
  56. let client;
  57. const MOCK_BODY = '{"mock-key":"mock-value"}';
  58. const MOCK_DEVICE_TOKEN = 'abcf0123abcf0123abcf0123abcf0123abcf0123abcf0123abcf0123abcf0123';
  59. // Create an insecure http2 client for unit testing.
  60. // (APNS would use https://, not http://)
  61. // (It's probably possible to allow accepting invalid certificates instead,
  62. // but that's not the most important point of these tests)
  63. const createClient = (port, timeout = 500) => {
  64. const mc = new MultiClient({
  65. port: TEST_PORT,
  66. address: '127.0.0.1',
  67. clientCount: 2,
  68. });
  69. mc.clients.forEach(c => {
  70. c._mockOverrideUrl = `http://127.0.0.1:${port}`;
  71. c.config.port = port;
  72. c.config.address = '127.0.0.1';
  73. c.config.requestTimeout = timeout;
  74. });
  75. return mc;
  76. };
  77. // Create an insecure server for unit testing.
  78. const createAndStartMockServer = (port, cb) => {
  79. server = http2.createServer((req, res) => {
  80. const buffers = [];
  81. req.on('data', data => buffers.push(data));
  82. req.on('end', () => {
  83. const requestBody = Buffer.concat(buffers).toString('utf-8');
  84. cb(req, res, requestBody);
  85. });
  86. });
  87. server.listen(port);
  88. server.on('error', err => {
  89. expect.fail(`unexpected error ${err}`);
  90. });
  91. // Don't block the tests if this server doesn't shut down properly
  92. server.unref();
  93. return server;
  94. };
  95. const createAndStartMockLowLevelServer = (port, cb) => {
  96. server = http2.createServer();
  97. server.on('stream', cb);
  98. server.listen(port);
  99. server.on('error', err => {
  100. expect.fail(`unexpected error ${err}`);
  101. });
  102. // Don't block the tests if this server doesn't shut down properly
  103. server.unref();
  104. return server;
  105. };
  106. afterEach(done => {
  107. const closeServer = () => {
  108. if (server) {
  109. server.close();
  110. server = null;
  111. }
  112. done();
  113. };
  114. if (client) {
  115. client.shutdown(closeServer);
  116. client = null;
  117. } else {
  118. closeServer();
  119. }
  120. });
  121. it('rejects invalid clientCount', () => {
  122. [-1, 'invalid'].forEach(clientCount => {
  123. expect(
  124. () =>
  125. new MultiClient({
  126. port: TEST_PORT,
  127. address: '127.0.0.1',
  128. clientCount,
  129. })
  130. ).to.throw(`Expected positive client count but got ${clientCount}`);
  131. });
  132. });
  133. it('Treats HTTP 200 responses as successful', async () => {
  134. let didRequest = false;
  135. let establishedConnections = 0;
  136. let requestsServed = 0;
  137. server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
  138. expect(req.headers).to.deep.equal({
  139. ':authority': '127.0.0.1',
  140. ':method': 'POST',
  141. ':path': `/3/device/${MOCK_DEVICE_TOKEN}`,
  142. ':scheme': 'https',
  143. 'apns-someheader': 'somevalue',
  144. });
  145. expect(requestBody).to.equal(MOCK_BODY);
  146. // res.setHeader('X-Foo', 'bar');
  147. // res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  148. res.writeHead(200);
  149. res.end('');
  150. requestsServed += 1;
  151. didRequest = true;
  152. });
  153. server.on('connection', () => (establishedConnections += 1));
  154. await new Promise(resolve => server.on('listening', resolve));
  155. client = createClient(TEST_PORT);
  156. const runSuccessfulRequest = async () => {
  157. const mockHeaders = { 'apns-someheader': 'somevalue' };
  158. const mockNotification = {
  159. headers: mockHeaders,
  160. body: MOCK_BODY,
  161. };
  162. const mockDevice = MOCK_DEVICE_TOKEN;
  163. const result = await client.write(mockNotification, mockDevice);
  164. expect(result).to.deep.equal({ device: MOCK_DEVICE_TOKEN });
  165. expect(didRequest).to.be.true;
  166. };
  167. expect(establishedConnections).to.equal(0); // should not establish a connection until it's needed
  168. // Validate that when multiple valid requests arrive concurrently,
  169. // only one HTTP/2 connection gets established
  170. await Promise.all([
  171. runSuccessfulRequest(),
  172. runSuccessfulRequest(),
  173. runSuccessfulRequest(),
  174. runSuccessfulRequest(),
  175. runSuccessfulRequest(),
  176. ]);
  177. didRequest = false;
  178. await runSuccessfulRequest();
  179. expect(establishedConnections).to.equal(2); // should establish a connection to the server and reuse it
  180. expect(requestsServed).to.equal(6);
  181. });
  182. // Assert that this doesn't crash when a large batch of requests are requested simultaneously
  183. it('Treats HTTP 200 responses as successful (load test for a batch of requests)', async function () {
  184. this.timeout(10000);
  185. let establishedConnections = 0;
  186. let requestsServed = 0;
  187. server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
  188. expect(req.headers).to.deep.equal({
  189. ':authority': '127.0.0.1',
  190. ':method': 'POST',
  191. ':path': `/3/device/${MOCK_DEVICE_TOKEN}`,
  192. ':scheme': 'https',
  193. 'apns-someheader': 'somevalue',
  194. });
  195. expect(requestBody).to.equal(MOCK_BODY);
  196. // Set a timeout of 100 to simulate latency to a remote server.
  197. setTimeout(() => {
  198. res.writeHead(200);
  199. res.end('');
  200. requestsServed += 1;
  201. }, 100);
  202. });
  203. server.on('connection', () => (establishedConnections += 1));
  204. await new Promise(resolve => server.on('listening', resolve));
  205. client = createClient(TEST_PORT, 1500);
  206. const runSuccessfulRequest = async () => {
  207. const mockHeaders = { 'apns-someheader': 'somevalue' };
  208. const mockNotification = {
  209. headers: mockHeaders,
  210. body: MOCK_BODY,
  211. };
  212. const mockDevice = MOCK_DEVICE_TOKEN;
  213. const result = await client.write(mockNotification, mockDevice);
  214. expect(result).to.deep.equal({ device: MOCK_DEVICE_TOKEN });
  215. };
  216. expect(establishedConnections).to.equal(0); // should not establish a connection until it's needed
  217. // Validate that when multiple valid requests arrive concurrently,
  218. // only one HTTP/2 connection gets established
  219. const promises = [];
  220. for (let i = 0; i < LOAD_TEST_BATCH_SIZE; i++) {
  221. promises.push(runSuccessfulRequest());
  222. }
  223. await Promise.all(promises);
  224. expect(establishedConnections).to.equal(2); // should establish a connection to the server and reuse it
  225. expect(requestsServed).to.equal(LOAD_TEST_BATCH_SIZE);
  226. });
  227. // https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/handling_notification_responses_from_apns
  228. it('JSON decodes HTTP 400 responses', async () => {
  229. let didRequest = false;
  230. let establishedConnections = 0;
  231. server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
  232. expect(requestBody).to.equal(MOCK_BODY);
  233. // res.setHeader('X-Foo', 'bar');
  234. // res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  235. res.writeHead(400);
  236. res.end('{"reason": "BadDeviceToken"}');
  237. didRequest = true;
  238. });
  239. server.on('connection', () => (establishedConnections += 1));
  240. await new Promise(resolve => server.on('listening', resolve));
  241. client = createClient(TEST_PORT);
  242. const infoMessages = [];
  243. const errorMessages = [];
  244. const mockInfoLogger = message => {
  245. infoMessages.push(message);
  246. };
  247. const mockErrorLogger = message => {
  248. errorMessages.push(message);
  249. };
  250. mockInfoLogger.enabled = true;
  251. mockErrorLogger.enabled = true;
  252. client.setLogger(mockInfoLogger, mockErrorLogger);
  253. const runRequestWithBadDeviceToken = async () => {
  254. const mockHeaders = { 'apns-someheader': 'somevalue' };
  255. const mockNotification = {
  256. headers: mockHeaders,
  257. body: MOCK_BODY,
  258. };
  259. const mockDevice = MOCK_DEVICE_TOKEN;
  260. const result = await client.write(mockNotification, mockDevice);
  261. expect(result).to.deep.equal({
  262. device: MOCK_DEVICE_TOKEN,
  263. response: {
  264. reason: 'BadDeviceToken',
  265. },
  266. status: 400,
  267. });
  268. expect(didRequest).to.be.true;
  269. didRequest = false;
  270. };
  271. await runRequestWithBadDeviceToken();
  272. await runRequestWithBadDeviceToken();
  273. expect(establishedConnections).to.equal(2); // should establish a connection to the server and reuse it
  274. expect(infoMessages).to.deep.equal([
  275. 'Session connected',
  276. 'Request ended with status 400 and responseData: {"reason": "BadDeviceToken"}',
  277. 'Session connected',
  278. 'Request ended with status 400 and responseData: {"reason": "BadDeviceToken"}',
  279. ]);
  280. expect(errorMessages).to.deep.equal([]);
  281. });
  282. // node-apn started closing connections in response to a bug report where HTTP 500 responses
  283. // persisted until a new connection was reopened
  284. it('Closes connections when HTTP 500 responses are received', async () => {
  285. let establishedConnections = 0;
  286. let responseDelay = 50;
  287. server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
  288. // Wait 50ms before sending the responses in parallel
  289. setTimeout(() => {
  290. expect(requestBody).to.equal(MOCK_BODY);
  291. res.writeHead(500);
  292. res.end('{"reason": "InternalServerError"}');
  293. }, responseDelay);
  294. });
  295. server.on('connection', () => (establishedConnections += 1));
  296. await new Promise(resolve => server.on('listening', resolve));
  297. client = createClient(TEST_PORT);
  298. const runRequestWithInternalServerError = async () => {
  299. const mockHeaders = { 'apns-someheader': 'somevalue' };
  300. const mockNotification = {
  301. headers: mockHeaders,
  302. body: MOCK_BODY,
  303. };
  304. const mockDevice = MOCK_DEVICE_TOKEN;
  305. const result = await client.write(mockNotification, mockDevice);
  306. expect(result).to.exist;
  307. expect(result.device).to.equal(MOCK_DEVICE_TOKEN);
  308. expect(result.error).to.be.an.instanceof(VError);
  309. expect(result.error.message).to.have.string('stream ended unexpectedly');
  310. };
  311. await runRequestWithInternalServerError();
  312. await runRequestWithInternalServerError();
  313. await runRequestWithInternalServerError();
  314. expect(establishedConnections).to.equal(3); // should close and establish new connections on http 500
  315. // Validate that nothing wrong happens when multiple HTTP 500s are received simultaneously.
  316. // (no segfaults, all promises get resolved, etc.)
  317. responseDelay = 50;
  318. await Promise.all([
  319. runRequestWithInternalServerError(),
  320. runRequestWithInternalServerError(),
  321. runRequestWithInternalServerError(),
  322. runRequestWithInternalServerError(),
  323. ]);
  324. expect(establishedConnections).to.equal(5); // should close and establish new connections on http 500
  325. });
  326. it('Handles unexpected invalid JSON responses', async () => {
  327. let establishedConnections = 0;
  328. const responseDelay = 0;
  329. server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
  330. // Wait 50ms before sending the responses in parallel
  331. setTimeout(() => {
  332. expect(requestBody).to.equal(MOCK_BODY);
  333. res.writeHead(500);
  334. res.end('PC LOAD LETTER');
  335. }, responseDelay);
  336. });
  337. server.on('connection', () => (establishedConnections += 1));
  338. await new Promise(resolve => server.on('listening', resolve));
  339. client = createClient(TEST_PORT);
  340. const runRequestWithInternalServerError = async () => {
  341. const mockHeaders = { 'apns-someheader': 'somevalue' };
  342. const mockNotification = {
  343. headers: mockHeaders,
  344. body: MOCK_BODY,
  345. };
  346. const mockDevice = MOCK_DEVICE_TOKEN;
  347. const result = await client.write(mockNotification, mockDevice);
  348. // Should not happen, but if it does, the promise should resolve with an error
  349. expect(result.device).to.equal(MOCK_DEVICE_TOKEN);
  350. expect(result.error.message.startsWith('Unexpected error processing APNs response: Unexpected token')).to.equal(true);
  351. };
  352. await runRequestWithInternalServerError();
  353. await runRequestWithInternalServerError();
  354. expect(establishedConnections).to.equal(2); // Currently reuses the connections.
  355. });
  356. it('Handles APNs timeouts', async () => {
  357. let didGetRequest = false;
  358. let didGetResponse = false;
  359. server = createAndStartMockServer(TEST_PORT, (req, res, requestBody) => {
  360. didGetRequest = true;
  361. setTimeout(() => {
  362. res.writeHead(200);
  363. res.end('');
  364. didGetResponse = true;
  365. }, 1900);
  366. });
  367. client = createClient(TEST_PORT);
  368. const onListeningPromise = new Promise(resolve => server.on('listening', resolve));
  369. await onListeningPromise;
  370. const mockHeaders = { 'apns-someheader': 'somevalue' };
  371. const mockNotification = {
  372. headers: mockHeaders,
  373. body: MOCK_BODY,
  374. };
  375. const mockDevice = MOCK_DEVICE_TOKEN;
  376. const performRequestExpectingTimeout = async () => {
  377. const result = await client.write(mockNotification, mockDevice);
  378. expect(result).to.deep.equal({
  379. device: MOCK_DEVICE_TOKEN,
  380. error: new VError('apn write timeout'),
  381. });
  382. expect(didGetRequest).to.be.true;
  383. expect(didGetResponse).to.be.false;
  384. };
  385. await performRequestExpectingTimeout();
  386. didGetResponse = false;
  387. didGetRequest = false;
  388. // Should be able to have multiple in flight requests all get notified that the server is shutting down
  389. await Promise.all([
  390. performRequestExpectingTimeout(),
  391. performRequestExpectingTimeout(),
  392. performRequestExpectingTimeout(),
  393. performRequestExpectingTimeout(),
  394. ]);
  395. });
  396. it('Handles goaway frames', async () => {
  397. let didGetRequest = false;
  398. let establishedConnections = 0;
  399. server = createAndStartMockLowLevelServer(TEST_PORT, stream => {
  400. const session = stream.session;
  401. const errorCode = 1;
  402. didGetRequest = true;
  403. session.goaway(errorCode);
  404. });
  405. server.on('connection', () => (establishedConnections += 1));
  406. client = createClient(TEST_PORT);
  407. const onListeningPromise = new Promise(resolve => server.on('listening', resolve));
  408. await onListeningPromise;
  409. const mockHeaders = { 'apns-someheader': 'somevalue' };
  410. const mockNotification = {
  411. headers: mockHeaders,
  412. body: MOCK_BODY,
  413. };
  414. const mockDevice = MOCK_DEVICE_TOKEN;
  415. const performRequestExpectingGoAway = async () => {
  416. const result = await client.write(mockNotification, mockDevice);
  417. expect(result.device).to.equal(MOCK_DEVICE_TOKEN);
  418. expect(result.error).to.be.an.instanceof(VError);
  419. expect(didGetRequest).to.be.true;
  420. didGetRequest = false;
  421. };
  422. await performRequestExpectingGoAway();
  423. await performRequestExpectingGoAway();
  424. expect(establishedConnections).to.equal(2);
  425. });
  426. it('Handles unexpected protocol errors (no response sent)', async () => {
  427. let didGetRequest = false;
  428. let establishedConnections = 0;
  429. let responseTimeout = 0;
  430. server = createAndStartMockLowLevelServer(TEST_PORT, stream => {
  431. setTimeout(() => {
  432. const session = stream.session;
  433. didGetRequest = true;
  434. if (session) {
  435. session.destroy();
  436. }
  437. }, responseTimeout);
  438. });
  439. server.on('connection', () => (establishedConnections += 1));
  440. client = createClient(TEST_PORT);
  441. const onListeningPromise = new Promise(resolve => server.on('listening', resolve));
  442. await onListeningPromise;
  443. const mockHeaders = { 'apns-someheader': 'somevalue' };
  444. const mockNotification = {
  445. headers: mockHeaders,
  446. body: MOCK_BODY,
  447. };
  448. const mockDevice = MOCK_DEVICE_TOKEN;
  449. const performRequestExpectingDisconnect = async () => {
  450. const result = await client.write(mockNotification, mockDevice);
  451. expect(result).to.deep.equal({
  452. device: MOCK_DEVICE_TOKEN,
  453. error: new VError('stream ended unexpectedly with status null and empty body'),
  454. });
  455. expect(didGetRequest).to.be.true;
  456. };
  457. await performRequestExpectingDisconnect();
  458. didGetRequest = false;
  459. await performRequestExpectingDisconnect();
  460. didGetRequest = false;
  461. expect(establishedConnections).to.equal(2);
  462. responseTimeout = 10;
  463. await Promise.all([
  464. performRequestExpectingDisconnect(),
  465. performRequestExpectingDisconnect(),
  466. performRequestExpectingDisconnect(),
  467. performRequestExpectingDisconnect(),
  468. ]);
  469. expect(establishedConnections).to.equal(4);
  470. });
  471. // let fakes, MultiClient;
  472. // beforeEach(() => {
  473. // fakes = {
  474. // config: sinon.stub(),
  475. // EndpointManager: sinon.stub(),
  476. // endpointManager: new EventEmitter(),
  477. // };
  478. // fakes.EndpointManager.returns(fakes.endpointManager);
  479. // fakes.endpointManager.shutdown = sinon.stub();
  480. // MultiClient = require("../lib/client")(fakes);
  481. // });
  482. // describe("constructor", () => {
  483. // it("prepares the configuration with passed options", () => {
  484. // let options = { production: true };
  485. // let client = new MultiClient(options);
  486. // expect(fakes.config).to.be.calledWith(options);
  487. // });
  488. // describe("EndpointManager instance", function() {
  489. // it("is created", () => {
  490. // let client = new MultiClient();
  491. // expect(fakes.EndpointManager).to.be.calledOnce;
  492. // expect(fakes.EndpointManager).to.be.calledWithNew;
  493. // });
  494. // it("is passed the prepared configuration", () => {
  495. // const returnSentinel = { "configKey": "configValue"};
  496. // fakes.config.returns(returnSentinel);
  497. // let client = new MultiClient({});
  498. // expect(fakes.EndpointManager).to.be.calledWith(returnSentinel);
  499. // });
  500. // });
  501. // });
  502. describe('write', () => {
  503. // beforeEach(() => {
  504. // fakes.config.returnsArg(0);
  505. // fakes.endpointManager.getStream = sinon.stub();
  506. // fakes.EndpointManager.returns(fakes.endpointManager);
  507. // });
  508. // context("a stream is available", () => {
  509. // let client;
  510. // context("transmission succeeds", () => {
  511. // beforeEach( () => {
  512. // client = new MultiClient( { address: "testapi" } );
  513. // fakes.stream = new FakeStream("abcd1234", "200");
  514. // fakes.endpointManager.getStream.onCall(0).returns(fakes.stream);
  515. // });
  516. // it("attempts to acquire one stream", () => {
  517. // return client.write(builtNotification(), "abcd1234")
  518. // .then(() => {
  519. // expect(fakes.endpointManager.getStream).to.be.calledOnce;
  520. // });
  521. // });
  522. // describe("headers", () => {
  523. // it("sends the required HTTP/2 headers", () => {
  524. // return client.write(builtNotification(), "abcd1234")
  525. // .then(() => {
  526. // expect(fakes.stream.headers).to.be.calledWithMatch( {
  527. // ":scheme": "https",
  528. // ":method": "POST",
  529. // ":authority": "testapi",
  530. // ":path": "/3/device/abcd1234",
  531. // });
  532. // });
  533. // });
  534. // it("does not include apns headers when not required", () => {
  535. // return client.write(builtNotification(), "abcd1234")
  536. // .then(() => {
  537. // ["apns-id", "apns-priority", "apns-expiration", "apns-topic"].forEach( header => {
  538. // expect(fakes.stream.headers).to.not.be.calledWithMatch(sinon.match.has(header));
  539. // });
  540. // });
  541. // });
  542. // it("sends the notification-specific apns headers when specified", () => {
  543. // let notification = builtNotification();
  544. // notification.headers = {
  545. // "apns-id": "123e4567-e89b-12d3-a456-42665544000",
  546. // "apns-priority": 5,
  547. // "apns-expiration": 123,
  548. // "apns-topic": "io.apn.node",
  549. // };
  550. // return client.write(notification, "abcd1234")
  551. // .then(() => {
  552. // expect(fakes.stream.headers).to.be.calledWithMatch( {
  553. // "apns-id": "123e4567-e89b-12d3-a456-42665544000",
  554. // "apns-priority": 5,
  555. // "apns-expiration": 123,
  556. // "apns-topic": "io.apn.node",
  557. // });
  558. // });
  559. // });
  560. // context("when token authentication is enabled", () => {
  561. // beforeEach(() => {
  562. // fakes.token = {
  563. // generation: 0,
  564. // current: "fake-token",
  565. // regenerate: sinon.stub(),
  566. // isExpired: sinon.stub()
  567. // };
  568. // client = new MultiClient( { address: "testapi", token: fakes.token } );
  569. // fakes.stream = new FakeStream("abcd1234", "200");
  570. // fakes.endpointManager.getStream.onCall(0).returns(fakes.stream);
  571. // });
  572. // it("sends the bearer token", () => {
  573. // let notification = builtNotification();
  574. // return client.write(notification, "abcd1234").then(() => {
  575. // expect(fakes.stream.headers).to.be.calledWithMatch({
  576. // authorization: "bearer fake-token",
  577. // });
  578. // });
  579. // });
  580. // });
  581. // context("when token authentication is disabled", () => {
  582. // beforeEach(() => {
  583. // client = new MultiClient( { address: "testapi" } );
  584. // fakes.stream = new FakeStream("abcd1234", "200");
  585. // fakes.endpointManager.getStream.onCall(0).returns(fakes.stream);
  586. // });
  587. // it("does not set an authorization header", () => {
  588. // let notification = builtNotification();
  589. // return client.write(notification, "abcd1234").then(() => {
  590. // expect(fakes.stream.headers.firstCall.args[0]).to.not.have.property("authorization");
  591. // })
  592. // });
  593. // })
  594. // });
  595. // it("writes the notification data to the pipe", () => {
  596. // const notification = builtNotification();
  597. // return client.write(notification, "abcd1234")
  598. // .then(() => {
  599. // expect(fakes.stream._transform).to.be.calledWithMatch(actual => actual.equals(Buffer.from(notification.body)));
  600. // });
  601. // });
  602. // it("ends the stream", () => {
  603. // sinon.spy(fakes.stream, "end");
  604. // return client.write(builtNotification(), "abcd1234")
  605. // .then(() => {
  606. // expect(fakes.stream.end).to.be.calledOnce;
  607. // });
  608. // });
  609. // it("resolves with the device token", () => {
  610. // return expect(client.write(builtNotification(), "abcd1234"))
  611. // .to.become({ device: "abcd1234" });
  612. // });
  613. // });
  614. // context("error occurs", () => {
  615. // let promise;
  616. // context("general case", () => {
  617. // beforeEach(() => {
  618. // const client = new MultiClient( { address: "testapi" } );
  619. // fakes.stream = new FakeStream("abcd1234", "400", { "reason" : "BadDeviceToken" });
  620. // fakes.endpointManager.getStream.onCall(0).returns(fakes.stream);
  621. // promise = client.write(builtNotification(), "abcd1234");
  622. // });
  623. // it("resolves with the device token, status code and response", () => {
  624. // return expect(promise).to.eventually.deep.equal({ status: "400", device: "abcd1234", response: { reason: "BadDeviceToken" }});
  625. // });
  626. // })
  627. // context("ExpiredProviderToken", () => {
  628. // beforeEach(() => {
  629. // let tokenGenerator = sinon.stub().returns("fake-token");
  630. // const client = new MultiClient( { address: "testapi", token: tokenGenerator });
  631. // })
  632. // });
  633. // });
  634. // context("stream ends without completing request", () => {
  635. // let promise;
  636. // beforeEach(() => {
  637. // const client = new MultiClient( { address: "testapi" } );
  638. // fakes.stream = new stream.Transform({
  639. // transform: function(chunk, encoding, callback) {}
  640. // });
  641. // fakes.stream.headers = sinon.stub();
  642. // fakes.endpointManager.getStream.onCall(0).returns(fakes.stream);
  643. // promise = client.write(builtNotification(), "abcd1234");
  644. // fakes.stream.push(null);
  645. // });
  646. // it("resolves with an object containing the device token", () => {
  647. // return expect(promise).to.eventually.have.property("device", "abcd1234");
  648. // });
  649. // it("resolves with an object containing an error", () => {
  650. // return promise.then( (response) => {
  651. // expect(response).to.have.property("error");
  652. // expect(response.error).to.be.an.instanceOf(Error);
  653. // expect(response.error).to.match(/stream ended unexpectedly/);
  654. // });
  655. // });
  656. // });
  657. // context("stream is unprocessed", () => {
  658. // let promise;
  659. // beforeEach(() => {
  660. // const client = new MultiClient( { address: "testapi" } );
  661. // fakes.stream = new stream.Transform({
  662. // transform: function(chunk, encoding, callback) {}
  663. // });
  664. // fakes.stream.headers = sinon.stub();
  665. // fakes.secondStream = FakeStream("abcd1234", "200");
  666. // fakes.endpointManager.getStream.onCall(0).returns(fakes.stream);
  667. // fakes.endpointManager.getStream.onCall(1).returns(fakes.secondStream);
  668. // promise = client.write(builtNotification(), "abcd1234");
  669. // setImmediate(() => {
  670. // fakes.stream.emit("unprocessed");
  671. // });
  672. // });
  673. // it("attempts to resend on a new stream", function (done) {
  674. // setImmediate(() => {
  675. // expect(fakes.endpointManager.getStream).to.be.calledTwice;
  676. // done();
  677. // });
  678. // });
  679. // it("fulfills the promise", () => {
  680. // return expect(promise).to.eventually.deep.equal({ device: "abcd1234" });
  681. // });
  682. // });
  683. // context("stream error occurs", () => {
  684. // let promise;
  685. // beforeEach(() => {
  686. // const client = new MultiClient( { address: "testapi" } );
  687. // fakes.stream = new stream.Transform({
  688. // transform: function(chunk, encoding, callback) {}
  689. // });
  690. // fakes.stream.headers = sinon.stub();
  691. // fakes.endpointManager.getStream.onCall(0).returns(fakes.stream);
  692. // promise = client.write(builtNotification(), "abcd1234");
  693. // });
  694. // context("passing an Error", () => {
  695. // beforeEach(() => {
  696. // fakes.stream.emit("error", new Error("stream error"));
  697. // });
  698. // it("resolves with an object containing the device token", () => {
  699. // return expect(promise).to.eventually.have.property("device", "abcd1234");
  700. // });
  701. // it("resolves with an object containing a wrapped error", () => {
  702. // return promise.then( (response) => {
  703. // expect(response.error).to.be.an.instanceOf(Error);
  704. // expect(response.error).to.match(/apn write failed/);
  705. // expect(response.error.cause()).to.be.an.instanceOf(Error).and.match(/stream error/);
  706. // });
  707. // });
  708. // });
  709. // context("passing a string", () => {
  710. // it("resolves with the device token and an error", () => {
  711. // fakes.stream.emit("error", "stream error");
  712. // return promise.then( (response) => {
  713. // expect(response).to.have.property("device", "abcd1234");
  714. // expect(response.error).to.to.be.an.instanceOf(Error);
  715. // expect(response.error).to.match(/apn write failed/);
  716. // expect(response.error).to.match(/stream error/);
  717. // });
  718. // });
  719. // });
  720. // });
  721. // });
  722. // context("no new stream is returned but the endpoint later wakes up", () => {
  723. // let notification, promise;
  724. // beforeEach( () => {
  725. // const client = new MultiClient( { address: "testapi" } );
  726. // fakes.stream = new FakeStream("abcd1234", "200");
  727. // fakes.endpointManager.getStream.onCall(0).returns(null);
  728. // fakes.endpointManager.getStream.onCall(1).returns(fakes.stream);
  729. // notification = builtNotification();
  730. // promise = client.write(notification, "abcd1234");
  731. // expect(fakes.stream.headers).to.not.be.called;
  732. // fakes.endpointManager.emit("wakeup");
  733. // return promise;
  734. // });
  735. // it("sends the required headers to the newly available stream", () => {
  736. // expect(fakes.stream.headers).to.be.calledWithMatch( {
  737. // ":scheme": "https",
  738. // ":method": "POST",
  739. // ":authority": "testapi",
  740. // ":path": "/3/device/abcd1234",
  741. // });
  742. // });
  743. // it("writes the notification data to the pipe", () => {
  744. // expect(fakes.stream._transform).to.be.calledWithMatch(actual => actual.equals(Buffer.from(notification.body)));
  745. // });
  746. // });
  747. // context("when 5 successive notifications are sent", () => {
  748. // beforeEach(() => {
  749. // fakes.streams = [
  750. // new FakeStream("abcd1234", "200"),
  751. // new FakeStream("adfe5969", "400", { reason: "MissingTopic" }),
  752. // new FakeStream("abcd1335", "410", { reason: "BadDeviceToken", timestamp: 123456789 }),
  753. // new FakeStream("bcfe4433", "200"),
  754. // new FakeStream("aabbc788", "413", { reason: "PayloadTooLarge" }),
  755. // ];
  756. // });
  757. // context("streams are always returned", () => {
  758. // let promises;
  759. // beforeEach( () => {
  760. // const client = new MultiClient( { address: "testapi" } );
  761. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[0]);
  762. // fakes.endpointManager.getStream.onCall(1).returns(fakes.streams[1]);
  763. // fakes.endpointManager.getStream.onCall(2).returns(fakes.streams[2]);
  764. // fakes.endpointManager.getStream.onCall(3).returns(fakes.streams[3]);
  765. // fakes.endpointManager.getStream.onCall(4).returns(fakes.streams[4]);
  766. // promises = Promise.all([
  767. // client.write(builtNotification(), "abcd1234"),
  768. // client.write(builtNotification(), "adfe5969"),
  769. // client.write(builtNotification(), "abcd1335"),
  770. // client.write(builtNotification(), "bcfe4433"),
  771. // client.write(builtNotification(), "aabbc788"),
  772. // ]);
  773. // return promises;
  774. // });
  775. // it("sends the required headers for each stream", () => {
  776. // expect(fakes.streams[0].headers).to.be.calledWithMatch( { ":path": "/3/device/abcd1234" } );
  777. // expect(fakes.streams[1].headers).to.be.calledWithMatch( { ":path": "/3/device/adfe5969" } );
  778. // expect(fakes.streams[2].headers).to.be.calledWithMatch( { ":path": "/3/device/abcd1335" } );
  779. // expect(fakes.streams[3].headers).to.be.calledWithMatch( { ":path": "/3/device/bcfe4433" } );
  780. // expect(fakes.streams[4].headers).to.be.calledWithMatch( { ":path": "/3/device/aabbc788" } );
  781. // });
  782. // it("writes the notification data for each stream", () => {
  783. // fakes.streams.forEach( stream => {
  784. // expect(stream._transform).to.be.calledWithMatch(actual => actual.equals(Buffer.from(builtNotification().body)));
  785. // });
  786. // });
  787. // it("resolves with the notification outcomes", () => {
  788. // return expect(promises).to.eventually.deep.equal([
  789. // { device: "abcd1234"},
  790. // { device: "adfe5969", status: "400", response: { reason: "MissingTopic" } },
  791. // { device: "abcd1335", status: "410", response: { reason: "BadDeviceToken", timestamp: 123456789 } },
  792. // { device: "bcfe4433"},
  793. // { device: "aabbc788", status: "413", response: { reason: "PayloadTooLarge" } },
  794. // ]);
  795. // });
  796. // });
  797. // context("some streams return, others wake up later", () => {
  798. // let promises;
  799. // beforeEach( function() {
  800. // const client = new MultiClient( { address: "testapi" } );
  801. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[0]);
  802. // fakes.endpointManager.getStream.onCall(1).returns(fakes.streams[1]);
  803. // promises = Promise.all([
  804. // client.write(builtNotification(), "abcd1234"),
  805. // client.write(builtNotification(), "adfe5969"),
  806. // client.write(builtNotification(), "abcd1335"),
  807. // client.write(builtNotification(), "bcfe4433"),
  808. // client.write(builtNotification(), "aabbc788"),
  809. // ]);
  810. // setTimeout(() => {
  811. // fakes.endpointManager.getStream.reset();
  812. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[2]);
  813. // fakes.endpointManager.getStream.onCall(1).returns(null);
  814. // fakes.endpointManager.emit("wakeup");
  815. // }, 1);
  816. // setTimeout(() => {
  817. // fakes.endpointManager.getStream.reset();
  818. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[3]);
  819. // fakes.endpointManager.getStream.onCall(1).returns(fakes.streams[4]);
  820. // fakes.endpointManager.emit("wakeup");
  821. // }, 2);
  822. // return promises;
  823. // });
  824. // it("sends the correct device ID for each stream", () => {
  825. // expect(fakes.streams[0].headers).to.be.calledWithMatch({":path": "/3/device/abcd1234"});
  826. // expect(fakes.streams[1].headers).to.be.calledWithMatch({":path": "/3/device/adfe5969"});
  827. // expect(fakes.streams[2].headers).to.be.calledWithMatch({":path": "/3/device/abcd1335"});
  828. // expect(fakes.streams[3].headers).to.be.calledWithMatch({":path": "/3/device/bcfe4433"});
  829. // expect(fakes.streams[4].headers).to.be.calledWithMatch({":path": "/3/device/aabbc788"});
  830. // });
  831. // it("writes the notification data for each stream", () => {
  832. // fakes.streams.forEach( stream => {
  833. // expect(stream._transform).to.be.calledWithMatch(actual => actual.equals(Buffer.from(builtNotification().body)));
  834. // });
  835. // });
  836. // it("resolves with the notification reponses", () => {
  837. // return expect(promises).to.eventually.deep.equal([
  838. // { device: "abcd1234"},
  839. // { device: "adfe5969", status: "400", response: { reason: "MissingTopic" } },
  840. // { device: "abcd1335", status: "410", response: { reason: "BadDeviceToken", timestamp: 123456789 } },
  841. // { device: "bcfe4433"},
  842. // { device: "aabbc788", status: "413", response: { reason: "PayloadTooLarge" } },
  843. // ]);
  844. // });
  845. // });
  846. // context("connection fails", () => {
  847. // let promises, client;
  848. // beforeEach( function() {
  849. // client = new MultiClient( { address: "testapi" } );
  850. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[0]);
  851. // promises = Promise.all([
  852. // client.write(builtNotification(), "abcd1234"),
  853. // client.write(builtNotification(), "adfe5969"),
  854. // client.write(builtNotification(), "abcd1335"),
  855. // ]);
  856. // setTimeout(() => {
  857. // fakes.endpointManager.getStream.reset();
  858. // fakes.endpointManager.emit("error", new Error("endpoint failed"));
  859. // }, 1);
  860. // return promises;
  861. // });
  862. // it("resolves with 1 success", () => {
  863. // return promises.then( response => {
  864. // expect(response[0]).to.deep.equal({ device: "abcd1234" });
  865. // });
  866. // });
  867. // it("resolves with 2 errors", () => {
  868. // return promises.then( response => {
  869. // expect(response[1]).to.deep.equal({ device: "adfe5969", error: new Error("endpoint failed") });
  870. // expect(response[2]).to.deep.equal({ device: "abcd1335", error: new Error("endpoint failed") });
  871. // })
  872. // });
  873. // it("clears the queue", () => {
  874. // return promises.then( () => {
  875. // expect(client.queue.length).to.equal(0);
  876. // });
  877. // });
  878. // });
  879. // });
  880. // describe("token generator behaviour", () => {
  881. // beforeEach(() => {
  882. // fakes.token = {
  883. // generation: 0,
  884. // current: "fake-token",
  885. // regenerate: sinon.stub(),
  886. // isExpired: sinon.stub()
  887. // }
  888. // fakes.streams = [
  889. // new FakeStream("abcd1234", "200"),
  890. // new FakeStream("adfe5969", "400", { reason: "MissingTopic" }),
  891. // new FakeStream("abcd1335", "410", { reason: "BadDeviceToken", timestamp: 123456789 }),
  892. // ];
  893. // });
  894. // it("reuses the token", () => {
  895. // const client = new MultiClient( { address: "testapi", token: fakes.token } );
  896. // fakes.token.regenerate = () => {
  897. // fakes.token.generation = 1;
  898. // fakes.token.current = "second-token";
  899. // }
  900. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[0]);
  901. // fakes.endpointManager.getStream.onCall(1).returns(fakes.streams[1]);
  902. // fakes.endpointManager.getStream.onCall(2).returns(fakes.streams[2]);
  903. // return Promise.all([
  904. // client.write(builtNotification(), "abcd1234"),
  905. // client.write(builtNotification(), "adfe5969"),
  906. // client.write(builtNotification(), "abcd1335"),
  907. // ]).then(() => {
  908. // expect(fakes.streams[0].headers).to.be.calledWithMatch({ authorization: "bearer fake-token" });
  909. // expect(fakes.streams[1].headers).to.be.calledWithMatch({ authorization: "bearer fake-token" });
  910. // expect(fakes.streams[2].headers).to.be.calledWithMatch({ authorization: "bearer fake-token" });
  911. // });
  912. // });
  913. // context("token expires", () => {
  914. // beforeEach(() => {
  915. // fakes.token.regenerate = function (generation) {
  916. // if (generation === fakes.token.generation) {
  917. // fakes.token.generation += 1;
  918. // fakes.token.current = "token-" + fakes.token.generation;
  919. // }
  920. // }
  921. // });
  922. // it("resends the notification with a new token", () => {
  923. // fakes.streams = [
  924. // new FakeStream("adfe5969", "403", { reason: "ExpiredProviderToken" }),
  925. // new FakeStream("adfe5969", "200"),
  926. // ];
  927. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[0]);
  928. // const client = new MultiClient( { address: "testapi", token: fakes.token } );
  929. // const promise = client.write(builtNotification(), "adfe5969");
  930. // setTimeout(() => {
  931. // fakes.endpointManager.getStream.reset();
  932. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[1]);
  933. // fakes.endpointManager.emit("wakeup");
  934. // }, 1);
  935. // return promise.then(() => {
  936. // expect(fakes.streams[0].headers).to.be.calledWithMatch({ authorization: "bearer fake-token" });
  937. // expect(fakes.streams[1].headers).to.be.calledWithMatch({ authorization: "bearer token-1" });
  938. // });
  939. // });
  940. // it("only regenerates the token once per-expiry", () => {
  941. // fakes.streams = [
  942. // new FakeStream("abcd1234", "200"),
  943. // new FakeStream("adfe5969", "403", { reason: "ExpiredProviderToken" }),
  944. // new FakeStream("abcd1335", "403", { reason: "ExpiredProviderToken" }),
  945. // new FakeStream("adfe5969", "400", { reason: "MissingTopic" }),
  946. // new FakeStream("abcd1335", "410", { reason: "BadDeviceToken", timestamp: 123456789 }),
  947. // ];
  948. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[0]);
  949. // fakes.endpointManager.getStream.onCall(1).returns(fakes.streams[1]);
  950. // fakes.endpointManager.getStream.onCall(2).returns(fakes.streams[2]);
  951. // const client = new MultiClient( { address: "testapi", token: fakes.token } );
  952. // const promises = Promise.all([
  953. // client.write(builtNotification(), "abcd1234"),
  954. // client.write(builtNotification(), "adfe5969"),
  955. // client.write(builtNotification(), "abcd1335"),
  956. // ]);
  957. // setTimeout(() => {
  958. // fakes.endpointManager.getStream.reset();
  959. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[3]);
  960. // fakes.endpointManager.getStream.onCall(1).returns(fakes.streams[4]);
  961. // fakes.endpointManager.emit("wakeup");
  962. // }, 1);
  963. // return promises.then(() => {
  964. // expect(fakes.streams[0].headers).to.be.calledWithMatch({ authorization: "bearer fake-token" });
  965. // expect(fakes.streams[1].headers).to.be.calledWithMatch({ authorization: "bearer fake-token" });
  966. // expect(fakes.streams[2].headers).to.be.calledWithMatch({ authorization: "bearer fake-token" });
  967. // expect(fakes.streams[3].headers).to.be.calledWithMatch({ authorization: "bearer token-1" });
  968. // expect(fakes.streams[4].headers).to.be.calledWithMatch({ authorization: "bearer token-1" });
  969. // });
  970. // });
  971. // it("abandons sending after 3 ExpiredProviderToken failures", () => {
  972. // fakes.streams = [
  973. // new FakeStream("adfe5969", "403", { reason: "ExpiredProviderToken" }),
  974. // new FakeStream("adfe5969", "403", { reason: "ExpiredProviderToken" }),
  975. // new FakeStream("adfe5969", "403", { reason: "ExpiredProviderToken" }),
  976. // ];
  977. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[0]);
  978. // fakes.endpointManager.getStream.onCall(1).returns(fakes.streams[1]);
  979. // fakes.endpointManager.getStream.onCall(2).returns(fakes.streams[2]);
  980. // const client = new MultiClient( { address: "testapi", token: fakes.token } );
  981. // return expect(client.write(builtNotification(), "adfe5969")).to.eventually.have.property("status", "403");
  982. // });
  983. // it("regenerate token", () => {
  984. // fakes.stream = new FakeStream("abcd1234", "200");
  985. // fakes.endpointManager.getStream.onCall(0).returns(fakes.stream);
  986. // fakes.token.isExpired = function (current, validSeconds) {
  987. // return true;
  988. // }
  989. // let client = new MultiClient({
  990. // address: "testapi",
  991. // token: fakes.token
  992. // });
  993. // return client.write(builtNotification(), "abcd1234")
  994. // .then(() => {
  995. // expect(fakes.token.generation).to.equal(1);
  996. // });
  997. // });
  998. // it("internal server error", () => {
  999. // fakes.stream = new FakeStream("abcd1234", "500", { reason: "InternalServerError" });
  1000. // fakes.stream.connection = sinon.stub();
  1001. // fakes.stream.connection.close = sinon.stub();
  1002. // fakes.endpointManager.getStream.onCall(0).returns(fakes.stream);
  1003. // let client = new MultiClient({
  1004. // address: "testapi",
  1005. // token: fakes.token
  1006. // });
  1007. // return expect(client.write(builtNotification(), "abcd1234")).to.eventually.have.deep.property("error.jse_shortmsg","Error 500, stream ended unexpectedly");
  1008. // });
  1009. // });
  1010. // });
  1011. });
  1012. describe('shutdown', () => {
  1013. // beforeEach(() => {
  1014. // fakes.config.returnsArg(0);
  1015. // fakes.endpointManager.getStream = sinon.stub();
  1016. // fakes.EndpointManager.returns(fakes.endpointManager);
  1017. // });
  1018. // context("with no pending notifications", () => {
  1019. // it("invokes shutdown on endpoint manager", () => {
  1020. // let client = new MultiClient();
  1021. // client.shutdown();
  1022. // expect(fakes.endpointManager.shutdown).to.be.calledOnce;
  1023. // });
  1024. // });
  1025. // context("with pending notifications", () => {
  1026. // it("invokes shutdown on endpoint manager after queue drains", () => {
  1027. // let client = new MultiClient({ address: "none" });
  1028. // fakes.streams = [
  1029. // new FakeStream("abcd1234", "200"),
  1030. // new FakeStream("adfe5969", "400", { reason: "MissingTopic" }),
  1031. // new FakeStream("abcd1335", "410", { reason: "BadDeviceToken", timestamp: 123456789 }),
  1032. // new FakeStream("bcfe4433", "200"),
  1033. // new FakeStream("aabbc788", "413", { reason: "PayloadTooLarge" }),
  1034. // ];
  1035. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[0]);
  1036. // fakes.endpointManager.getStream.onCall(1).returns(fakes.streams[1]);
  1037. // let promises = Promise.all([
  1038. // client.write(builtNotification(), "abcd1234"),
  1039. // client.write(builtNotification(), "adfe5969"),
  1040. // client.write(builtNotification(), "abcd1335"),
  1041. // client.write(builtNotification(), "bcfe4433"),
  1042. // client.write(builtNotification(), "aabbc788"),
  1043. // ]);
  1044. // client.shutdown();
  1045. // expect(fakes.endpointManager.shutdown).to.not.be.called;
  1046. // setTimeout(() => {
  1047. // fakes.endpointManager.getStream.reset();
  1048. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[2]);
  1049. // fakes.endpointManager.getStream.onCall(1).returns(null);
  1050. // fakes.endpointManager.emit("wakeup");
  1051. // }, 1);
  1052. // setTimeout(() => {
  1053. // fakes.endpointManager.getStream.reset();
  1054. // fakes.endpointManager.getStream.onCall(0).returns(fakes.streams[3]);
  1055. // fakes.endpointManager.getStream.onCall(1).returns(fakes.streams[4]);
  1056. // fakes.endpointManager.emit("wakeup");
  1057. // }, 2);
  1058. // return promises.then( () => {
  1059. // expect(fakes.endpointManager.shutdown).to.have.been.called;
  1060. // });
  1061. // });
  1062. // });
  1063. });
  1064. });