api-test.js 2.6 KB

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