socket_pool_spec.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. var needle = require('../'),
  2. should = require('should'),
  3. http = require('http');
  4. var server, port = 11112;
  5. describe('socket reuse', function() {
  6. var httpAgent = new http.Agent({
  7. keepAlive : true,
  8. maxSockets : 1
  9. });
  10. before(function(done) {
  11. server = http.createServer(function(req, res) {
  12. res.setHeader('Content-Type', 'application/json');
  13. setTimeout(function() {
  14. res.end('{"foo":"bar"}');
  15. }, 50);
  16. }).listen(port, done);
  17. });
  18. after(function(done) {
  19. httpAgent.destroy();
  20. server.close(done);
  21. });
  22. describe('when sockets are reused', function() {
  23. it('does not duplicate listeners on .end', function(done) {
  24. var last_error;
  25. var count = 10;
  26. function completed(err) {
  27. --count || done(last_error);
  28. }
  29. function send() {
  30. needle.get('localhost:' + port, { agent: httpAgent }, function(err, resp) {
  31. if (err)
  32. throw new Error("Unexpected error: " + err);
  33. // lets go through all sockets and inspect all socket objects
  34. for (hostTarget in httpAgent.sockets) {
  35. httpAgent.sockets[hostTarget].forEach(function(socket) {
  36. // normally, there are 2 internal listeners and 1 needle sets up,
  37. // but to be sure the test does not fail even if newer node versions
  38. // introduce additional listeners, we use a higher limit.
  39. try {
  40. socket.listeners('end').length.should.be.below(5, "too many listeners on the socket object's end event");
  41. } catch (e) {
  42. last_error = e;
  43. }
  44. });
  45. }
  46. completed();
  47. });
  48. }
  49. for (var i = 0; i < count; i++) {
  50. send();
  51. }
  52. });
  53. });
  54. });