1'use strict';
2const common = require('../common');
3const assert = require('assert');
4
5const { Writable } = require('stream');
6
7function expectError(w, args, code, sync) {
8  if (sync) {
9    if (code) {
10      assert.throws(() => w.write(...args), { code });
11    } else {
12      w.write(...args);
13    }
14  } else {
15    let errorCalled = false;
16    let ticked = false;
17    w.write(...args, common.mustCall((err) => {
18      assert.strictEqual(ticked, true);
19      assert.strictEqual(errorCalled, false);
20      assert.strictEqual(err.code, code);
21    }));
22    ticked = true;
23    w.on('error', common.mustCall((err) => {
24      errorCalled = true;
25      assert.strictEqual(err.code, code);
26    }));
27  }
28}
29
30function test(autoDestroy) {
31  {
32    const w = new Writable({
33      autoDestroy,
34      _write() {}
35    });
36    w.end();
37    expectError(w, ['asd'], 'ERR_STREAM_WRITE_AFTER_END');
38  }
39
40  {
41    const w = new Writable({
42      autoDestroy,
43      _write() {}
44    });
45    w.destroy();
46  }
47
48  {
49    const w = new Writable({
50      autoDestroy,
51      _write() {}
52    });
53    expectError(w, [null], 'ERR_STREAM_NULL_VALUES', true);
54  }
55
56  {
57    const w = new Writable({
58      autoDestroy,
59      _write() {}
60    });
61    expectError(w, [{}], 'ERR_INVALID_ARG_TYPE', true);
62  }
63
64  {
65    const w = new Writable({
66      decodeStrings: false,
67      autoDestroy,
68      _write() {}
69    });
70    expectError(w, ['asd', 'noencoding'], 'ERR_UNKNOWN_ENCODING', true);
71  }
72}
73
74test(false);
75test(true);
76