buffered.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /* jshint loopfunc: true */
  2. /* global describe:true, beforeEach:true, it:true */
  3. var chan = require('..')
  4. var expect = require('expect.js')
  5. describe('A unbuffered channel', function () {
  6. it(
  7. 'should not call the added callback until the value is removed',
  8. function (done) {
  9. var ch = chan(0) // unbuffered
  10. var cbCalled = false
  11. ch('foo')(function () {
  12. cbCalled = true
  13. })
  14. setImmediate(function () {
  15. expect(cbCalled).to.not.be.ok()
  16. ch(function (err, val) {
  17. setImmediate(function () {
  18. expect(cbCalled).to.be.ok()
  19. done()
  20. })
  21. })
  22. })
  23. }
  24. )
  25. })
  26. describe('A buffered channel', function () {
  27. it(
  28. 'should pull values from the buffer when yielded',
  29. function (done) {
  30. var ch = chan(1)
  31. var cbCalled = false
  32. var testValue = 'foo'
  33. ch(testValue)
  34. ch(function (err, val) {
  35. cbCalled = true
  36. expect(val).to.be(testValue)
  37. })
  38. setImmediate(function () {
  39. expect(cbCalled).to.be.ok()
  40. done()
  41. })
  42. }
  43. )
  44. describe('with a non-full buffer', function () {
  45. it(
  46. 'should call added callback as soon as it is given to the returned thunk',
  47. function (done) {
  48. var buffer = 3
  49. var ch = chan(buffer)
  50. var called = 0
  51. var added = 0
  52. while (++added <= buffer + 10) {
  53. ch(added)(function (err) {
  54. called++
  55. })
  56. }
  57. setImmediate(function () {
  58. expect(called).to.be(buffer)
  59. done()
  60. })
  61. }
  62. )
  63. })
  64. describe('with a full buffer', function () {
  65. it(
  66. 'should not add another value untill a value has been removed',
  67. function (done) {
  68. var ch = chan(1)
  69. var cbCalled = false
  70. ch('foo')
  71. ch('bar')(function () {
  72. cbCalled = true
  73. })
  74. setImmediate(function () {
  75. expect(cbCalled).to.not.be.ok()
  76. ch(function (err, val) {
  77. setImmediate(function () {
  78. expect(cbCalled).to.be.ok()
  79. done()
  80. })
  81. })
  82. })
  83. }
  84. )
  85. it(
  86. 'should call cb with an error when the channel is closed before adding',
  87. function (done) {
  88. var ch = chan(0)
  89. var cbCalled = false
  90. ch('foo')(function (err) {
  91. cbCalled = true
  92. expect(err).to.be.an(Error)
  93. })
  94. ch.close()
  95. setImmediate(function () {
  96. expect(cbCalled).to.be.ok()
  97. done()
  98. })
  99. }
  100. )
  101. })
  102. })