socket_cleanup_spec.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. var should = require('should'),
  2. needle = require('./../'),
  3. fs = require('fs'),
  4. https = require('https'),
  5. stream = require('stream');
  6. describe('socket cleanup', function(){
  7. var outFile = 'test/tmp';
  8. var httpAgent, readStream, writeStream
  9. var file = 'ubuntu-21.04-desktop-amd64.iso',
  10. url = 'https://releases.ubuntu.com/21.04/' + file;
  11. function getActiveSockets() {
  12. return Object.keys(httpAgent.sockets).length
  13. }
  14. before(function() {
  15. httpAgent = new https.Agent({
  16. keepAlive : true,
  17. maxSockets : 1
  18. });
  19. })
  20. after(function() {
  21. httpAgent.destroy()
  22. fs.unlinkSync(outFile);
  23. })
  24. it('should cleanup sockets on ERR_STREAM_PREMATURE_CLOSE (using .pipe)', function(done) {
  25. getActiveSockets().should.eql(0);
  26. var resp = needle.get(url, { agent: httpAgent });
  27. var writable = fs.createWriteStream(outFile);
  28. resp.pipe(writable);
  29. writable.on('close', function(e) {
  30. if (!resp.done) resp.abort();
  31. })
  32. setTimeout(function() {
  33. getActiveSockets().should.eql(1);
  34. writable.destroy();
  35. }, 50);
  36. setTimeout(function() {
  37. getActiveSockets().should.eql(0);
  38. done();
  39. }, 500); // takes a bit
  40. })
  41. it('should cleanup sockets on ERR_STREAM_PREMATURE_CLOSE (using stream.pipeline)', function(done) {
  42. if (!stream.pipeline)
  43. return done()
  44. getActiveSockets().should.eql(0);
  45. var resp = needle.get(url, { agent: httpAgent });
  46. var writable = fs.createWriteStream(outFile);
  47. stream.pipeline(resp, writable, function(err) {
  48. err.code.should.eql('ERR_STREAM_PREMATURE_CLOSE')
  49. if (err) resp.request.destroy();
  50. });
  51. setTimeout(function() {
  52. getActiveSockets().should.eql(1);
  53. writable.destroy();
  54. }, 50);
  55. setTimeout(function() {
  56. getActiveSockets().should.eql(0);
  57. done();
  58. }, 1000); // takes a bit
  59. })
  60. })