readable.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. var Stream = require('stream')
  2. var spec = require('..')
  3. var tests = 0
  4. function pass(message) {
  5. console.log('ok ' + ++tests, message ? ' -- ' + message : '')
  6. }
  7. function fail(message) {
  8. console.log('not ok ' + ++tests, message ? ' -- ' + message : '')
  9. }
  10. function checkValid(contract, expectFail) {
  11. return function (create, test) {
  12. var stream = create()
  13. try {
  14. var validate = contract(stream, spec).validate
  15. test(stream)
  16. validate()
  17. } catch (err) {
  18. if(!expectFail) {
  19. fail(err.message); throw err
  20. }
  21. return pass(err.message)
  22. }
  23. if(expectFail) {
  24. throw new Error('expected error')
  25. }
  26. pass('valid')
  27. }
  28. }
  29. var valid = checkValid(function (stream, spec) {
  30. return spec(stream).readable()
  31. }, false)
  32. var invalid = checkValid(function (stream, spec) {
  33. return spec(stream).readable()
  34. }, true)
  35. //does not emit 'end'
  36. invalid(function () {
  37. var s = new Stream()
  38. return s
  39. }, function (s) {
  40. })
  41. //does not set readable = false, on 'end'
  42. invalid(function () {
  43. var s = new Stream()
  44. s.destroy = function () {}
  45. s._end = function () {
  46. this.emit('end')
  47. }
  48. return s
  49. }, function (s) {
  50. s._end()
  51. })
  52. //does not set emit 'close'
  53. invalid(function () {
  54. var s = new Stream()
  55. s.destroy = function () {}
  56. s._end = function () {
  57. this.readable = false
  58. this.emit('end')
  59. }
  60. return s
  61. }, function (s) {
  62. s._end()
  63. })
  64. valid(function () {
  65. var s = new Stream()
  66. s.destroy = function () {}
  67. s._end = function () {
  68. this.readable = false
  69. this.emit('end')
  70. this.emit('close')
  71. }
  72. return s
  73. }, function (s) {
  74. s._end()
  75. })