/
test-fs-promises-write-optional-params.js
87 lines (76 loc) · 2.72 KB
/
test-fs-promises-write-optional-params.js
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
86
87
'use strict';
const common = require('../common');
// This test ensures that filehandle.write accepts "named parameters" object
// and doesn't interpret objects as strings
const assert = require('assert');
const fsPromises = require('fs').promises;
const path = require('path');
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
const dest = path.resolve(tmpdir.path, 'tmp.txt');
const buffer = Buffer.from('zyx');
async function testInvalid(dest, expectedCode, params) {
let fh;
try {
fh = await fsPromises.open(dest, 'w+');
await assert.rejects(
async () => fh.write(params),
{ code: expectedCode });
} finally {
await fh?.close();
}
}
async function testValid(dest, params) {
let fh;
try {
fh = await fsPromises.open(dest, 'w+');
const writeResult = await fh.write(params);
const writeBufCopy = Uint8Array.prototype.slice.call(writeResult.buffer);
const readResult = await fh.read(params);
const readBufCopy = Uint8Array.prototype.slice.call(readResult.buffer);
assert.ok(writeResult.bytesWritten >= readResult.bytesRead);
if (params.length !== undefined && params.length !== null) {
assert.strictEqual(writeResult.bytesWritten, params.length);
}
if (params.offset === undefined || params.offset === 0) {
assert.deepStrictEqual(writeBufCopy, readBufCopy);
}
assert.deepStrictEqual(writeResult.buffer, readResult.buffer);
} finally {
await fh?.close();
}
}
(async () => {
// Test if first argument is not wrongly interpreted as ArrayBufferView|string
for (const badParams of [
undefined, null, true, 42, 42n, Symbol('42'), NaN, [],
{},
{ buffer: 'amNotParam' },
{ string: 'amNotParam' },
{ buffer: new Uint8Array(1).buffer },
new Date(),
new String('notPrimitive'),
{ toString() { return 'amObject'; } },
{ [Symbol.toPrimitive]: (hint) => 'amObject' },
]) {
await testInvalid(dest, 'ERR_INVALID_ARG_TYPE', badParams);
}
// Various invalid params
testInvalid(dest, 'ERR_OUT_OF_RANGE', { buffer, length: 5 });
testInvalid(dest, 'ERR_OUT_OF_RANGE', { buffer, offset: 5 });
testInvalid(dest, 'ERR_OUT_OF_RANGE', { buffer, offset: 1 });
testInvalid(dest, 'ERR_OUT_OF_RANGE', { buffer, length: 1, offset: 3 });
testInvalid(dest, 'ERR_OUT_OF_RANGE', { buffer, length: -1 });
testInvalid(dest, 'ERR_OUT_OF_RANGE', { buffer, offset: -1 });
// Test compatibility with filehandle.read counterpart with reused params
for (const params of [
{ buffer },
{ buffer, length: 1 },
{ buffer, position: 5 },
{ buffer, length: 1, position: 5 },
{ buffer, length: 1, position: -1, offset: 2 },
{ buffer, length: null },
]) {
await testValid(dest, params);
}
})().then(common.mustCall());