summaryrefslogtreecommitdiff
path: root/test/parallel/test-stream2-pipe-error-handling.js
blob: 7d7cfb6b2b3307a280d83253499e6a07f3c5be75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use strict';
require('../common');
var assert = require('assert');
var stream = require('stream');

(function testErrorListenerCatches() {
  var count = 1000;

  var source = new stream.Readable();
  source._read = function(n) {
    n = Math.min(count, n);
    count -= n;
    source.push(new Buffer(n));
  };

  var unpipedDest;
  source.unpipe = function(dest) {
    unpipedDest = dest;
    stream.Readable.prototype.unpipe.call(this, dest);
  };

  var dest = new stream.Writable();
  dest._write = function(chunk, encoding, cb) {
    cb();
  };

  source.pipe(dest);

  var gotErr = null;
  dest.on('error', function(err) {
    gotErr = err;
  });

  var unpipedSource;
  dest.on('unpipe', function(src) {
    unpipedSource = src;
  });

  var err = new Error('This stream turned into bacon.');
  dest.emit('error', err);
  assert.strictEqual(gotErr, err);
  assert.strictEqual(unpipedSource, source);
  assert.strictEqual(unpipedDest, dest);
})();

(function testErrorWithoutListenerThrows() {
  var count = 1000;

  var source = new stream.Readable();
  source._read = function(n) {
    n = Math.min(count, n);
    count -= n;
    source.push(new Buffer(n));
  };

  var unpipedDest;
  source.unpipe = function(dest) {
    unpipedDest = dest;
    stream.Readable.prototype.unpipe.call(this, dest);
  };

  var dest = new stream.Writable();
  dest._write = function(chunk, encoding, cb) {
    cb();
  };

  source.pipe(dest);

  var unpipedSource;
  dest.on('unpipe', function(src) {
    unpipedSource = src;
  });

  var err = new Error('This stream turned into bacon.');

  var gotErr = null;
  try {
    dest.emit('error', err);
  } catch (e) {
    gotErr = e;
  }
  assert.strictEqual(gotErr, err);
  assert.strictEqual(unpipedSource, source);
  assert.strictEqual(unpipedDest, dest);
})();