node/test/parallel/test-buffer-tostring-rangeerror.js
Joyee Cheung 996a774eba
test: skip in test-buffer-tostring-rangeerror on allocation failure
If the buffer allocation fails due to insufficient memory, there is no
point continue testing toString().

PR-URL: https://github.com/nodejs/node/pull/58415
Reviewed-By: LiviaMedeiros <livia@cirno.name>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
2025-05-23 21:02:37 +00:00

44 lines
1 KiB
JavaScript

'use strict';
const common = require('../common');
// This test ensures that Node.js throws an Error when trying to convert a
// large buffer into a string.
// Regression test for https://github.com/nodejs/node/issues/649.
if (!common.enoughTestMem) {
common.skip('skipped due to memory requirements');
}
const assert = require('assert');
const {
Buffer,
constants: {
MAX_STRING_LENGTH,
},
} = require('buffer');
const len = MAX_STRING_LENGTH + 1;
const message = {
code: 'ERR_STRING_TOO_LONG',
name: 'Error',
};
function test(getBuffer) {
let buf;
try {
buf = getBuffer();
} catch (e) {
// If the buffer allocation fails, we skip the test.
if (e.code === 'ERR_MEMORY_ALLOCATION_FAILED' || /Array buffer allocation failed/.test(e.message)) {
return;
}
}
assert.throws(() => { buf.toString('utf8'); }, message);
}
test(() => Buffer(len));
test(() => Buffer.allocUnsafeSlow(len));
test(() => Buffer.alloc(len));
test(() => Buffer.allocUnsafe(len));
test(() => Buffer.allocUnsafeSlow(len));