api-test.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. var assert = require('assert');
  2. var net = require('net');
  3. var streamPair = require('stream-pair');
  4. var thing = require('../');
  5. describe('Handle Thing', function() {
  6. var handle;
  7. var pair;
  8. var socket;
  9. [ 'normal', 'lazy' ].forEach(function(mode) {
  10. describe(mode, function() {
  11. beforeEach(function() {
  12. pair = streamPair.create();
  13. handle = thing.create(mode === 'normal' ? pair.other : null);
  14. socket = new net.Socket({ handle: handle });
  15. if (mode === 'lazy') {
  16. setTimeout(function() {
  17. handle.setStream(pair.other);
  18. }, 50);
  19. }
  20. // For v0.8
  21. socket.readable = true;
  22. socket.writable = true;
  23. });
  24. afterEach(function() {
  25. assert(handle._stream);
  26. });
  27. it('should write data to Socket', function(done) {
  28. pair.write('hello');
  29. pair.write(' world');
  30. pair.end('... ok');
  31. var chunks = '';
  32. socket.on('data', function(chunk) {
  33. chunks += chunk;
  34. });
  35. socket.on('end', function() {
  36. assert.equal(chunks, 'hello world... ok');
  37. // allowHalfOpen is `false`, so the `end` should be followed by `close`
  38. socket.once('close', function() {
  39. done();
  40. });
  41. });
  42. });
  43. it('should read data from Socket', function(done) {
  44. socket.write('hello');
  45. socket.write(' world');
  46. socket.end('... ok');
  47. var chunks = '';
  48. pair.on('data', function(chunk) {
  49. chunks += chunk;
  50. });
  51. pair.on('end', function() {
  52. assert.equal(chunks, 'hello world... ok');
  53. done();
  54. });
  55. });
  56. it('should invoke `close` callback', function(done) {
  57. handle._options.close = function(callback) {
  58. done();
  59. process.nextTick(callback);
  60. };
  61. pair.end('hello');
  62. socket.resume();
  63. });
  64. it('should kill pending requests', function(done) {
  65. handle._options.close = function() {
  66. setTimeout(done, 75);
  67. };
  68. socket.write('hello');
  69. socket.destroy();
  70. });
  71. if (mode === 'normal') {
  72. it('should invoke `getPeerName` callback', function() {
  73. handle._options.getPeerName = function() {
  74. return { address: 'ohai' };
  75. };
  76. assert.equal(socket.remoteAddress, 'ohai');
  77. });
  78. it('should emit ECONNRESET at `close` event', function(done) {
  79. pair.other.emit('close');
  80. // No error emitted in v0.8
  81. if (thing.mode === 'rusty') {
  82. socket.on('close', function() {
  83. done();
  84. });
  85. return;
  86. }
  87. socket.on('error', function(err) {
  88. assert(/ECONNRESET/.test(err.message));
  89. done();
  90. });
  91. });
  92. }
  93. });
  94. });
  95. });