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