index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. var spec = require('stream-spec')
  2. var through = require('..')
  3. var a = require('assertions')
  4. /*
  5. I'm using these two functions, and not streams and pipe
  6. so there is less to break. if this test fails it must be
  7. the implementation of _through_
  8. */
  9. function write(array, stream) {
  10. array = array.slice()
  11. function next() {
  12. while(array.length)
  13. if(stream.write(array.shift()) === false)
  14. return stream.once('drain', next)
  15. stream.end()
  16. }
  17. next()
  18. }
  19. function read(stream, callback) {
  20. var actual = []
  21. stream.on('data', function (data) {
  22. actual.push(data)
  23. })
  24. stream.once('end', function () {
  25. callback(null, actual)
  26. })
  27. stream.once('error', function (err) {
  28. callback(err)
  29. })
  30. }
  31. exports['simple defaults'] = function (test) {
  32. var l = 1000
  33. , expected = []
  34. while(l--) expected.push(l * Math.random())
  35. var t = through()
  36. spec(t)
  37. .through()
  38. .pausable()
  39. .validateOnExit()
  40. read(t, function (err, actual) {
  41. if(err) test.error(err) //fail
  42. a.deepEqual(actual, expected)
  43. test.done()
  44. })
  45. write(expected, t)
  46. }
  47. exports['simple functions'] = function (test) {
  48. var l = 1000
  49. , expected = []
  50. while(l--) expected.push(l * Math.random())
  51. var t = through(function (data) {
  52. this.emit('data', data*2)
  53. })
  54. spec(t)
  55. .through()
  56. .pausable()
  57. .validateOnExit()
  58. read(t, function (err, actual) {
  59. if(err) test.error(err) //fail
  60. a.deepEqual(actual, expected.map(function (data) {
  61. return data*2
  62. }))
  63. test.done()
  64. })
  65. write(expected, t)
  66. }
  67. exports['pauses'] = function (test) {
  68. var l = 1000
  69. , expected = []
  70. while(l--) expected.push(l) //Math.random())
  71. var t = through()
  72. spec(t)
  73. .through()
  74. .pausable()
  75. .validateOnExit()
  76. t.on('data', function () {
  77. if(Math.random() > 0.1) return
  78. t.pause()
  79. process.nextTick(function () {
  80. t.resume()
  81. })
  82. })
  83. read(t, function (err, actual) {
  84. if(err) test.error(err) //fail
  85. a.deepEqual(actual, expected)
  86. test.done()
  87. })
  88. write(expected, t)
  89. }