test: refactor common.expectsError

This completely refactors the `expectsError` behavior: so far it's
almost identical to `assert.throws(fn, object)` in case it was used
with a function as first argument. It had a magical property check
that allowed to verify a functions `type` in case `type` was passed
used in the validation object. This pattern is now completely removed
and `assert.throws()` should be used instead.

The main intent for `common.expectsError()` is to verify error cases
for callback based APIs. This is now more flexible by accepting all
validation possibilites that `assert.throws()` accepts as well. No
magical properties exist anymore. This reduces surprising behavior
for developers who are not used to the Node.js core code base.

This has the side effect that `common` is used significantly less
frequent.

Backport-PR-URL: https://github.com/nodejs/node/pull/31449
PR-URL: https://github.com/nodejs/node/pull/31092
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
This commit is contained in:
Ruben Bridgewater authored and Myles Borins committed 2020-04-01 12:58:33 -04:00
1 parent e4f9360287
commit d568efcd22
392 files changed
+2106 -2148

No files matched your search

-1
View File
@@ -14,7 +14,6 @@ rules:
# Custom rules in tools/eslint-rules
node-core/prefer-assert-iferror: error
node-core/prefer-assert-methods: error
node-core/prefer-common-expectserror: error
node-core/prefer-common-mustnotcall: error
node-core/crypto-check: error
node-core/eslint-check: error
@@ -5,6 +5,7 @@ const skipMessage = 'intensive toString tests due to memory confinements';
if (!common.enoughTestMem)
common.skip(skipMessage);
const assert = require('assert');
const binding = require(`./build/${common.buildType}/binding`);
// v8 fails silently if string length > v8::String::kMaxLength
@@ -25,11 +26,11 @@ if (!binding.ensureAllocation(2 * kStringMaxLength))
common.skip(skipMessage);
const stringLengthHex = kStringMaxLength.toString(16);
common.expectsError(() => {
assert.throws(() => {
buf.toString('ascii');
}, {
message: `Cannot create a string longer than 0x${stringLengthHex} ` +
'characters',
code: 'ERR_STRING_TOO_LONG',
type: Error
name: 'Error'
});
@@ -5,6 +5,7 @@ const skipMessage = 'intensive toString tests due to memory confinements';
if (!common.enoughTestMem)
common.skip(skipMessage);
const assert = require('assert');
const binding = require(`./build/${common.buildType}/binding`);
// v8 fails silently if string length > v8::String::kMaxLength
@@ -25,11 +26,11 @@ if (!binding.ensureAllocation(2 * kStringMaxLength))
common.skip(skipMessage);
const stringLengthHex = kStringMaxLength.toString(16);
common.expectsError(() => {
assert.throws(() => {
buf.toString('base64');
}, {
message: `Cannot create a string longer than 0x${stringLengthHex} ` +
'characters',
code: 'ERR_STRING_TOO_LONG',
type: Error
name: 'Error'
});
@@ -27,13 +27,13 @@ if (!binding.ensureAllocation(2 * kStringMaxLength))
common.skip(skipMessage);
const stringLengthHex = kStringMaxLength.toString(16);
common.expectsError(() => {
assert.throws(() => {
buf.toString('latin1');
}, {
message: `Cannot create a string longer than 0x${stringLengthHex} ` +
'characters',
code: 'ERR_STRING_TOO_LONG',
type: Error
name: 'Error'
});
// FIXME: Free the memory early to avoid OOM.
@@ -5,6 +5,7 @@ const skipMessage = 'intensive toString tests due to memory confinements';
if (!common.enoughTestMem)
common.skip(skipMessage);
const assert = require('assert');
const binding = require(`./build/${common.buildType}/binding`);
// v8 fails silently if string length > v8::String::kMaxLength
@@ -25,11 +26,11 @@ if (!binding.ensureAllocation(2 * kStringMaxLength))
common.skip(skipMessage);
const stringLengthHex = kStringMaxLength.toString(16);
common.expectsError(() => {
assert.throws(() => {
buf.toString('hex');
}, {
message: `Cannot create a string longer than 0x${stringLengthHex} ` +
'characters',
code: 'ERR_STRING_TOO_LONG',
type: Error
name: 'Error'
});
@@ -35,7 +35,7 @@ assert.throws(() => {
message: `Cannot create a string longer than 0x${stringLengthHex} ` +
'characters',
code: 'ERR_STRING_TOO_LONG',
type: Error
name: 'Error'
})(e);
return true;
} else {
@@ -43,11 +43,11 @@ assert.throws(() => {
}
});
common.expectsError(() => {
assert.throws(() => {
buf.toString('utf8');
}, {
message: `Cannot create a string longer than 0x${stringLengthHex} ` +
'characters',
code: 'ERR_STRING_TOO_LONG',
type: Error
name: 'Error'
});
@@ -5,6 +5,7 @@ const skipMessage = 'intensive toString tests due to memory confinements';
if (!common.enoughTestMem)
common.skip(skipMessage);
const assert = require('assert');
const binding = require(`./build/${common.buildType}/binding`);
// v8 fails silently if string length > v8::String::kMaxLength
@@ -26,11 +27,11 @@ if (!binding.ensureAllocation(2 * kStringMaxLength))
const stringLengthHex = kStringMaxLength.toString(16);
common.expectsError(() => {
assert.throws(() => {
buf.toString('utf16le');
}, {
message: `Cannot create a string longer than 0x${stringLengthHex} ` +
'characters',
code: 'ERR_STRING_TOO_LONG',
type: Error
name: 'Error'
});
@@ -18,9 +18,9 @@ if (process.argv[2] === 'child') {
}
[null, undefined, 1, Date, {}, []].forEach((i) => {
common.expectsError(() => new Foo(i), {
assert.throws(() => new Foo(i), {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
name: 'TypeError'
});
});
@@ -12,16 +12,16 @@ const { checkInvocations } = require('./hook-checks');
const hooks = initHooks();
hooks.enable();
common.expectsError(
assert.throws(
() => new AsyncResource(), {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
});
common.expectsError(() => {
assert.throws(() => {
new AsyncResource('invalid_trigger_id', { triggerAsyncId: null });
}, {
code: 'ERR_INVALID_ASYNC_ID',
type: RangeError,
name: 'RangeError',
});
assert.strictEqual(
+10 -36
View File
@@ -81,44 +81,17 @@ least 1 GHz.
Indicates if there is more than 1gb of total memory.
### `expectsError([fn, ]settings[, exact])`
* `fn` [&lt;Function>][] a function that should throw.
* `settings` [&lt;Object>][]
that must contain the `code` property plus any of the other following
properties (some properties only apply for `AssertionError`):
* `code` [&lt;string>][]
expected error must have this value for its `code` property.
* `type` [&lt;Function>][]
expected error must be an instance of `type` and must be an Error subclass.
* `message` [&lt;string>][] or [&lt;RegExp>][]
if a string is provided for `message`, expected error must have it for its
`message` property; if a regular expression is provided for `message`, the
regular expression must match the `message` property of the expected error.
* `name` [&lt;string>][]
expected error must have this value for its `name` property.
* `info` &lt;Object> expected error must have the same `info` property
that is deeply equal to this value.
* `generatedMessage` [&lt;string>][]
(`AssertionError` only) expected error must have this value for its
`generatedMessage` property.
* `actual` &lt;any>
(`AssertionError` only) expected error must have this value for its
`actual` property.
* `expected` &lt;any>
(`AssertionError` only) expected error must have this value for its
`expected` property.
* `operator` &lt;any>
(`AssertionError` only) expected error must have this value for its
`operator` property.
### expectsError(validator\[, exact\])
* `validator` [&lt;Object>][] | [&lt;RegExp>][] | [&lt;Function>][] |
[&lt;Error>][] The validator behaves identical to
`assert.throws(fn, validator)`.
* `exact` [&lt;number>][] default = 1
* return [&lt;Function>][]
* return [&lt;Function>][] A callback function that expects an error.
If `fn` is provided, it will be passed to `assert.throws` as first argument
and `undefined` will be returned.
Otherwise a function suitable as callback or for use as a validation function
passed as the second argument to `assert.throws()` will be returned. If the
returned function has not been called exactly `exact` number of times when the
test is complete, then the test will fail.
A function suitable as callback to validate callback based errors. The error is
validated using `assert.throws(() => { throw error; }, validator)`. If the
returned function has not been called exactly `exact` number of times when the
test is complete, then the test will fail.
### `expectWarning(name[, expected[, code]])`
@@ -974,6 +947,7 @@ See [the WPT tests README][] for details.
[&lt;ArrayBufferView>]: https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView
[&lt;Buffer>]: https://nodejs.org/api/buffer.html#buffer_class_buffer
[&lt;BufferSource>]: https://developer.mozilla.org/en-US/docs/Web/API/BufferSource
[&lt;Error>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
[&lt;Function>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
[&lt;Object>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
[&lt;RegExp>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
+7 -77
View File
@@ -526,92 +526,22 @@ function expectWarning(nameOrMap, expected, code) {
}
}
class Comparison {
constructor(obj, keys) {
for (const key of keys) {
if (key in obj)
this[key] = obj[key];
}
}
}
// Useful for testing expected internal/error objects
function expectsError(fn, settings, exact) {
if (typeof fn !== 'function') {
exact = settings;
settings = fn;
fn = undefined;
}
function innerFn(error) {
if (arguments.length !== 1) {
function expectsError(validator, exact) {
return mustCall((...args) => {
if (args.length !== 1) {
// Do not use `assert.strictEqual()` to prevent `util.inspect` from
// always being called.
assert.fail(`Expected one argument, got ${util.inspect(arguments)}`);
assert.fail(`Expected one argument, got ${util.inspect(args)}`);
}
const error = args.pop();
const descriptor = Object.getOwnPropertyDescriptor(error, 'message');
// The error message should be non-enumerable
assert.strictEqual(descriptor.enumerable, false);
let innerSettings = settings;
if ('type' in settings) {
const type = settings.type;
if (type !== Error && !Error.isPrototypeOf(type)) {
throw new TypeError('`settings.type` must inherit from `Error`');
}
let constructor = error.constructor;
if (constructor.name === 'NodeError' && type.name !== 'NodeError') {
constructor = Object.getPrototypeOf(error.constructor);
}
// Add the `type` to the error to properly compare and visualize it.
if (!('type' in error))
error.type = constructor;
}
if ('message' in settings &&
typeof settings.message === 'object' &&
settings.message.test(error.message)) {
// Make a copy so we are able to modify the settings.
innerSettings = Object.create(
settings, Object.getOwnPropertyDescriptors(settings));
// Visualize the message as identical in case of other errors.
innerSettings.message = error.message;
}
// Check all error properties.
const keys = Object.keys(settings);
for (const key of keys) {
if (!util.isDeepStrictEqual(error[key], innerSettings[key])) {
// Create placeholder objects to create a nice output.
const a = new Comparison(error, keys);
const b = new Comparison(innerSettings, keys);
const tmpLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
const err = new assert.AssertionError({
actual: a,
expected: b,
operator: 'strictEqual',
stackStartFn: assert.throws
});
Error.stackTraceLimit = tmpLimit;
throw new assert.AssertionError({
actual: error,
expected: settings,
operator: 'common.expectsError',
message: err.message
});
}
}
assert.throws(() => { throw error; }, validator);
return true;
}
if (fn) {
assert.throws(fn, innerFn);
return;
}
return mustCall(innerFn, exact);
}, exact);
}
const suffix = 'This is caused by either a bug in Node.js ' +
+10 -9
View File
@@ -4,8 +4,9 @@
// This test ensures that the type checking of ModuleMap throws
// errors appropriately
const common = require('../common');
require('../common');
const assert = require('assert');
const { URL } = require('url');
const { Loader } = require('internal/modules/esm/loader');
const ModuleMap = require('internal/modules/esm/module_map');
@@ -20,41 +21,41 @@ const moduleMap = new ModuleMap();
const moduleJob = new ModuleJob(loader, stubModule.module,
() => new Promise(() => {}));
common.expectsError(
assert.throws(
() => moduleMap.get(1),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "url" argument must be of type string. Received type number' +
' (1)'
}
);
common.expectsError(
assert.throws(
() => moduleMap.set(1, moduleJob),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "url" argument must be of type string. Received type number' +
' (1)'
}
);
common.expectsError(
assert.throws(
() => moduleMap.set('somestring', 'notamodulejob'),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "job" argument must be an instance of ModuleJob. ' +
"Received type string ('notamodulejob')"
}
);
common.expectsError(
assert.throws(
() => moduleMap.has(1),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "url" argument must be of type string. Received type number' +
' (1)'
}
+1 -1
View File
@@ -11,7 +11,7 @@ const {
} = require('internal/modules/esm/resolve');
assert.throws(
() => resolve('target'),
() => resolve('target', undefined),
{
code: 'ERR_MODULE_NOT_FOUND',
name: 'Error',
+2 -2
View File
@@ -86,11 +86,11 @@ assert.throws(() => {
}
// Test paths option validation
common.expectsError(() => {
assert.throws(() => {
require.resolve('.\\three.js', { paths: 'foo' })
}, {
code: 'ERR_INVALID_OPT_VALUE',
type: TypeError,
name: 'TypeError',
});
// Verify that the default require.resolve() is used for empty options.
+5 -5
View File
@@ -1,5 +1,5 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
const dnsPromises = require('dns').promises;
@@ -7,11 +7,11 @@ const dnsPromises = require('dns').promises;
// Error when rrtype is invalid.
{
const rrtype = 'DUMMY';
common.expectsError(
assert.throws(
() => dnsPromises.resolve('example.org', rrtype),
{
code: 'ERR_INVALID_OPT_VALUE',
type: TypeError,
name: 'TypeError',
message: `The value "${rrtype}" is invalid for option "rrtype"`
}
);
@@ -20,11 +20,11 @@ const dnsPromises = require('dns').promises;
// Error when rrtype is a number.
{
const rrtype = 0;
common.expectsError(
assert.throws(
() => dnsPromises.resolve('example.org', rrtype),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "rrtype" argument must be of type string. ' +
`Received type ${typeof rrtype} (${rrtype})`
}
+3 -3
View File
@@ -69,21 +69,21 @@ assert.throws(() => {
}
));
common.expectsError(
assert.throws(
() => test_error.throwErrorCode(),
{
code: 'ERR_TEST_CODE',
message: 'Error [error]'
});
common.expectsError(
assert.throws(
() => test_error.throwRangeErrorCode(),
{
code: 'ERR_TEST_CODE',
message: 'RangeError [range error]'
});
common.expectsError(
assert.throws(
() => test_error.throwTypeErrorCode(),
{
code: 'ERR_TEST_CODE',
+2 -2
View File
@@ -67,8 +67,8 @@ assert.strictEqual(derefItemWasCalled, true,
// Assert that wrapping twice fails.
const x = {};
test_general.wrap(x);
common.expectsError(() => test_general.wrap(x),
{ type: Error, message: 'Invalid argument' });
assert.throws(() => test_general.wrap(x),
{ name: 'Error', message: 'Invalid argument' });
// Ensure that wrapping, removing the wrap, and then wrapping again works.
const y = {};
@@ -13,12 +13,12 @@ test_general.addFinalizerOnly(finalized, callback);
test_general.addFinalizerOnly(finalized, callback);
// Ensure attached items cannot be retrieved.
common.expectsError(() => test_general.unwrap(finalized),
{ type: Error, message: 'Invalid argument' });
assert.throws(() => test_general.unwrap(finalized),
{ name: 'Error', message: 'Invalid argument' });
// Ensure attached items cannot be removed.
common.expectsError(() => test_general.removeWrap(finalized),
{ type: Error, message: 'Invalid argument' });
assert.throws(() => test_general.removeWrap(finalized),
{ name: 'Error', message: 'Invalid argument' });
finalized = null;
global.gc();
+40 -40
View File
@@ -398,11 +398,11 @@ assert.throws(
{
// Verify that throws() and doesNotThrow() throw on non-functions.
const testBlockTypeError = (method, fn) => {
common.expectsError(
assert.throws(
() => method(fn),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "fn" argument must be of type function.' +
common.invalidArgTypeHelper(fn)
}
@@ -525,7 +525,7 @@ assert.throws(
// Test setting the limit to zero and that assert.strict works properly.
const tmpLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
common.expectsError(
assert.throws(
() => {
assert.ok(
typeof 123 === 'string'
@@ -533,7 +533,7 @@ assert.throws(
},
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n ' +
"assert.ok(\n typeof 123 === 'string'\n )\n"
}
@@ -699,32 +699,32 @@ assert.throws(
/* eslint-enable no-restricted-properties */
}
common.expectsError(
assert.throws(
() => assert.ok(null),
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
generatedMessage: true,
message: 'The expression evaluated to a falsy value:\n\n ' +
'assert.ok(null)\n'
}
);
common.expectsError(
assert.throws(
() => assert(typeof 123n === 'string'),
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
generatedMessage: true,
message: 'The expression evaluated to a falsy value:\n\n ' +
"assert(typeof 123n === 'string')\n"
}
);
common.expectsError(
assert.throws(
() => assert(false, Symbol('foo')),
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
generatedMessage: false,
message: 'Symbol(foo)'
}
@@ -740,20 +740,20 @@ common.expectsError(
(Buffer.from('test') instanceof Error)
);
}
common.expectsError(
assert.throws(
() => throwErr(),
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n ' +
"assert(\n (Buffer.from('test') instanceof Error)\n )\n"
}
);
common.expectsError(
assert.throws(
() => throwErr(),
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n ' +
"assert(\n (Buffer.from('test') instanceof Error)\n )\n"
}
@@ -761,7 +761,7 @@ common.expectsError(
fs.close = tmp;
}
common.expectsError(
assert.throws(
() => {
a(
(() => 'string')()
@@ -773,7 +773,7 @@ common.expectsError(
},
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n' +
' a(\n' +
' (() => \'string\')()\n' +
@@ -785,7 +785,7 @@ common.expectsError(
}
);
common.expectsError(
assert.throws(
() => {
a(
(() => 'string')()
@@ -797,7 +797,7 @@ common.expectsError(
},
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n' +
' a(\n' +
' (() => \'string\')()\n' +
@@ -810,7 +810,7 @@ common.expectsError(
);
/* eslint-disable indent */
common.expectsError(() => {
assert.throws(() => {
a((
() => 'string')() ===
123 instanceof
@@ -818,7 +818,7 @@ Buffer
);
}, {
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n' +
' a((\n' +
' () => \'string\')() ===\n' +
@@ -829,81 +829,81 @@ Buffer
);
/* eslint-enable indent */
common.expectsError(
assert.throws(
() => {
assert(true); assert(null, undefined);
},
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n ' +
'assert(null, undefined)\n'
}
);
common.expectsError(
assert.throws(
() => {
assert
.ok(null, undefined);
},
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n ' +
'ok(null, undefined)\n'
}
);
common.expectsError(
assert.throws(
// eslint-disable-next-line dot-notation, quotes
() => assert['ok']["apply"](null, [0]),
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n ' +
'assert[\'ok\']["apply"](null, [0])\n'
}
);
common.expectsError(
assert.throws(
() => {
const wrapper = (fn, value) => fn(value);
wrapper(assert, false);
},
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n fn(value)\n'
}
);
common.expectsError(
assert.throws(
() => assert.ok.call(null, 0),
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n ' +
'assert.ok.call(null, 0)\n',
generatedMessage: true
}
);
common.expectsError(
assert.throws(
() => assert.ok.call(null, 0, 'test'),
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'test',
generatedMessage: false
}
);
// Works in eval.
common.expectsError(
assert.throws(
() => new Function('assert', 'assert(1 === 2);')(assert),
{
code: 'ERR_ASSERTION',
type: assert.AssertionError,
constructor: assert.AssertionError,
message: 'The expression evaluated to a falsy value:\n\n assert(1 === 2)\n'
}
);
@@ -915,11 +915,11 @@ assert.throws(
}
);
common.expectsError(
assert.throws(
() => assert.throws(() => {}, 'Error message', 'message'),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "error" argument must be of type function or ' +
'an instance of Error, RegExp, or Object. Received type string ' +
"('Error message')"
@@ -1001,19 +1001,19 @@ common.expectsError(
}
);
common.expectsError(
assert.throws(
() => assert.throws(() => { throw new Error(); }, { foo: 'bar' }, 'foobar'),
{
type: assert.AssertionError,
constructor: assert.AssertionError,
code: 'ERR_ASSERTION',
message: 'foobar'
}
);
common.expectsError(
assert.throws(
() => a.doesNotThrow(() => { throw new Error(); }, { foo: 'bar' }),
{
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "expected" argument must be of type function or an ' +
'instance of RegExp. Received an instance of Object'
@@ -2,7 +2,8 @@
// This tests that AsyncResource throws an error if bad parameters are passed
const common = require('../common');
require('../common');
const assert = require('assert');
const async_hooks = require('async_hooks');
const { AsyncResource } = async_hooks;
@@ -11,30 +12,30 @@ async_hooks.createHook({
init() {}
}).enable();
common.expectsError(() => {
assert.throws(() => {
return new AsyncResource();
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
});
common.expectsError(() => {
assert.throws(() => {
new AsyncResource('');
}, {
code: 'ERR_ASYNC_TYPE',
type: TypeError,
name: 'TypeError',
});
common.expectsError(() => {
assert.throws(() => {
new AsyncResource('type', -4);
}, {
code: 'ERR_INVALID_ASYNC_ID',
type: RangeError,
name: 'RangeError',
});
common.expectsError(() => {
assert.throws(() => {
new AsyncResource('type', Math.PI);
}, {
code: 'ERR_INVALID_ASYNC_ID',
type: RangeError,
name: 'RangeError',
});
@@ -2,7 +2,8 @@
// This tests that AsyncHooks throws an error if bad parameters are passed.
const common = require('../common');
require('../common');
const assert = require('assert');
const async_hooks = require('async_hooks');
const non_function = 10;
@@ -13,11 +14,11 @@ typeErrorForFunction('destroy');
typeErrorForFunction('promiseResolve');
function typeErrorForFunction(functionName) {
common.expectsError(() => {
assert.throws(() => {
async_hooks.createHook({ [functionName]: non_function });
}, {
code: 'ERR_ASYNC_CALLBACK',
type: TypeError,
name: 'TypeError',
message: `hook.${functionName} must be a function`
});
}
+4 -3
View File
@@ -2,17 +2,18 @@
// This tests that using falsy values in createHook throws an error.
const common = require('../common');
require('../common');
const assert = require('assert');
const async_hooks = require('async_hooks');
for (const badArg of [0, 1, false, true, null, 'hello']) {
const hookNames = ['init', 'before', 'after', 'destroy', 'promiseResolve'];
for (const field of hookNames) {
common.expectsError(() => {
assert.throws(() => {
async_hooks.createHook({ [field]: badArg });
}, {
code: 'ERR_ASYNC_CALLBACK',
type: TypeError,
name: 'TypeError',
});
}
}
+25 -25
View File
@@ -81,20 +81,20 @@ Buffer(0);
const outOfRangeError = {
code: 'ERR_OUT_OF_RANGE',
type: RangeError
name: 'RangeError'
};
// Try to write a 0-length string beyond the end of b
common.expectsError(() => b.write('', 2048), outOfRangeError);
assert.throws(() => b.write('', 2048), outOfRangeError);
// Throw when writing to negative offset
common.expectsError(() => b.write('a', -1), outOfRangeError);
assert.throws(() => b.write('a', -1), outOfRangeError);
// Throw when writing past bounds from the pool
common.expectsError(() => b.write('a', 2048), outOfRangeError);
assert.throws(() => b.write('a', 2048), outOfRangeError);
// Throw when writing to negative offset
common.expectsError(() => b.write('a', -1), outOfRangeError);
assert.throws(() => b.write('a', -1), outOfRangeError);
// Try to copy 0 bytes worth of data into an empty buffer
b.copy(Buffer.alloc(0), 0, 0, 0);
@@ -793,31 +793,31 @@ assert.strictEqual(Buffer.from('13.37').length, 5);
Buffer.from(Buffer.allocUnsafe(0), 0, 0);
// issue GH-5587
common.expectsError(
assert.throws(
() => Buffer.alloc(8).writeFloatLE(0, 5),
outOfRangeError
);
common.expectsError(
assert.throws(
() => Buffer.alloc(16).writeDoubleLE(0, 9),
outOfRangeError
);
// Attempt to overflow buffers, similar to previous bug in array buffers
common.expectsError(
assert.throws(
() => Buffer.allocUnsafe(8).writeFloatLE(0.0, 0xffffffff),
outOfRangeError
);
common.expectsError(
assert.throws(
() => Buffer.allocUnsafe(8).writeFloatLE(0.0, 0xffffffff),
outOfRangeError
);
// Ensure negative values can't get past offset
common.expectsError(
assert.throws(
() => Buffer.allocUnsafe(8).writeFloatLE(0.0, -1),
outOfRangeError
);
common.expectsError(
assert.throws(
() => Buffer.allocUnsafe(8).writeFloatLE(0.0, -1),
outOfRangeError
);
@@ -917,11 +917,11 @@ common.expectsError(
// Regression test for https://github.com/nodejs/node-v0.x-archive/issues/5482:
// should throw but not assert in C++ land.
common.expectsError(
assert.throws(
() => Buffer.from('', 'buffer'),
{
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
name: 'TypeError',
message: 'Unknown encoding: buffer'
}
);
@@ -962,11 +962,11 @@ Buffer.poolSize = 0;
assert(Buffer.allocUnsafe(1).parent instanceof ArrayBuffer);
Buffer.poolSize = ps;
common.expectsError(
assert.throws(
() => Buffer.allocUnsafe(10).copy(),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "target" argument must be an instance of Buffer or ' +
'Uint8Array. Received undefined'
});
@@ -1007,14 +1007,14 @@ assert.strictEqual(SlowBuffer.prototype.offset, undefined);
{
const errMsg = common.expectsError({
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
type: RangeError,
name: 'RangeError',
message: '"offset" is outside of buffer bounds'
});
assert.throws(() => Buffer.from(new ArrayBuffer(0), -1 >>> 0), errMsg);
}
// ParseArrayIndex() should reject values that don't fit in a 32 bits size_t.
common.expectsError(() => {
assert.throws(() => {
const a = Buffer.alloc(1);
const b = Buffer.alloc(1);
a.copy(b, 0, 0x100000000, 0x100000001);
@@ -1047,30 +1047,30 @@ assert.strictEqual(Buffer.prototype.toLocaleString, Buffer.prototype.toString);
assert.strictEqual(buf.toLocaleString(), buf.toString());
}
common.expectsError(() => {
assert.throws(() => {
Buffer.alloc(0x1000, 'This is not correctly encoded', 'hex');
}, {
code: 'ERR_INVALID_ARG_VALUE',
type: TypeError
name: 'TypeError'
});
common.expectsError(() => {
assert.throws(() => {
Buffer.alloc(0x1000, 'c', 'hex');
}, {
code: 'ERR_INVALID_ARG_VALUE',
type: TypeError
name: 'TypeError'
});
common.expectsError(() => {
assert.throws(() => {
Buffer.alloc(1, Buffer.alloc(0));
}, {
code: 'ERR_INVALID_ARG_VALUE',
type: TypeError
name: 'TypeError'
});
common.expectsError(() => {
assert.throws(() => {
Buffer.alloc(40, 'x', 20);
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
name: 'TypeError'
});
+2 -2
View File
@@ -11,11 +11,11 @@ const vm = require('vm');
[{}, 'latin1'],
[]
].forEach((args) => {
common.expectsError(
assert.throws(
() => Buffer.byteLength(...args),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "string" argument must be of type string or an instance ' +
'of Buffer or ArrayBuffer.' +
common.invalidArgTypeHelper(args[0])
+3 -3
View File
@@ -1,6 +1,6 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
const a = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
@@ -86,9 +86,9 @@ assert.throws(() => a.compare(b, -1), oor);
assert.throws(() => a.compare(b, 0, Infinity), oor);
assert.throws(() => a.compare(b, 0, 1, -1), oor);
assert.throws(() => a.compare(b, -Infinity, Infinity), oor);
common.expectsError(() => a.compare(), {
assert.throws(() => a.compare(), {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "target" argument must be an instance of ' +
'Buffer or Uint8Array. Received undefined'
});
+3 -3
View File
@@ -1,6 +1,6 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
const b = Buffer.alloc(1, 'a');
@@ -39,9 +39,9 @@ assert.throws(() => Buffer.compare('abc', Buffer.alloc(1)), {
"Received type string ('abc')"
});
common.expectsError(() => Buffer.alloc(1).compare('abc'), {
assert.throws(() => Buffer.alloc(1).compare('abc'), {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "target" argument must be an instance of ' +
"Buffer or Uint8Array. Received type string ('abc')"
});
+5 -5
View File
@@ -1,6 +1,6 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
const b = Buffer.allocUnsafe(1024);
@@ -108,11 +108,11 @@ bb.fill('hello crazy world');
b.copy(c, 0, 100, 10);
// Copy throws at negative sourceStart
common.expectsError(
assert.throws(
() => Buffer.allocUnsafe(5).copy(Buffer.allocUnsafe(5), 0, -1),
{
code: 'ERR_OUT_OF_RANGE',
type: RangeError,
name: 'RangeError',
message: 'The value of "sourceStart" is out of range. ' +
'It must be >= 0. Received -1'
}
@@ -129,11 +129,11 @@ common.expectsError(
}
// Throw with negative sourceEnd
common.expectsError(
assert.throws(
() => b.copy(c, 0, 0, -1),
{
code: 'ERR_OUT_OF_RANGE',
type: RangeError,
name: 'RangeError',
message: 'The value of "sourceEnd" is out of range. ' +
'It must be >= 0. Received -1'
}
+3 -3
View File
@@ -1,6 +1,6 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
const b = Buffer.from('abcdf');
@@ -14,11 +14,11 @@ assert.ok(!d.equals(e));
assert.ok(d.equals(d));
assert.ok(d.equals(new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65])));
common.expectsError(
assert.throws(
() => Buffer.alloc(1).equals('abc'),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "otherBuffer" argument must be an instance of ' +
"Buffer or Uint8Array. Received type string ('abc')"
}
+17 -17
View File
@@ -112,22 +112,22 @@ testBufs('c8a26161', 8, 1, 'hex');
testBufs('61c8b462c8b563c8b6', 4, 1, 'hex');
testBufs('61c8b462c8b563c8b6', 12, 1, 'hex');
common.expectsError(() => {
assert.throws(() => {
const buf = Buffer.allocUnsafe(SIZE);
buf.fill('yKJh', 'hex');
}, {
code: 'ERR_INVALID_ARG_VALUE',
type: TypeError
name: 'TypeError'
});
common.expectsError(() => {
assert.throws(() => {
const buf = Buffer.allocUnsafe(SIZE);
buf.fill('\u0222', 'hex');
}, {
code: 'ERR_INVALID_ARG_VALUE',
type: TypeError
name: 'TypeError'
});
// BASE64
@@ -172,17 +172,17 @@ deepStrictEqualValues(genBuffer(4, [hexBufFill, 1, 1]), [0, 0, 0, 0]);
['', 0, buf1.length + 1],
['', 1, -1],
].forEach((args) => {
common.expectsError(
assert.throws(
() => buf1.fill(...args),
{ code: 'ERR_OUT_OF_RANGE' }
);
});
common.expectsError(
assert.throws(
() => buf1.fill('a', 0, buf1.length, 'node rocks!'),
{
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
name: 'TypeError',
message: 'Unknown encoding: node rocks!'
}
);
@@ -191,7 +191,7 @@ common.expectsError(
['a', 0, 0, NaN],
['a', 0, 0, false]
].forEach((args) => {
common.expectsError(
assert.throws(
() => buf1.fill(...args),
{
code: 'ERR_INVALID_ARG_TYPE',
@@ -201,11 +201,11 @@ common.expectsError(
);
});
common.expectsError(
assert.throws(
() => buf1.fill('a', 0, 0, 'foo'),
{
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
name: 'TypeError',
message: 'Unknown encoding: foo'
}
);
@@ -275,10 +275,10 @@ function testBufs(string, offset, length, encoding) {
}
// Make sure these throw.
common.expectsError(
assert.throws(
() => Buffer.allocUnsafe(8).fill('a', -1),
{ code: 'ERR_OUT_OF_RANGE' });
common.expectsError(
assert.throws(
() => Buffer.allocUnsafe(8).fill('a', 0, 9),
{ code: 'ERR_OUT_OF_RANGE' });
@@ -335,7 +335,7 @@ assert.throws(
// Make sure "end" is properly checked, even if it's magically mangled using
// Symbol.toPrimitive.
{
common.expectsError(() => {
assert.throws(() => {
const end = {
[Symbol.toPrimitive]() {
return 1;
@@ -357,7 +357,7 @@ assert.throws(
);
// Test that bypassing 'length' won't cause an abort.
common.expectsError(() => {
assert.throws(() => {
const buf = Buffer.from('w00t');
Object.defineProperty(buf, 'length', {
value: 1337,
@@ -366,7 +366,7 @@ common.expectsError(() => {
buf.fill('');
}, {
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
type: RangeError,
name: 'RangeError',
message: 'Attempt to access memory outside buffer bounds'
});
@@ -405,11 +405,11 @@ assert.strictEqual(
Buffer.allocUnsafeSlow(16).fill('Љ', 'utf8').toString('utf8'),
'Љ'.repeat(8));
common.expectsError(() => {
assert.throws(() => {
const buf = Buffer.from('a'.repeat(1000));
buf.fill('This is not correctly encoded', 'hex');
}, {
code: 'ERR_INVALID_ARG_VALUE',
type: TypeError
name: 'TypeError'
});
+2 -2
View File
@@ -277,11 +277,11 @@ for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
{},
[]
].forEach((val) => {
common.expectsError(
assert.throws(
() => b.includes(val),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "value" argument must be one of type number or string ' +
'or an instance of Buffer or Uint8Array.' +
common.invalidArgTypeHelper(val)
+2 -2
View File
@@ -352,11 +352,11 @@ assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1);
{},
[]
].forEach((val) => {
common.expectsError(
assert.throws(
() => b.indexOf(val),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "value" argument must be one of type number or string ' +
'or an instance of Buffer or Uint8Array.' +
common.invalidArgTypeHelper(val)
+4 -3
View File
@@ -1,10 +1,11 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
common.expectsError(() => new Buffer(42, 'utf8'), {
assert.throws(() => new Buffer(42, 'utf8'), {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "string" argument must be of type string. Received type ' +
'number (42)'
});
@@ -1,14 +1,14 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
const { SlowBuffer } = require('buffer');
const msg = common.expectsError({
const msg = {
code: 'ERR_INVALID_OPT_VALUE',
type: RangeError,
name: 'RangeError',
message: /^The value "[^"]*" is invalid for option "size"$/
}, 20);
};
// Test that negative Buffer length inputs throw errors.
+4 -4
View File
@@ -1,16 +1,16 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
const buffer = require('buffer');
const SlowBuffer = buffer.SlowBuffer;
const kMaxLength = buffer.kMaxLength;
const bufferMaxSizeMsg = common.expectsError({
const bufferMaxSizeMsg = {
code: 'ERR_INVALID_OPT_VALUE',
type: RangeError,
name: 'RangeError',
message: /^The value "[^"]*" is invalid for option "size"$/
}, 12);
};
assert.throws(() => Buffer((-1 >>> 0) + 1), bufferMaxSizeMsg);
assert.throws(() => SlowBuffer((-1 >>> 0) + 1), bufferMaxSizeMsg);
+2 -2
View File
@@ -1,5 +1,5 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
// Testing basic buffer read functions
@@ -7,7 +7,7 @@ const buf = Buffer.from([0xa4, 0xfd, 0x48, 0xea, 0xcf, 0xff, 0xd9, 0x01, 0xde]);
function read(buff, funx, args, expected) {
assert.strictEqual(buff[funx](...args), expected);
common.expectsError(
assert.throws(
() => buff[funx](-1, args[1]),
{ code: 'ERR_OUT_OF_RANGE' }
);
+5 -5
View File
@@ -1,6 +1,6 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
const rangeBuffer = Buffer.from('abc');
@@ -84,17 +84,17 @@ assert.strictEqual(rangeBuffer.toString({ toString: function() {
} }), 'abc');
// Try toString() with 0 and null as the encoding
common.expectsError(() => {
assert.throws(() => {
rangeBuffer.toString(0, 1, 2);
}, {
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
name: 'TypeError',
message: 'Unknown encoding: 0'
});
common.expectsError(() => {
assert.throws(() => {
rangeBuffer.toString(null, 1, 2);
}, {
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
name: 'TypeError',
message: 'Unknown encoding: null'
});
@@ -1,5 +1,5 @@
'use strict';
const common = require('../common');
require('../common');
// This test ensures that Node.js throws a RangeError when trying to convert a
// gigantic buffer into a string.
@@ -9,11 +9,11 @@ const assert = require('assert');
const SlowBuffer = require('buffer').SlowBuffer;
const len = 1422561062959;
const message = common.expectsError({
const message = {
code: 'ERR_INVALID_OPT_VALUE',
type: RangeError,
name: 'RangeError',
message: /^The value "[^"]*" is invalid for option "size"$/
}, 5);
};
assert.throws(() => Buffer(len).toString('utf8'), message);
assert.throws(() => SlowBuffer(len).toString('utf8'), message);
assert.throws(() => Buffer.alloc(len).toString('utf8'), message);
+1 -1
View File
@@ -29,7 +29,7 @@ for (let i = 1; i < 10; i++) {
const encoding = String(i).repeat(i);
const error = common.expectsError({
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
name: 'TypeError',
message: `Unknown encoding: ${encoding}`
});
assert.ok(!Buffer.isEncoding(encoding));
+1 -1
View File
@@ -66,7 +66,7 @@ for (let i = 1; i < 10; i++) {
const encoding = String(i).repeat(i);
const error = common.expectsError({
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
name: 'TypeError',
message: `Unknown encoding: ${encoding}`
});
+4 -4
View File
@@ -2,14 +2,14 @@
// Tests to verify signed integers are correctly written
const common = require('../common');
require('../common');
const assert = require('assert');
const errorOutOfBounds = common.expectsError({
const errorOutOfBounds = {
code: 'ERR_OUT_OF_RANGE',
type: RangeError,
name: 'RangeError',
message: new RegExp('^The value of "value" is out of range\\. ' +
'It must be >= -\\d+ and <= \\d+\\. Received .+$')
}, 10);
};
// Test 8 bit
{
+3 -3
View File
@@ -70,16 +70,16 @@ dns.lookup('::1', common.mustCall((error, result, addressType) => {
].forEach((val) => {
const err = {
code: 'ERR_INVALID_OPT_VALUE',
type: TypeError,
name: 'TypeError',
message: `The value "${val}" is invalid for option "rrtype"`
};
common.expectsError(
assert.throws(
() => dns.resolve('www.google.com', val),
err
);
common.expectsError(() => dnsPromises.resolve('www.google.com', val), err);
assert.throws(() => dnsPromises.resolve('www.google.com', val), err);
});
// Windows doesn't usually have an entry for localhost 127.0.0.1 in
@@ -6,7 +6,7 @@ const { once } = require('events');
if (process.argv[2] !== 'child') {
for (const value of [null, 42, Infinity, 'foo']) {
common.expectsError(() => {
assert.throws(() => {
child_process.spawn(process.execPath, [], { serialization: value });
}, {
code: 'ERR_INVALID_OPT_VALUE',
+10 -10
View File
@@ -10,11 +10,11 @@ assert.strictEqual(typeof ChildProcess, 'function');
const child = new ChildProcess();
[undefined, null, 'foo', 0, 1, NaN, true, false].forEach((options) => {
common.expectsError(() => {
assert.throws(() => {
child.spawn(options);
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "options" argument must be of type object.' +
`${common.invalidArgTypeHelper(options)}`
});
@@ -26,11 +26,11 @@ assert.strictEqual(typeof ChildProcess, 'function');
const child = new ChildProcess();
[undefined, null, 0, 1, NaN, true, false, {}].forEach((file) => {
common.expectsError(() => {
assert.throws(() => {
child.spawn({ file });
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "options.file" property must be of type string.' +
`${common.invalidArgTypeHelper(file)}`
});
@@ -42,11 +42,11 @@ assert.strictEqual(typeof ChildProcess, 'function');
const child = new ChildProcess();
[null, 0, 1, NaN, true, false, {}, 'foo'].forEach((envPairs) => {
common.expectsError(() => {
assert.throws(() => {
child.spawn({ envPairs, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "options.envPairs" property must be an instance of Array.' +
common.invalidArgTypeHelper(envPairs)
});
@@ -58,11 +58,11 @@ assert.strictEqual(typeof ChildProcess, 'function');
const child = new ChildProcess();
[null, 0, 1, NaN, true, false, {}, 'foo'].forEach((args) => {
common.expectsError(() => {
assert.throws(() => {
child.spawn({ file: 'foo', args });
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "options.args" property must be an instance of Array.' +
common.invalidArgTypeHelper(args)
});
@@ -82,9 +82,9 @@ assert.strictEqual(child.hasOwnProperty('pid'), true);
assert(Number.isInteger(child.pid));
// Try killing with invalid signal
common.expectsError(
assert.throws(
() => { child.kill('foo'); },
{ code: 'ERR_UNKNOWN_SIGNAL', type: TypeError }
{ code: 'ERR_UNKNOWN_SIGNAL', name: 'TypeError' }
);
assert.strictEqual(child.kill(), true);
@@ -22,9 +22,9 @@ const expectedEnv = { foo: 'bar' };
Symbol('t')
];
invalidModulePath.forEach((modulePath) => {
common.expectsError(() => fork(modulePath), {
assert.throws(() => fork(modulePath), {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: /^The "modulePath" argument must be of type string/
});
});
@@ -49,13 +49,13 @@ const expectedEnv = { foo: 'bar' };
Symbol('t')
];
invalidSecondArgs.forEach((arg) => {
common.expectsError(
assert.throws(
() => {
fork(fixtures.path('child-process-echo-options.js'), arg);
},
{
code: 'ERR_INVALID_ARG_VALUE',
type: TypeError
name: 'TypeError'
}
);
});
@@ -92,13 +92,13 @@ const expectedEnv = { foo: 'bar' };
Symbol('t')
];
invalidThirdArgs.forEach((arg) => {
common.expectsError(
assert.throws(
() => {
fork(fixtures.path('child-process-echo-options.js'), [], arg);
},
{
code: 'ERR_INVALID_ARG_VALUE',
type: TypeError
name: 'TypeError'
}
);
});
@@ -13,9 +13,9 @@ const childScript = fixtures.path('child-process-spawn-node');
const malFormedOpts = { stdio: '33' };
const payload = { hello: 'world' };
common.expectsError(
assert.throws(
() => fork(childScript, malFormedOpts),
{ code: 'ERR_INVALID_OPT_VALUE', type: TypeError });
{ code: 'ERR_INVALID_OPT_VALUE', name: 'TypeError' });
function test(stringVariant) {
const child = fork(childScript, { stdio: stringVariant });
@@ -19,9 +19,9 @@ if (process.argv[2] === 'child') {
process.send(data);
});
} else {
common.expectsError(
assert.throws(
() => cp.fork(__filename, { stdio: ['pipe', 'pipe', 'pipe', 'pipe'] }),
{ code: 'ERR_CHILD_PROCESS_IPC_REQUIRED', type: Error });
{ code: 'ERR_CHILD_PROCESS_IPC_REQUIRED', name: 'Error' });
let ipc = '';
let stderr = '';
@@ -12,7 +12,7 @@ child.on('close', common.mustCall((code, signal) => {
assert.strictEqual(signal, null);
const testError = common.expectsError({
type: Error,
name: 'Error',
message: 'Channel closed',
code: 'ERR_IPC_CHANNEL_CLOSED'
}, 2);
@@ -5,9 +5,9 @@ const assert = require('assert');
const cp = require('child_process');
function fail(proc, args) {
common.expectsError(() => {
assert.throws(() => {
proc.send.apply(proc, args);
}, { code: 'ERR_INVALID_ARG_TYPE', type: TypeError });
}, { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError' });
}
let target = process;
@@ -29,11 +29,15 @@ const invalidcmd = 'hopefully_you_dont_have_this_on_your_machine';
const empty = fixtures.path('empty.js');
const invalidArgValueError =
common.expectsError({ code: 'ERR_INVALID_ARG_VALUE', type: TypeError }, 14);
const invalidArgValueError = {
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError'
};
const invalidArgTypeError =
common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError }, 11);
const invalidArgTypeError = {
code: 'ERR_INVALID_ARG_TYPE',
name: 'TypeError'
};
assert.throws(function() {
spawn(invalidcmd, 'this is not an array');
@@ -76,9 +76,9 @@ let options = {
input: 1234
};
common.expectsError(
assert.throws(
() => spawnSync('cat', [], options),
{ code: 'ERR_INVALID_ARG_TYPE', type: TypeError });
{ code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError' });
options = {
input: 'hello world'
@@ -29,9 +29,9 @@ if (process.argv[2] === 'child') {
}
// Verify that an error is thrown for unknown signals.
common.expectsError(() => {
assert.throws(() => {
spawn('SIG_NOT_A_REAL_SIGNAL');
}, { code: 'ERR_UNKNOWN_SIGNAL', type: TypeError });
}, { code: 'ERR_UNKNOWN_SIGNAL', name: 'TypeError' });
// Verify that the default kill signal is SIGTERM.
{
@@ -6,12 +6,8 @@ const signals = require('os').constants.signals;
const rootUser = common.isWindows ? false :
common.isIBMi ? true : process.getuid() === 0;
const invalidArgTypeError = common.expectsError(
{ code: 'ERR_INVALID_ARG_TYPE', type: TypeError },
common.isWindows || rootUser ? 42 : 62);
const invalidRangeError =
common.expectsError({ code: 'ERR_OUT_OF_RANGE', type: RangeError }, 20);
const invalidArgTypeError = { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError' };
const invalidRangeError = { code: 'ERR_OUT_OF_RANGE', name: 'RangeError' };
function pass(option, value) {
// Run the command with the specified option. Since it's not a real command,
@@ -189,8 +185,7 @@ if (!common.isWindows) {
{
// Validate the killSignal option
const unknownSignalErr =
common.expectsError({ code: 'ERR_UNKNOWN_SIGNAL', type: TypeError }, 17);
const unknownSignalErr = { code: 'ERR_UNKNOWN_SIGNAL', name: 'TypeError' };
pass('killSignal', undefined);
pass('killSignal', null);
+2 -2
View File
@@ -66,12 +66,12 @@ const { spawn } = require('child_process');
}
// Assert only one IPC pipe allowed.
common.expectsError(
assert.throws(
() => {
spawn(
...common.pwdCommand,
{ stdio: ['pipe', 'pipe', 'pipe', 'ipc', 'ipc'] }
);
},
{ code: 'ERR_IPC_ONE_PIPE', type: Error }
{ code: 'ERR_IPC_ONE_PIPE', name: 'Error' }
);
@@ -5,13 +5,13 @@ const common = require('../common');
const assert = require('assert');
const getValidStdio = require('internal/child_process').getValidStdio;
const expectedError = { code: 'ERR_INVALID_OPT_VALUE', type: TypeError };
const expectedError = { code: 'ERR_INVALID_OPT_VALUE', name: 'TypeError' };
// Should throw if string and not ignore, pipe, or inherit
common.expectsError(() => getValidStdio('foo'), expectedError);
assert.throws(() => getValidStdio('foo'), expectedError);
// Should throw if not a string or array
common.expectsError(() => getValidStdio(600), expectedError);
assert.throws(() => getValidStdio(600), expectedError);
// Should populate stdio with undefined if len < 3
{
@@ -25,22 +25,22 @@ common.expectsError(() => getValidStdio(600), expectedError);
// Should throw if stdio has ipc and sync is true
const stdio2 = ['ipc', 'ipc', 'ipc'];
common.expectsError(() => getValidStdio(stdio2, true),
{ code: 'ERR_IPC_SYNC_FORK', type: Error }
assert.throws(() => getValidStdio(stdio2, true),
{ code: 'ERR_IPC_SYNC_FORK', name: 'Error' }
);
// Should throw if stdio is not a valid input
{
const stdio = ['foo'];
common.expectsError(() => getValidStdio(stdio, false),
{ code: 'ERR_INVALID_SYNC_FORK_INPUT', type: TypeError }
assert.throws(() => getValidStdio(stdio, false),
{ code: 'ERR_INVALID_SYNC_FORK_INPUT', name: 'TypeError' }
);
}
// Should throw if stdio is not a valid option
{
const stdio = [{ foo: 'bar' }];
common.expectsError(() => getValidStdio(stdio), expectedError);
assert.throws(() => getValidStdio(stdio), expectedError);
}
if (common.isMainThread) {
+1 -1
View File
@@ -63,7 +63,7 @@ assert.throws(function() {
}, /^TypeError: Invalid minimum value: \/foo\/$/);
// assert.fail() tests
common.expectsError(
assert.throws(
() => { assert.fail('fhqwhgads'); },
{
code: 'ERR_ASSERTION',
+4 -4
View File
@@ -43,17 +43,17 @@ assert.ok(!({} instanceof Console));
// Make sure that the Console constructor throws
// when not given a writable stream instance.
common.expectsError(
assert.throws(
() => { new Console(); },
{
code: 'ERR_CONSOLE_WRITABLE_STREAM',
type: TypeError,
name: 'TypeError',
message: /stdout/
}
);
// Console constructor should throw if stderr exists but is not writable.
common.expectsError(
assert.throws(
() => {
out.write = () => {};
err.write = undefined;
@@ -61,7 +61,7 @@ common.expectsError(
},
{
code: 'ERR_CONSOLE_WRITABLE_STREAM',
type: TypeError,
name: 'TypeError',
message: /stderr/
}
);
@@ -1,10 +1,11 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const { Console } = require('console');
const { Writable } = require('stream');
for (const method of ['dir', 'log', 'warn']) {
common.expectsError(() => {
assert.throws(() => {
const out = new Writable({
write: common.mustCall(function write(...args) {
// Exceeds call stack.
+2 -2
View File
@@ -1,6 +1,6 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
const { Console } = require('console');
@@ -23,7 +23,7 @@ function test(data, only, expected) {
);
}
common.expectsError(() => console.table([], false), {
assert.throws(() => console.table([], false), {
code: 'ERR_INVALID_ARG_TYPE',
});
+18 -18
View File
@@ -237,17 +237,17 @@ for (const test of TEST_CASES) {
// throw.
{
for (const length of [0, 1, 2, 6, 9, 10, 11, 17]) {
common.expectsError(() => {
assert.throws(() => {
const decrypt = crypto.createDecipheriv('aes-128-gcm',
'FxLKsqdmv0E9xrQh',
'qkuZpJWCewa6Szih');
decrypt.setAuthTag(Buffer.from('1'.repeat(length)));
}, {
type: Error,
name: 'Error',
message: `Invalid authentication tag length: ${length}`
});
common.expectsError(() => {
assert.throws(() => {
crypto.createCipheriv('aes-256-gcm',
'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8',
'qkuZpJWCewa6Szih',
@@ -255,11 +255,11 @@ for (const test of TEST_CASES) {
authTagLength: length
});
}, {
type: Error,
name: 'Error',
message: `Invalid authentication tag length: ${length}`
});
common.expectsError(() => {
assert.throws(() => {
crypto.createDecipheriv('aes-256-gcm',
'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8',
'qkuZpJWCewa6Szih',
@@ -267,7 +267,7 @@ for (const test of TEST_CASES) {
authTagLength: length
});
}, {
type: Error,
name: 'Error',
message: `Invalid authentication tag length: ${length}`
});
}
@@ -298,11 +298,11 @@ for (const test of TEST_CASES) {
authTagLength: 8
});
common.expectsError(() => {
assert.throws(() => {
// This tag would normally be allowed.
decipher.setAuthTag(Buffer.from('1'.repeat(12)));
}, {
type: Error,
name: 'Error',
message: 'Invalid authentication tag length: 12'
});
@@ -319,7 +319,7 @@ for (const test of TEST_CASES) {
// authentication tag length has been specified.
{
for (const authTagLength of [-1, true, false, NaN, 5.5]) {
common.expectsError(() => {
assert.throws(() => {
crypto.createCipheriv('aes-256-ccm',
'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8',
'qkuZpJWCewa6S',
@@ -327,13 +327,13 @@ for (const test of TEST_CASES) {
authTagLength
});
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${authTagLength}" is invalid for option ` +
'"authTagLength"'
});
common.expectsError(() => {
assert.throws(() => {
crypto.createDecipheriv('aes-256-ccm',
'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8',
'qkuZpJWCewa6S',
@@ -341,26 +341,26 @@ for (const test of TEST_CASES) {
authTagLength
});
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${authTagLength}" is invalid for option ` +
'"authTagLength"'
});
if (!common.hasFipsCrypto) {
common.expectsError(() => {
assert.throws(() => {
crypto.createCipher('aes-256-ccm', 'bad password', { authTagLength });
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${authTagLength}" is invalid for option ` +
'"authTagLength"'
});
common.expectsError(() => {
assert.throws(() => {
crypto.createDecipher('aes-256-ccm', 'bad password', { authTagLength });
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${authTagLength}" is invalid for option ` +
'"authTagLength"'
@@ -448,10 +448,10 @@ for (const test of TEST_CASES) {
});
for (const plaintextLength of [-1, true, false, NaN, 5.5]) {
common.expectsError(() => {
assert.throws(() => {
cipher.setAAD(Buffer.from('0123456789', 'hex'), { plaintextLength });
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${plaintextLength}" is invalid for option ` +
'"plaintextLength"'
+2 -2
View File
@@ -572,11 +572,11 @@ testCipher4(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678'));
// update() should only take buffers / strings
common.expectsError(
assert.throws(
() => crypto.createHash('sha1').update({ foo: 'bar' }),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
name: 'TypeError'
});
+22 -22
View File
@@ -85,38 +85,38 @@ testCipher2(Buffer.from('0123456789abcdef'));
assert(instance instanceof Cipher, 'Cipher is expected to return a new ' +
'instance when called without `new`');
common.expectsError(
assert.throws(
() => crypto.createCipher(null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "cipher" argument must be of type string. ' +
'Received null'
});
common.expectsError(
assert.throws(
() => crypto.createCipher('aes-256-cbc', null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "password" argument must be of type string or an instance' +
' of Buffer, TypedArray, or DataView. Received null'
});
common.expectsError(
assert.throws(
() => crypto.createCipher('aes-256-cbc', 'secret').update(null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "data" argument must be of type string or an instance' +
' of Buffer, TypedArray, or DataView. Received null'
});
common.expectsError(
assert.throws(
() => crypto.createCipher('aes-256-cbc', 'secret').setAAD(null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "buffer" argument must be an instance' +
' of Buffer, TypedArray, or DataView. Received null'
});
@@ -128,29 +128,29 @@ testCipher2(Buffer.from('0123456789abcdef'));
assert(instance instanceof Decipher, 'Decipher is expected to return a new ' +
'instance when called without `new`');
common.expectsError(
assert.throws(
() => crypto.createDecipher(null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "cipher" argument must be of type string. ' +
'Received null'
});
common.expectsError(
assert.throws(
() => crypto.createDecipher('aes-256-cbc', 'secret').setAuthTag(null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "buffer" argument must be an instance of Buffer, ' +
'TypedArray, or DataView. Received null'
});
common.expectsError(
assert.throws(
() => crypto.createDecipher('aes-256-cbc', null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "password" argument must be of type string or an ' +
'instance of Buffer, TypedArray, or DataView. Received null'
});
@@ -248,11 +248,11 @@ testCipher2(Buffer.from('0123456789abcdef'));
cipher.setAAD(aadbuf);
cipher.setAutoPadding();
common.expectsError(
assert.throws(
() => cipher.getAuthTag(),
{
code: 'ERR_CRYPTO_INVALID_STATE',
type: Error,
name: 'Error',
message: 'Invalid state for operation getAuthTag'
}
);
@@ -266,27 +266,27 @@ testCipher2(Buffer.from('0123456789abcdef'));
decipher.update(encrypted);
decipher.final();
common.expectsError(
assert.throws(
() => decipher.setAAD(aadbuf),
{
code: 'ERR_CRYPTO_INVALID_STATE',
type: Error,
name: 'Error',
message: 'Invalid state for operation setAAD'
});
common.expectsError(
assert.throws(
() => decipher.setAuthTag(cipher.getAuthTag()),
{
code: 'ERR_CRYPTO_INVALID_STATE',
type: Error,
name: 'Error',
message: 'Invalid state for operation setAuthTag'
});
common.expectsError(
assert.throws(
() => decipher.setAutoPadding(),
{
code: 'ERR_CRYPTO_INVALID_STATE',
type: Error,
name: 'Error',
message: 'Invalid state for operation setAutoPadding'
}
);
@@ -87,29 +87,29 @@ function testCipher3(key, iv) {
assert(instance instanceof Cipheriv, 'Cipheriv is expected to return a new ' +
'instance when called without `new`');
common.expectsError(
assert.throws(
() => crypto.createCipheriv(null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "cipher" argument must be of type string. ' +
'Received null'
});
common.expectsError(
assert.throws(
() => crypto.createCipheriv('des-ede3-cbc', null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "key" argument must be of type string or an instance of ' +
'Buffer, TypedArray, DataView, or KeyObject. Received null'
});
common.expectsError(
assert.throws(
() => crypto.createCipheriv('des-ede3-cbc', key, 10),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "iv" argument must be of type string or an instance of ' +
'Buffer, TypedArray, or DataView. Received type number (10)'
});
@@ -124,29 +124,29 @@ function testCipher3(key, iv) {
assert(instance instanceof Decipheriv, 'Decipheriv expected to return a new' +
' instance when called without `new`');
common.expectsError(
assert.throws(
() => crypto.createDecipheriv(null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "cipher" argument must be of type string. ' +
'Received null'
});
common.expectsError(
assert.throws(
() => crypto.createDecipheriv('des-ede3-cbc', null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "key" argument must be of type string or an instance of ' +
'Buffer, TypedArray, DataView, or KeyObject. Received null'
});
common.expectsError(
assert.throws(
() => crypto.createDecipheriv('des-ede3-cbc', key, 10),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "iv" argument must be of type string or an instance of ' +
'Buffer, TypedArray, or DataView. Received type number (10)'
});
+10 -10
View File
@@ -48,11 +48,11 @@ assert.strictEqual(dh2.verifyError, 0);
/abc/,
{}
].forEach((input) => {
common.expectsError(
assert.throws(
() => crypto.createDiffieHellman(input),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "sizeOrKey" argument must be one of type number or string' +
' or an instance of Buffer, TypedArray, or DataView.' +
common.invalidArgTypeHelper(input)
@@ -233,11 +233,11 @@ if (availableCurves.has('prime256v1') && availableCurves.has('secp256k1')) {
assert(firstByte === 6 || firstByte === 7);
// Format value should be string
common.expectsError(
assert.throws(
() => ecdh1.getPublicKey('buffer', 10),
{
code: 'ERR_CRYPTO_ECDH_INVALID_FORMAT',
type: TypeError,
name: 'TypeError',
message: 'Invalid ECDH format: 10'
});
@@ -245,11 +245,11 @@ if (availableCurves.has('prime256v1') && availableCurves.has('secp256k1')) {
const ecdh3 = crypto.createECDH('secp256k1');
const key3 = ecdh3.generateKeys();
common.expectsError(
assert.throws(
() => ecdh2.computeSecret(key3, 'latin1', 'buffer'),
{
code: 'ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY',
type: Error,
name: 'Error',
message: 'Public key is not valid for specified curve'
});
@@ -358,11 +358,11 @@ if (availableCurves.has('prime256v1') && availableHashes.has('sha256')) {
const invalidKey = Buffer.alloc(65);
invalidKey.fill('\0');
curve.generateKeys();
common.expectsError(
assert.throws(
() => curve.computeSecret(invalidKey),
{
code: 'ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY',
type: Error,
name: 'Error',
message: 'Public key is not valid for specified curve'
});
// Check that signing operations are not impacted by the above error.
@@ -376,11 +376,11 @@ if (availableCurves.has('prime256v1') && availableHashes.has('sha256')) {
}
// Invalid test: curve argument is undefined
common.expectsError(
assert.throws(
() => crypto.createECDH(),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "curve" argument must be of type string. ' +
'Received undefined'
});
@@ -17,36 +17,36 @@ const cafebabePubPtUnComp =
'2e02c7f93d13dc2732b760ca377a5897b9dd41a1c1b29dc0442fdce6d0a04d1d';
// Invalid test: key argument is undefined.
common.expectsError(
assert.throws(
() => ECDH.convertKey(),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
});
// Invalid test: curve argument is undefined.
common.expectsError(
assert.throws(
() => ECDH.convertKey(cafebabePubPtComp),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
});
// Invalid test: curve argument is invalid.
common.expectsError(
assert.throws(
() => ECDH.convertKey(cafebabePubPtComp, 'badcurve'),
{
type: TypeError,
name: 'TypeError',
message: 'Invalid ECDH curve name'
});
if (getCurves().includes('secp256k1')) {
// Invalid test: format argument is undefined.
common.expectsError(
assert.throws(
() => ECDH.convertKey(cafebabePubPtComp, 'secp256k1', 'hex', 'hex', 10),
{
code: 'ERR_CRYPTO_ECDH_INVALID_FORMAT',
type: TypeError,
name: 'TypeError',
message: 'Invalid ECDH format: 10'
});
+9 -8
View File
@@ -4,39 +4,40 @@ const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
const assert = require('assert');
const crypto = require('crypto');
const invalidEngineName = 'xxx';
common.expectsError(
assert.throws(
() => crypto.setEngine(true),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "id" argument must be of type string. Received type boolean' +
' (true)'
});
common.expectsError(
assert.throws(
() => crypto.setEngine('/path/to/engine', 'notANumber'),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "flags" argument must be of type number. Received type' +
" string ('notANumber')"
});
common.expectsError(
assert.throws(
() => crypto.setEngine(invalidEngineName),
{
code: 'ERR_CRYPTO_ENGINE_UNKNOWN',
type: Error,
name: 'Error',
message: `Engine "${invalidEngineName}" was not found`
});
common.expectsError(
assert.throws(
() => crypto.setEngine(invalidEngineName, crypto.constants.ENGINE_METHOD_RSA),
{
code: 'ERR_CRYPTO_ENGINE_UNKNOWN',
type: Error,
name: 'Error',
message: `Engine "${invalidEngineName}" was not found`
});
+17 -17
View File
@@ -113,22 +113,22 @@ assert.throws(function() {
// Issue https://github.com/nodejs/node/issues/9819: throwing encoding used to
// segfault.
common.expectsError(
assert.throws(
() => crypto.createHash('sha256').digest({
toString: () => { throw new Error('boom'); },
}),
{
type: Error,
name: 'Error',
message: 'boom'
});
// Issue https://github.com/nodejs/node/issues/25487: error message for invalid
// arg type to update method should include all possible types
common.expectsError(
assert.throws(
() => crypto.createHash('sha256').update(),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "data" argument must be of type string or an instance of ' +
'Buffer, TypedArray, or DataView. Received undefined'
});
@@ -147,29 +147,29 @@ assert.notStrictEqual(
const h3 = crypto.createHash('sha256');
h3.digest();
common.expectsError(
assert.throws(
() => h3.digest(),
{
code: 'ERR_CRYPTO_HASH_FINALIZED',
type: Error
name: 'Error'
});
common.expectsError(
assert.throws(
() => h3.update('foo'),
{
code: 'ERR_CRYPTO_HASH_FINALIZED',
type: Error
name: 'Error'
});
assert.strictEqual(
crypto.createHash('sha256').update('test').digest('ucs2'),
crypto.createHash('sha256').update('test').digest().toString('ucs2'));
common.expectsError(
assert.throws(
() => crypto.createHash(),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "algorithm" argument must be of type string. ' +
'Received undefined'
}
@@ -246,28 +246,28 @@ common.expectsError(
'15a2b01f828ea62ac5b3e42f');
// Passing invalid sizes should throw during creation.
common.expectsError(() => {
assert.throws(() => {
crypto.createHash('sha256', { outputLength: 28 });
}, {
code: 'ERR_OSSL_EVP_NOT_XOF_OR_INVALID_LENGTH'
});
for (const outputLength of [null, {}, 'foo', false]) {
common.expectsError(() => crypto.createHash('sha256', { outputLength }),
{ code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => crypto.createHash('sha256', { outputLength }),
{ code: 'ERR_INVALID_ARG_TYPE' });
}
for (const outputLength of [-1, .5, Infinity, 2 ** 90]) {
common.expectsError(() => crypto.createHash('sha256', { outputLength }),
{ code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => crypto.createHash('sha256', { outputLength }),
{ code: 'ERR_OUT_OF_RANGE' });
}
}
{
const h = crypto.createHash('sha512');
h.digest();
common.expectsError(() => h.copy(), { code: 'ERR_CRYPTO_HASH_FINALIZED' });
common.expectsError(() => h.digest(), { code: 'ERR_CRYPTO_HASH_FINALIZED' });
assert.throws(() => h.copy(), { code: 'ERR_CRYPTO_HASH_FINALIZED' });
assert.throws(() => h.digest(), { code: 'ERR_CRYPTO_HASH_FINALIZED' });
}
{
+6 -6
View File
@@ -13,29 +13,29 @@ const crypto = require('crypto');
' when called without `new`');
}
common.expectsError(
assert.throws(
() => crypto.createHmac(null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "hmac" argument must be of type string. Received null'
});
// This used to segfault. See: https://github.com/nodejs/node/issues/9819
common.expectsError(
assert.throws(
() => crypto.createHmac('sha256', 'key').digest({
toString: () => { throw new Error('boom'); },
}),
{
type: Error,
name: 'Error',
message: 'boom'
});
common.expectsError(
assert.throws(
() => crypto.createHmac('sha1', null),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "key" argument must be of type string or an instance of ' +
'Buffer, TypedArray, DataView, or KeyObject. Received null'
});
+22 -22
View File
@@ -32,10 +32,10 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
{
// Attempting to create an empty key should throw.
common.expectsError(() => {
assert.throws(() => {
createSecretKey(Buffer.alloc(0));
}, {
type: RangeError,
name: 'RangeError',
code: 'ERR_OUT_OF_RANGE',
message: 'The value of "key.byteLength" is out of range. ' +
'It must be > 0. Received 0'
@@ -46,8 +46,8 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
// Attempting to create a key of a wrong type should throw
const TYPE = 'wrong_type';
common.expectsError(() => new KeyObject(TYPE), {
type: TypeError,
assert.throws(() => new KeyObject(TYPE), {
name: 'TypeError',
code: 'ERR_INVALID_ARG_VALUE',
message: `The argument 'type' is invalid. Received '${TYPE}'`
});
@@ -55,8 +55,8 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
{
// Attempting to create a key with non-object handle should throw
common.expectsError(() => new KeyObject('secret', ''), {
type: TypeError,
assert.throws(() => new KeyObject('secret', ''), {
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE',
message:
'The "handle" argument must be of type object. Received type ' +
@@ -92,16 +92,16 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
{
// Passing an existing public key object to createPublicKey should throw.
const publicKey = createPublicKey(publicPem);
common.expectsError(() => createPublicKey(publicKey), {
type: TypeError,
assert.throws(() => createPublicKey(publicKey), {
name: 'TypeError',
code: 'ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE',
message: 'Invalid key object type public, expected private.'
});
// Constructing a private key from a public key should be impossible, even
// if the public key was derived from a private key.
common.expectsError(() => createPrivateKey(createPublicKey(privatePem)), {
type: TypeError,
assert.throws(() => createPrivateKey(createPublicKey(privatePem)), {
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "key" argument must be of type string or an instance of ' +
'Buffer, TypedArray, or DataView. Received an instance of ' +
@@ -111,8 +111,8 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
// Similarly, passing an existing private key object to createPrivateKey
// should throw.
const privateKey = createPrivateKey(privatePem);
common.expectsError(() => createPrivateKey(privateKey), {
type: TypeError,
assert.throws(() => createPrivateKey(privateKey), {
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "key" argument must be of type string or an instance of ' +
'Buffer, TypedArray, or DataView. Received an instance of ' +
@@ -139,8 +139,8 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
// Test exporting with an invalid options object, this should throw.
for (const opt of [undefined, null, 'foo', 0, NaN]) {
common.expectsError(() => publicKey.export(opt), {
type: TypeError,
assert.throws(() => publicKey.export(opt), {
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE',
message: /^The "options" argument must be of type object/
});
@@ -280,26 +280,26 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
{
// Reading an encrypted key without a passphrase should fail.
common.expectsError(() => createPrivateKey(privateDsa), {
type: TypeError,
assert.throws(() => createPrivateKey(privateDsa), {
name: 'TypeError',
code: 'ERR_MISSING_PASSPHRASE',
message: 'Passphrase required for encrypted key'
});
// Reading an encrypted key with a passphrase that exceeds OpenSSL's buffer
// size limit should fail with an appropriate error code.
common.expectsError(() => createPrivateKey({
assert.throws(() => createPrivateKey({
key: privateDsa,
format: 'pem',
passphrase: Buffer.alloc(1025, 'a')
}), {
code: 'ERR_OSSL_PEM_BAD_PASSWORD_READ',
type: Error
name: 'Error'
});
// The buffer has a size of 1024 bytes, so this passphrase should be permitted
// (but will fail decryption).
common.expectsError(() => createPrivateKey({
assert.throws(() => createPrivateKey({
key: privateDsa,
format: 'pem',
passphrase: Buffer.alloc(1024, 'a')
@@ -362,7 +362,7 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
// Exporting the key using PKCS#1 should not work since this would discard
// any algorithm restrictions.
common.expectsError(() => {
assert.throws(() => {
publicKey.export({ format: 'pem', type: 'pkcs1' });
}, {
code: 'ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS'
@@ -465,12 +465,12 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
{
// Exporting an encrypted private key requires a cipher
const privateKey = createPrivateKey(privatePem);
common.expectsError(() => {
assert.throws(() => {
privateKey.export({
format: 'pem', type: 'pkcs8', passphrase: 'super-secret'
});
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: 'The value "undefined" is invalid for option "cipher"'
});
+74 -74
View File
@@ -180,8 +180,8 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Since the private key is encrypted, signing shouldn't work anymore.
const publicKey = { key: publicKeyDER, ...publicKeyEncoding };
common.expectsError(() => testSignVerify(publicKey, privateKey), {
type: TypeError,
assert.throws(() => testSignVerify(publicKey, privateKey), {
name: 'TypeError',
code: 'ERR_MISSING_PASSPHRASE',
message: 'Passphrase required for encrypted key'
});
@@ -212,14 +212,14 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Since the private key is encrypted, signing shouldn't work anymore.
const publicKey = { key: publicKeyDER, ...publicKeyEncoding };
common.expectsError(() => {
assert.throws(() => {
testSignVerify(publicKey, {
key: privateKeyDER,
format: 'der',
type: 'pkcs8'
});
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_MISSING_PASSPHRASE',
message: 'Passphrase required for encrypted key'
});
@@ -333,13 +333,13 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
assertApproximateSize(privateKeyDER, 336);
// Since the private key is encrypted, signing shouldn't work anymore.
common.expectsError(() => {
assert.throws(() => {
return testSignVerify(publicKey, {
key: privateKeyDER,
...privateKeyEncoding
});
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_MISSING_PASSPHRASE',
message: 'Passphrase required for encrypted key'
});
@@ -425,8 +425,8 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
assert(sec1EncExp('AES-128-CBC').test(privateKey));
// Since the private key is encrypted, signing shouldn't work anymore.
common.expectsError(() => testSignVerify(publicKey, privateKey), {
type: TypeError,
assert.throws(() => testSignVerify(publicKey, privateKey), {
name: 'TypeError',
code: 'ERR_MISSING_PASSPHRASE',
message: 'Passphrase required for encrypted key'
});
@@ -457,8 +457,8 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
assert(sec1EncExp('AES-128-CBC').test(privateKey));
// Since the private key is encrypted, signing shouldn't work anymore.
common.expectsError(() => testSignVerify(publicKey, privateKey), {
type: TypeError,
assert.throws(() => testSignVerify(publicKey, privateKey), {
name: 'TypeError',
code: 'ERR_MISSING_PASSPHRASE',
message: 'Passphrase required for encrypted key'
});
@@ -492,8 +492,8 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
assert(pkcs8EncExp.test(privateKey));
// Since the private key is encrypted, signing shouldn't work anymore.
common.expectsError(() => testSignVerify(publicKey, privateKey), {
type: TypeError,
assert.throws(() => testSignVerify(publicKey, privateKey), {
name: 'TypeError',
code: 'ERR_MISSING_PASSPHRASE',
message: 'Passphrase required for encrypted key'
});
@@ -528,8 +528,8 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
assert(pkcs8EncExp.test(privateKey));
// Since the private key is encrypted, signing shouldn't work anymore.
common.expectsError(() => testSignVerify(publicKey, privateKey), {
type: TypeError,
assert.throws(() => testSignVerify(publicKey, privateKey), {
name: 'TypeError',
code: 'ERR_MISSING_PASSPHRASE',
message: 'Passphrase required for encrypted key'
});
@@ -543,7 +543,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Test invalid parameter encoding.
{
common.expectsError(() => generateKeyPairSync('ec', {
assert.throws(() => generateKeyPairSync('ec', {
namedCurve: 'P-256',
paramEncoding: 'otherEncoding',
publicKeyEncoding: {
@@ -557,7 +557,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
passphrase: 'top secret'
}
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: 'The value "otherEncoding" is invalid for ' +
'option "paramEncoding"'
@@ -595,16 +595,16 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
{
// Test invalid key types.
for (const type of [undefined, null, 0]) {
common.expectsError(() => generateKeyPairSync(type, {}), {
type: TypeError,
assert.throws(() => generateKeyPairSync(type, {}), {
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "type" argument must be of type string.' +
common.invalidArgTypeHelper(type)
});
}
common.expectsError(() => generateKeyPairSync('rsa2', {}), {
type: TypeError,
assert.throws(() => generateKeyPairSync('rsa2', {}), {
name: 'TypeError',
code: 'ERR_INVALID_ARG_VALUE',
message: "The argument 'type' must be a supported key type. Received 'rsa2'"
});
@@ -612,8 +612,8 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
{
// Test keygen without options object.
common.expectsError(() => generateKeyPair('rsa', common.mustNotCall()), {
type: TypeError,
assert.throws(() => generateKeyPair('rsa', common.mustNotCall()), {
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "options" argument must be of type object. ' +
'Received undefined'
@@ -621,8 +621,8 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Even if no options are required, it should be impossible to pass anything
// but an object (or undefined).
common.expectsError(() => generateKeyPair('ed448', 0, common.mustNotCall()), {
type: TypeError,
assert.throws(() => generateKeyPair('ed448', 0, common.mustNotCall()), {
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "options" argument must be of type object. ' +
'Received type number (0)'
@@ -676,7 +676,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
{
// Invalid publicKeyEncoding.
for (const enc of [0, 'a', true]) {
common.expectsError(() => generateKeyPairSync('rsa', {
assert.throws(() => generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: enc,
privateKeyEncoding: {
@@ -684,7 +684,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
format: 'pem'
}
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${enc}" is invalid for option "publicKeyEncoding"`
});
@@ -692,7 +692,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Missing publicKeyEncoding.type.
for (const type of [undefined, null, 0, true, {}]) {
common.expectsError(() => generateKeyPairSync('rsa', {
assert.throws(() => generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type,
@@ -703,7 +703,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
format: 'pem'
}
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${type}" is invalid for option ` +
'"publicKeyEncoding.type"'
@@ -712,7 +712,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Missing / invalid publicKeyEncoding.format.
for (const format of [undefined, null, 0, false, 'a', {}]) {
common.expectsError(() => generateKeyPairSync('rsa', {
assert.throws(() => generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
@@ -723,7 +723,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
format: 'pem'
}
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${format}" is invalid for option ` +
'"publicKeyEncoding.format"'
@@ -732,7 +732,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Invalid privateKeyEncoding.
for (const enc of [0, 'a', true]) {
common.expectsError(() => generateKeyPairSync('rsa', {
assert.throws(() => generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
@@ -740,7 +740,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
},
privateKeyEncoding: enc
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${enc}" is invalid for option "privateKeyEncoding"`
});
@@ -748,7 +748,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Missing / invalid privateKeyEncoding.type.
for (const type of [undefined, null, 0, true, {}]) {
common.expectsError(() => generateKeyPairSync('rsa', {
assert.throws(() => generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
@@ -759,7 +759,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
format: 'pem'
}
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${type}" is invalid for option ` +
'"privateKeyEncoding.type"'
@@ -768,7 +768,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Missing / invalid privateKeyEncoding.format.
for (const format of [undefined, null, 0, false, 'a', {}]) {
common.expectsError(() => generateKeyPairSync('rsa', {
assert.throws(() => generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
@@ -779,7 +779,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
format
}
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${format}" is invalid for option ` +
'"privateKeyEncoding.format"'
@@ -788,7 +788,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Cipher of invalid type.
for (const cipher of [0, true, {}]) {
common.expectsError(() => generateKeyPairSync('rsa', {
assert.throws(() => generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
@@ -800,7 +800,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
cipher
}
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${cipher}" is invalid for option ` +
'"privateKeyEncoding.cipher"'
@@ -808,7 +808,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
}
// Invalid cipher.
common.expectsError(() => generateKeyPairSync('rsa', {
assert.throws(() => generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
@@ -821,13 +821,13 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
passphrase: 'secret'
}
}), {
type: Error,
name: 'Error',
message: 'Unknown cipher'
});
// Cipher, but no valid passphrase.
for (const passphrase of [undefined, null, 5, false, true]) {
common.expectsError(() => generateKeyPairSync('rsa', {
assert.throws(() => generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
@@ -840,7 +840,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
passphrase
}
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${passphrase}" is invalid for option ` +
'"privateKeyEncoding.passphrase"'
@@ -849,12 +849,12 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Test invalid callbacks.
for (const cb of [undefined, null, 0, {}]) {
common.expectsError(() => generateKeyPair('rsa', {
assert.throws(() => generateKeyPair('rsa', {
modulusLength: 512,
publicKeyEncoding: { type: 'pkcs1', format: 'pem' },
privateKeyEncoding: { type: 'pkcs1', format: 'pem' }
}, cb), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_CALLBACK'
});
}
@@ -864,10 +864,10 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
{
// Test invalid modulus lengths.
for (const modulusLength of [undefined, null, 'a', true, {}, [], 512.1, -1]) {
common.expectsError(() => generateKeyPair('rsa', {
assert.throws(() => generateKeyPair('rsa', {
modulusLength
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${modulusLength}" is invalid for option ` +
'"modulusLength"'
@@ -876,11 +876,11 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Test invalid exponents.
for (const publicExponent of ['a', true, {}, [], 3.5, -1]) {
common.expectsError(() => generateKeyPair('rsa', {
assert.throws(() => generateKeyPair('rsa', {
modulusLength: 4096,
publicExponent
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${publicExponent}" is invalid for option ` +
'"publicExponent"'
@@ -892,10 +892,10 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
{
// Test invalid modulus lengths.
for (const modulusLength of [undefined, null, 'a', true, {}, [], 4096.1]) {
common.expectsError(() => generateKeyPair('dsa', {
assert.throws(() => generateKeyPair('dsa', {
modulusLength
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${modulusLength}" is invalid for option ` +
'"modulusLength"'
@@ -904,11 +904,11 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Test invalid divisor lengths.
for (const divisorLength of ['a', true, {}, [], 4096.1]) {
common.expectsError(() => generateKeyPair('dsa', {
assert.throws(() => generateKeyPair('dsa', {
modulusLength: 2048,
divisorLength
}), {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${divisorLength}" is invalid for option ` +
'"divisorLength"'
@@ -919,27 +919,27 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Test EC parameters.
{
// Test invalid curves.
common.expectsError(() => {
assert.throws(() => {
generateKeyPairSync('ec', {
namedCurve: 'abcdef',
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'sec1', format: 'pem' }
});
}, {
type: TypeError,
name: 'TypeError',
message: 'Invalid ECDH curve name'
});
// Test error type when curve is not a string
for (const namedCurve of [true, {}, [], 123]) {
common.expectsError(() => {
assert.throws(() => {
generateKeyPairSync('ec', {
namedCurve,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'sec1', format: 'pem' }
});
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${namedCurve}" is invalid for option ` +
'"namedCurve"'
@@ -985,14 +985,14 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
{
// Invalid public key type.
for (const type of ['foo', 'pkcs8', 'sec1']) {
common.expectsError(() => {
assert.throws(() => {
generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: { type, format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${type}" is invalid for option ` +
'"publicKeyEncoding.type"'
@@ -1001,13 +1001,13 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Invalid hash value.
for (const hashValue of [123, true, {}, []]) {
common.expectsError(() => {
assert.throws(() => {
generateKeyPairSync('rsa-pss', {
modulusLength: 4096,
hash: hashValue
});
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${hashValue}" is invalid for option "hash"`
});
@@ -1015,14 +1015,14 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Invalid private key type.
for (const type of ['foo', 'spki']) {
common.expectsError(() => {
assert.throws(() => {
generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type, format: 'pem' }
});
}, {
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${type}" is invalid for option ` +
'"privateKeyEncoding.type"'
@@ -1031,7 +1031,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Key encoding doesn't match key type.
for (const type of ['dsa', 'ec']) {
common.expectsError(() => {
assert.throws(() => {
generateKeyPairSync(type, {
modulusLength: 4096,
namedCurve: 'P-256',
@@ -1039,12 +1039,12 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
}, {
type: Error,
name: 'Error',
code: 'ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS',
message: 'The selected key encoding pkcs1 can only be used for RSA keys.'
});
common.expectsError(() => {
assert.throws(() => {
generateKeyPairSync(type, {
modulusLength: 4096,
namedCurve: 'P-256',
@@ -1052,21 +1052,21 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
privateKeyEncoding: { type: 'pkcs1', format: 'pem' }
});
}, {
type: Error,
name: 'Error',
code: 'ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS',
message: 'The selected key encoding pkcs1 can only be used for RSA keys.'
});
}
for (const type of ['rsa', 'dsa']) {
common.expectsError(() => {
assert.throws(() => {
generateKeyPairSync(type, {
modulusLength: 4096,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'sec1', format: 'pem' }
});
}, {
type: Error,
name: 'Error',
code: 'ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS',
message: 'The selected key encoding sec1 can only be used for EC keys.'
});
@@ -1074,7 +1074,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Attempting to encrypt a DER-encoded, non-PKCS#8 key.
for (const type of ['pkcs1', 'sec1']) {
common.expectsError(() => {
assert.throws(() => {
generateKeyPairSync(type === 'pkcs1' ? 'rsa' : 'ec', {
modulusLength: 4096,
namedCurve: 'P-256',
@@ -1087,7 +1087,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
}
});
}, {
type: Error,
name: 'Error',
code: 'ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS',
message: `The selected key encoding ${type} does not support encryption.`
});
@@ -1095,7 +1095,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
}
{
// Test RSA-PSS.
common.expectsError(
assert.throws(
() => {
generateKeyPair('rsa-pss', {
modulusLength: 512,
@@ -1105,14 +1105,14 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
});
},
{
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_CALLBACK',
message: 'Callback must be a function. Received undefined'
}
);
for (const mgf1Hash of [null, 0, false, {}, []]) {
common.expectsError(
assert.throws(
() => {
generateKeyPair('rsa-pss', {
modulusLength: 512,
@@ -1122,7 +1122,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
});
},
{
type: TypeError,
name: 'TypeError',
code: 'ERR_INVALID_OPT_VALUE',
message: `The value "${mgf1Hash}" is invalid for option "mgf1Hash"`
}
+8 -8
View File
@@ -273,35 +273,35 @@ assert.throws(
[1, true, NaN, null, undefined, {}, []].forEach((i) => {
const buf = Buffer.alloc(10);
common.expectsError(
assert.throws(
() => crypto.randomFillSync(i),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
name: 'TypeError'
}
);
common.expectsError(
assert.throws(
() => crypto.randomFill(i, common.mustNotCall()),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
name: 'TypeError'
}
);
common.expectsError(
assert.throws(
() => crypto.randomFill(buf, 0, 10, i),
{
code: 'ERR_INVALID_CALLBACK',
type: TypeError,
name: 'TypeError',
message: `Callback must be a function. Received ${inspect(i)}`
});
});
[1, true, NaN, null, {}, []].forEach((i) => {
common.expectsError(
assert.throws(
() => crypto.randomBytes(1, i),
{
code: 'ERR_INVALID_CALLBACK',
type: TypeError,
name: 'TypeError',
message: `Callback must be a function. Received ${inspect(i)}`
}
);
+3 -3
View File
@@ -193,7 +193,7 @@ test_rsa('RSA_PKCS1_OAEP_PADDING', undefined, 'sha1');
test_rsa('RSA_PKCS1_OAEP_PADDING', 'sha1', undefined);
test_rsa('RSA_PKCS1_OAEP_PADDING', 'sha256', 'sha256');
test_rsa('RSA_PKCS1_OAEP_PADDING', 'sha512', 'sha512');
common.expectsError(() => {
assert.throws(() => {
test_rsa('RSA_PKCS1_OAEP_PADDING', 'sha256', 'sha512');
}, {
code: 'ERR_OSSL_RSA_OAEP_DECODING_ERROR'
@@ -228,7 +228,7 @@ for (const fn of [crypto.publicEncrypt, crypto.privateDecrypt]) {
});
for (const oaepHash of [0, false, null, Symbol(), () => {}]) {
common.expectsError(() => {
assert.throws(() => {
fn({
key: rsaPubPem,
oaepHash
@@ -239,7 +239,7 @@ for (const fn of [crypto.publicEncrypt, crypto.privateDecrypt]) {
}
for (const oaepLabel of [0, false, null, Symbol(), () => {}, {}, 'foo']) {
common.expectsError(() => {
assert.throws(() => {
fn({
key: rsaPubPem,
oaepLabel
+18 -18
View File
@@ -159,24 +159,24 @@ for (const options of bad) {
const expected = {
code: 'ERR_CRYPTO_SCRYPT_INVALID_PARAMETER',
message: 'Invalid scrypt parameter',
type: Error,
name: 'Error',
};
common.expectsError(() => crypto.scrypt('pass', 'salt', 1, options, () => {}),
expected);
common.expectsError(() => crypto.scryptSync('pass', 'salt', 1, options),
expected);
assert.throws(() => crypto.scrypt('pass', 'salt', 1, options, () => {}),
expected);
assert.throws(() => crypto.scryptSync('pass', 'salt', 1, options),
expected);
}
for (const options of toobig) {
const expected = {
message: new RegExp('error:[^:]+:digital envelope routines:' +
'(?:EVP_PBE_scrypt|scrypt_alg):memory limit exceeded'),
type: Error,
name: 'Error',
};
common.expectsError(() => crypto.scrypt('pass', 'salt', 1, options, () => {}),
expected);
common.expectsError(() => crypto.scryptSync('pass', 'salt', 1, options),
expected);
assert.throws(() => crypto.scrypt('pass', 'salt', 1, options, () => {}),
expected);
assert.throws(() => crypto.scryptSync('pass', 'salt', 1, options),
expected);
}
{
@@ -209,16 +209,16 @@ for (const options of toobig) {
}
for (const { args, expected } of badargs) {
common.expectsError(() => crypto.scrypt(...args), expected);
common.expectsError(() => crypto.scryptSync(...args), expected);
assert.throws(() => crypto.scrypt(...args), expected);
assert.throws(() => crypto.scryptSync(...args), expected);
}
{
const expected = { code: 'ERR_INVALID_CALLBACK' };
common.expectsError(() => crypto.scrypt('', '', 42, null), expected);
common.expectsError(() => crypto.scrypt('', '', 42, {}, null), expected);
common.expectsError(() => crypto.scrypt('', '', 42, {}), expected);
common.expectsError(() => crypto.scrypt('', '', 42, {}, {}), expected);
assert.throws(() => crypto.scrypt('', '', 42, null), expected);
assert.throws(() => crypto.scrypt('', '', 42, {}, null), expected);
assert.throws(() => crypto.scrypt('', '', 42, {}), expected);
assert.throws(() => crypto.scrypt('', '', 42, {}, {}), expected);
}
{
@@ -231,7 +231,7 @@ for (const { args, expected } of badargs) {
}));
// Values that exceed Number.isSafeInteger should not be allowed.
common.expectsError(() => crypto.scryptSync('', '', 0, { maxmem: 2 ** 53 }), {
assert.throws(() => crypto.scryptSync('', '', 0, { maxmem: 2 ** 53 }), {
code: 'ERR_OUT_OF_RANGE'
});
}
@@ -251,7 +251,7 @@ for (const { args, expected } of badargs) {
});
// Try to crash the process on the last access.
common.expectsError(() => {
assert.throws(() => {
crypto.scryptSync('', '', 1, {
get [name]() {
if (--accessCount === 0)
+12 -12
View File
@@ -68,25 +68,25 @@ const keySize = 2048;
delete Object.prototype.opensslErrorStack;
}
common.expectsError(
assert.throws(
() => crypto.createVerify('SHA256').verify({
key: certPem,
padding: null,
}, ''),
{
code: 'ERR_INVALID_OPT_VALUE',
type: TypeError,
name: 'TypeError',
message: 'The value "null" is invalid for option "padding"'
});
common.expectsError(
assert.throws(
() => crypto.createVerify('SHA256').verify({
key: certPem,
saltLength: null,
}, ''),
{
code: 'ERR_INVALID_OPT_VALUE',
type: TypeError,
name: 'TypeError',
message: 'The value "null" is invalid for option "saltLength"'
});
@@ -306,7 +306,7 @@ common.expectsError(
{
[null, NaN, 'boom', {}, [], true, false]
.forEach((invalidValue) => {
common.expectsError(() => {
assert.throws(() => {
crypto.createSign('SHA256')
.update('Test123')
.sign({
@@ -315,10 +315,10 @@ common.expectsError(
});
}, {
code: 'ERR_INVALID_OPT_VALUE',
type: TypeError
name: 'TypeError'
});
common.expectsError(() => {
assert.throws(() => {
crypto.createSign('SHA256')
.update('Test123')
.sign({
@@ -328,7 +328,7 @@ common.expectsError(
});
}, {
code: 'ERR_INVALID_OPT_VALUE',
type: TypeError
name: 'TypeError'
});
});
@@ -351,11 +351,11 @@ common.expectsError(
// Test throws exception when key options is null
{
common.expectsError(() => {
assert.throws(() => {
crypto.createSign('SHA1').update('Test123').sign(null, 'base64');
}, {
code: 'ERR_CRYPTO_SIGN_KEY_REQUIRED',
type: Error
name: 'Error'
});
}
@@ -534,7 +534,7 @@ common.expectsError(
// Test invalid signature lengths.
for (const i of [-2, -1, 1, 2, 4, 8]) {
sig = crypto.randomBytes(length + i);
common.expectsError(() => {
assert.throws(() => {
crypto.verify('sha1', data, opts, sig);
}, {
message: 'Malformed signature'
@@ -588,7 +588,7 @@ common.expectsError(
);
for (const dsaEncoding of ['foo', null, {}, 5, true, NaN]) {
common.expectsError(() => {
assert.throws(() => {
crypto.sign('sha1', data, {
key: certPem,
dsaEncoding
+58 -71
View File
@@ -41,7 +41,7 @@ const certPfx = fixtures.readKey('rsa_cert.pfx');
// 'this' safety
// https://github.com/joyent/node/issues/6690
assert.throws(function() {
assert.throws(() => {
const credentials = tls.createSecureContext();
const context = credentials.context;
const notcontext = { setOptions: context.setOptions };
@@ -52,56 +52,52 @@ assert.throws(function() {
notcontext.setOptions();
}, (err) => {
// Throws TypeError, so there is no opensslErrorStack property.
if ((err instanceof Error) &&
/^TypeError: Illegal invocation$/.test(err) &&
err.opensslErrorStack === undefined) {
return true;
}
return err instanceof TypeError &&
err.name === 'TypeError' &&
/^TypeError: Illegal invocation$/.test(err) &&
!('opensslErrorStack' in err);
});
// PFX tests
tls.createSecureContext({ pfx: certPfx, passphrase: 'sample' });
assert.throws(function() {
assert.throws(() => {
tls.createSecureContext({ pfx: certPfx });
}, (err) => {
// Throws general Error, so there is no opensslErrorStack property.
if ((err instanceof Error) &&
/^Error: mac verify failure$/.test(err) &&
err.opensslErrorStack === undefined) {
return true;
}
return err instanceof Error &&
err.name === 'Error' &&
/^Error: mac verify failure$/.test(err) &&
!('opensslErrorStack' in err);
});
assert.throws(function() {
assert.throws(() => {
tls.createSecureContext({ pfx: certPfx, passphrase: 'test' });
}, (err) => {
// Throws general Error, so there is no opensslErrorStack property.
if ((err instanceof Error) &&
/^Error: mac verify failure$/.test(err) &&
err.opensslErrorStack === undefined) {
return true;
}
return err instanceof Error &&
err.name === 'Error' &&
/^Error: mac verify failure$/.test(err) &&
!('opensslErrorStack' in err);
});
assert.throws(function() {
assert.throws(() => {
tls.createSecureContext({ pfx: 'sample', passphrase: 'test' });
}, (err) => {
// Throws general Error, so there is no opensslErrorStack property.
if ((err instanceof Error) &&
/^Error: not enough data$/.test(err) &&
err.opensslErrorStack === undefined) {
return true;
}
return err instanceof Error &&
err.name === 'Error' &&
/^Error: not enough data$/.test(err) &&
!('opensslErrorStack' in err);
});
// update() should only take buffers / strings
common.expectsError(
assert.throws(
() => crypto.createHash('sha1').update({ foo: 'bar' }),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
name: 'TypeError'
});
@@ -167,44 +163,32 @@ testImmutability(crypto.getCurves);
// Regression tests for https://github.com/nodejs/node-v0.x-archive/pull/5725:
// hex input that's not a power of two should throw, not assert in C++ land.
assert.throws(function() {
crypto.createCipher('aes192', 'test').update('0', 'hex');
}, (err) => {
const errorMessage =
common.hasFipsCrypto ? /not supported in FIPS mode/ : /Bad input string/;
// Throws general Error, so there is no opensslErrorStack property.
if ((err instanceof Error) &&
errorMessage.test(err) &&
err.opensslErrorStack === undefined) {
return true;
}
['createCipher', 'createDecipher'].forEach((funcName) => {
assert.throws(
() => crypto[funcName]('aes192', 'test').update('0', 'hex'),
(error) => {
assert.ok(!('opensslErrorStack' in error));
if (common.hasFipsCrypto) {
return error instanceof Error &&
error.name === 'Error' &&
/^Error: not supported in FIPS mode$/.test(error);
}
assert.throws(() => { throw error; }, /^TypeError: Bad input string$/);
return true;
}
);
});
assert.throws(function() {
crypto.createDecipher('aes192', 'test').update('0', 'hex');
}, (err) => {
const errorMessage =
common.hasFipsCrypto ? /not supported in FIPS mode/ : /Bad input string/;
// Throws general Error, so there is no opensslErrorStack property.
if ((err instanceof Error) &&
errorMessage.test(err) &&
err.opensslErrorStack === undefined) {
assert.throws(
() => crypto.createHmac('sha256', 'a secret').update('0', 'hex'),
(error) => {
assert.ok(!('opensslErrorStack' in error));
assert.throws(() => { throw error; }, /^TypeError: Bad input string$/);
return true;
}
});
);
assert.throws(function() {
crypto.createHash('sha1').update('0', 'hex');
}, (err) => {
// Throws TypeError, so there is no opensslErrorStack property.
if ((err instanceof Error) &&
/^TypeError: Bad input string$/.test(err) &&
err.opensslErrorStack === undefined) {
return true;
}
});
assert.throws(function() {
assert.throws(() => {
const priv = [
'-----BEGIN RSA PRIVATE KEY-----',
'MIGrAgEAAiEA+3z+1QNF2/unumadiwEr+C5vfhezsb3hp4jAnCNRpPcCAwEAAQIgQNriSQK4',
@@ -216,14 +200,19 @@ assert.throws(function() {
].join('\n');
crypto.createSign('SHA256').update('test').sign(priv);
}, (err) => {
if ((err instanceof Error) &&
/digest too big for rsa key$/.test(err) &&
err.opensslErrorStack === undefined) {
return true;
}
assert.ok(!('opensslErrorStack' in err));
assert.throws(() => { throw err; }, {
name: 'Error',
message: /routines:RSA_sign:digest too big for rsa key$/,
library: 'rsa routines',
function: 'RSA_sign',
reason: 'digest too big for rsa key',
code: 'ERR_OSSL_RSA_DIGEST_TOO_BIG_FOR_RSA_KEY'
});
return true;
});
assert.throws(function() {
assert.throws(() => {
// The correct header inside `rsa_private_pkcs8_bad.pem` should have been
// -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY-----
// instead of
@@ -251,15 +240,13 @@ assert.throws(function() {
// Make sure memory isn't released before being returned
console.log(crypto.randomBytes(16));
assert.throws(function() {
assert.throws(() => {
tls.createSecureContext({ crl: 'not a CRL' });
}, (err) => {
// Throws general error, so there is no opensslErrorStack property.
if ((err instanceof Error) &&
/^Error: Failed to parse CRL$/.test(err) &&
err.opensslErrorStack === undefined) {
return true;
}
return err instanceof Error &&
/^Error: Failed to parse CRL$/.test(err) &&
!('opensslErrorStack' in err);
});
/**
+4 -4
View File
@@ -19,13 +19,13 @@ const TYPE = 'udp4';
const anotherSocket = dgram.createSocket(TYPE);
const { handle } = socket[kStateSymbol];
common.expectsError(() => {
assert.throws(() => {
anotherSocket.bind({
fd: handle.fd,
});
}, {
code: 'EEXIST',
type: Error,
name: 'Error',
message: /^open EEXIST$/
});
@@ -42,13 +42,13 @@ const TYPE = 'udp4';
assert.notStrictEqual(fd, -1);
const socket = new dgram.createSocket(TYPE);
common.expectsError(() => {
assert.throws(() => {
socket.bind({
fd,
});
}, {
code: 'ERR_INVALID_FD_TYPE',
type: TypeError,
name: 'TypeError',
message: /^Unsupported fd type: TCP$/
});
+2 -2
View File
@@ -27,11 +27,11 @@ const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
socket.on('listening', common.mustCall(() => {
common.expectsError(() => {
assert.throws(() => {
socket.bind();
}, {
code: 'ERR_SOCKET_ALREADY_BOUND',
type: Error,
name: 'Error',
message: /^Socket is already bound$/
});
@@ -23,11 +23,11 @@ const errMessage = /^Bad socket type specified\. Valid types are: udp4, udp6$/;
// Error must be thrown with invalid types
invalidTypes.forEach((invalidType) => {
common.expectsError(() => {
assert.throws(() => {
dgram.createSocket(invalidType);
}, {
code: 'ERR_SOCKET_BAD_TYPE',
type: TypeError,
name: 'TypeError',
message: errMessage
});
});
+3 -2
View File
@@ -1,5 +1,6 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const dgram = require('dgram');
const dns = require('dns');
@@ -35,11 +36,11 @@ const dns = require('dns');
{
// Verify that non-functions throw.
[null, true, false, 0, 1, NaN, '', 'foo', {}, Symbol()].forEach((value) => {
common.expectsError(() => {
assert.throws(() => {
dgram.createSocket({ type: 'udp4', lookup: value });
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "lookup" argument must be of type function.' +
common.invalidArgTypeHelper(value)
});
+8 -8
View File
@@ -11,11 +11,11 @@ const setup = dgram.createSocket.bind(dgram, { type: 'udp4', reuseAddr: true });
{
const socket = setup();
socket.close(common.mustCall(() => {
common.expectsError(() => {
assert.throws(() => {
socket.addMembership(multicastAddress);
}, {
code: 'ERR_SOCKET_DGRAM_NOT_RUNNING',
type: Error,
name: 'Error',
message: /^Not running$/
});
}));
@@ -25,11 +25,11 @@ const setup = dgram.createSocket.bind(dgram, { type: 'udp4', reuseAddr: true });
{
const socket = setup();
socket.close(common.mustCall(() => {
common.expectsError(() => {
assert.throws(() => {
socket.dropMembership(multicastAddress);
}, {
code: 'ERR_SOCKET_DGRAM_NOT_RUNNING',
type: Error,
name: 'Error',
message: /^Not running$/
});
}));
@@ -38,11 +38,11 @@ const setup = dgram.createSocket.bind(dgram, { type: 'udp4', reuseAddr: true });
// addMembership() with no argument should throw
{
const socket = setup();
common.expectsError(() => {
assert.throws(() => {
socket.addMembership();
}, {
code: 'ERR_MISSING_ARGS',
type: TypeError,
name: 'TypeError',
message: /^The "multicastAddress" argument must be specified$/
});
socket.close();
@@ -51,11 +51,11 @@ const setup = dgram.createSocket.bind(dgram, { type: 'udp4', reuseAddr: true });
// dropMembership() with no argument should throw
{
const socket = setup();
common.expectsError(() => {
assert.throws(() => {
socket.dropMembership();
}, {
code: 'ERR_MISSING_ARGS',
type: TypeError,
name: 'TypeError',
message: /^The "multicastAddress" argument must be specified$/
});
socket.close();
+2 -2
View File
@@ -35,11 +35,11 @@ socket.on('listening', common.mustCall(() => {
socket.setMulticastTTL(1000);
}, /^Error: setMulticastTTL EINVAL$/);
common.expectsError(() => {
assert.throws(() => {
socket.setMulticastTTL('foo');
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "ttl" argument must be of type number. Received type string' +
" ('foo')"
});
+14 -14
View File
@@ -30,11 +30,11 @@ const sock = dgram.createSocket('udp4');
function checkArgs(connected) {
// First argument should be a buffer.
common.expectsError(
assert.throws(
() => { sock.send(); },
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "buffer" argument must be of type string or an instance ' +
'of Buffer or Uint8Array. Received undefined'
}
@@ -42,38 +42,38 @@ function checkArgs(connected) {
// send(buf, offset, length, port, host)
if (connected) {
common.expectsError(
assert.throws(
() => { sock.send(buf, 1, 1, -1, host); },
{
code: 'ERR_SOCKET_DGRAM_IS_CONNECTED',
type: Error,
name: 'Error',
message: 'Already connected'
}
);
common.expectsError(
assert.throws(
() => { sock.send(buf, 1, 1, 0, host); },
{
code: 'ERR_SOCKET_DGRAM_IS_CONNECTED',
type: Error,
name: 'Error',
message: 'Already connected'
}
);
common.expectsError(
assert.throws(
() => { sock.send(buf, 1, 1, 65536, host); },
{
code: 'ERR_SOCKET_DGRAM_IS_CONNECTED',
type: Error,
name: 'Error',
message: 'Already connected'
}
);
common.expectsError(
assert.throws(
() => { sock.send(buf, 1234, '127.0.0.1', common.mustNotCall()); },
{
code: 'ERR_SOCKET_DGRAM_IS_CONNECTED',
type: Error,
name: 'Error',
message: 'Already connected'
}
);
@@ -84,22 +84,22 @@ function checkArgs(connected) {
}
// send(buf, port, host)
common.expectsError(
assert.throws(
() => { sock.send(23, 12345, host); },
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "buffer" argument must be of type string or an instance ' +
'of Buffer or Uint8Array. Received type number (23)'
}
);
// send([buf1, ..], port, host)
common.expectsError(
assert.throws(
() => { sock.send([buf, 23], 12345, host); },
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "buffer list arguments" argument must be of type string ' +
'or an instance of Buffer. Received an instance of Array'
}
+2 -2
View File
@@ -9,11 +9,11 @@ socket.on('listening', common.mustCall(() => {
const result = socket.setTTL(16);
assert.strictEqual(result, 16);
common.expectsError(() => {
assert.throws(() => {
socket.setTTL('foo');
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "ttl" argument must be of type number. Received type string' +
" ('foo')"
});
+10 -11
View File
@@ -5,7 +5,6 @@ const common = require('../common');
const assert = require('assert');
const dgram = require('dgram');
const { inspect } = require('util');
const { SystemError } = require('internal/errors');
const { internalBinding } = require('internal/test/binding');
const {
UV_EBADF,
@@ -61,7 +60,7 @@ function getExpectedError(type) {
return true;
});
common.expectsError(() => {
assert.throws(() => {
socket.getSendBufferSize();
}, errorObj);
}
@@ -72,11 +71,11 @@ function getExpectedError(type) {
// Should throw error if the socket is never bound.
const errorObj = getExpectedError('recv');
common.expectsError(() => {
assert.throws(() => {
socket.setRecvBufferSize(8192);
}, errorObj);
common.expectsError(() => {
assert.throws(() => {
socket.getRecvBufferSize();
}, errorObj);
}
@@ -85,7 +84,7 @@ function getExpectedError(type) {
// Should throw error if invalid buffer size is specified
const errorObj = {
code: 'ERR_SOCKET_BAD_BUFFER_SIZE',
type: TypeError,
name: 'TypeError',
message: /^Buffer size must be a positive integer$/
};
@@ -95,11 +94,11 @@ function getExpectedError(type) {
socket.bind(common.mustCall(() => {
badBufferSizes.forEach((badBufferSize) => {
common.expectsError(() => {
assert.throws(() => {
socket.setRecvBufferSize(badBufferSize);
}, errorObj);
common.expectsError(() => {
assert.throws(() => {
socket.setSendBufferSize(badBufferSize);
}, errorObj);
});
@@ -132,14 +131,14 @@ function getExpectedError(type) {
};
const errorObj = {
code: 'ERR_SOCKET_BUFFER_SIZE',
type: SystemError,
name: 'SystemError',
message: 'Could not get or set buffer size: uv_recv_buffer_size ' +
'returned EINVAL (invalid argument)',
info
};
const socket = dgram.createSocket('udp4');
socket.bind(common.mustCall(() => {
common.expectsError(() => {
assert.throws(() => {
socket.setRecvBufferSize(2147483648);
}, errorObj);
socket.close();
@@ -155,14 +154,14 @@ function getExpectedError(type) {
};
const errorObj = {
code: 'ERR_SOCKET_BUFFER_SIZE',
type: SystemError,
name: 'SystemError',
message: 'Could not get or set buffer size: uv_send_buffer_size ' +
'returned EINVAL (invalid argument)',
info
};
const socket = dgram.createSocket('udp4');
socket.bind(common.mustCall(() => {
common.expectsError(() => {
assert.throws(() => {
socket.setSendBufferSize(2147483648);
}, errorObj);
socket.close();
+13 -13
View File
@@ -15,12 +15,12 @@ const dnsPromises = dns.promises;
{
const err = {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: /^The "hostname" argument must be of type string\. Received type number/
};
common.expectsError(() => dns.lookup(1, {}), err);
common.expectsError(() => dnsPromises.lookup(1, {}), err);
assert.throws(() => dns.lookup(1, {}), err);
assert.throws(() => dnsPromises.lookup(1, {}), err);
}
// This also verifies different expectWarning notations.
@@ -36,24 +36,24 @@ common.expectWarning({
}
});
common.expectsError(() => {
assert.throws(() => {
dns.lookup(false, 'cb');
}, {
code: 'ERR_INVALID_CALLBACK',
type: TypeError
name: 'TypeError'
});
common.expectsError(() => {
assert.throws(() => {
dns.lookup(false, 'options', 'cb');
}, {
code: 'ERR_INVALID_CALLBACK',
type: TypeError
name: 'TypeError'
});
{
const err = {
code: 'ERR_INVALID_OPT_VALUE',
type: TypeError,
name: 'TypeError',
message: 'The value "100" is invalid for option "hints"'
};
const options = {
@@ -62,8 +62,8 @@ common.expectsError(() => {
all: false
};
common.expectsError(() => { dnsPromises.lookup(false, options); }, err);
common.expectsError(() => {
assert.throws(() => { dnsPromises.lookup(false, options); }, err);
assert.throws(() => {
dns.lookup(false, options, common.mustNotCall());
}, err);
}
@@ -71,7 +71,7 @@ common.expectsError(() => {
{
const err = {
code: 'ERR_INVALID_OPT_VALUE',
type: TypeError,
name: 'TypeError',
message: 'The value "20" is invalid for option "family"'
};
const options = {
@@ -80,8 +80,8 @@ common.expectsError(() => {
all: false
};
common.expectsError(() => { dnsPromises.lookup(false, options); }, err);
common.expectsError(() => {
assert.throws(() => { dnsPromises.lookup(false, options); }, err);
assert.throws(() => {
dns.lookup(false, options, common.mustNotCall());
}, err);
}
@@ -20,35 +20,36 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
require('../common');
// This test ensures `dns.resolveNs()` does not raise a C++-land assertion error
// and throw a JavaScript TypeError instead.
// Issue https://github.com/nodejs/node-v0.x-archive/issues/7070
const assert = require('assert');
const dns = require('dns');
const dnsPromises = dns.promises;
common.expectsError(
assert.throws(
() => dnsPromises.resolveNs([]), // bad name
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: /^The "name" argument must be of type string/
}
);
common.expectsError(
assert.throws(
() => dns.resolveNs([]), // bad name
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: /^The "name" argument must be of type string/
}
);
common.expectsError(
assert.throws(
() => dns.resolveNs(''), // bad callback
{
code: 'ERR_INVALID_CALLBACK',
type: TypeError
name: 'TypeError'
}
);
@@ -2,6 +2,7 @@
const common = require('../common');
const assert = require('assert');
const dns = require('dns');
const localhost = [ '127.0.0.1' ];
@@ -13,7 +14,7 @@ const localhost = [ '127.0.0.1' ];
const resolver = new dns.Resolver();
resolver.resolve('localhost', common.mustCall());
common.expectsError(resolver.setServers.bind(resolver, localhost), {
assert.throws(resolver.setServers.bind(resolver, localhost), {
code: 'ERR_DNS_SET_SERVERS_FAILED',
message: /^c-ares failed to set servers: "There are pending queries\." \[.+\]$/g
});
+30 -30
View File
@@ -96,14 +96,14 @@ const goog = [
];
dns.setServers(goog);
assert.deepStrictEqual(dns.getServers(), goog);
common.expectsError(() => dns.setServers(['foobar']), {
assert.throws(() => dns.setServers(['foobar']), {
code: 'ERR_INVALID_IP_ADDRESS',
type: TypeError,
name: 'TypeError',
message: 'Invalid IP address: foobar'
});
common.expectsError(() => dns.setServers(['127.0.0.1:va']), {
assert.throws(() => dns.setServers(['127.0.0.1:va']), {
code: 'ERR_INVALID_IP_ADDRESS',
type: TypeError,
name: 'TypeError',
message: 'Invalid IP address: 127.0.0.1:va'
});
assert.deepStrictEqual(dns.getServers(), goog);
@@ -142,36 +142,36 @@ assert.deepStrictEqual(dns.getServers(), []);
{
const errObj = {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "rrtype" argument must be of type string. ' +
'Received an instance of Array'
};
common.expectsError(() => {
assert.throws(() => {
dns.resolve('example.com', [], common.mustNotCall());
}, errObj);
common.expectsError(() => {
assert.throws(() => {
dnsPromises.resolve('example.com', []);
}, errObj);
}
{
const errObj = {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "name" argument must be of type string. ' +
'Received undefined'
};
common.expectsError(() => {
assert.throws(() => {
dnsPromises.resolve();
}, errObj);
}
// dns.lookup should accept only falsey and string values
{
const errorReg = common.expectsError({
const errorReg = {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: /^The "hostname" argument must be of type string\. Received .*/
}, 10);
};
assert.throws(() => dns.lookup({}, common.mustNotCall()), errorReg);
@@ -219,26 +219,26 @@ assert.deepStrictEqual(dns.getServers(), []);
const hints = (dns.V4MAPPED | dns.ADDRCONFIG) + 1;
const err = {
code: 'ERR_INVALID_OPT_VALUE',
type: TypeError,
name: 'TypeError',
message: /The value "\d+" is invalid for option "hints"/
};
common.expectsError(() => {
assert.throws(() => {
dnsPromises.lookup('nodejs.org', { hints });
}, err);
common.expectsError(() => {
assert.throws(() => {
dns.lookup('nodejs.org', { hints }, common.mustNotCall());
}, err);
}
common.expectsError(() => dns.lookup('nodejs.org'), {
assert.throws(() => dns.lookup('nodejs.org'), {
code: 'ERR_INVALID_CALLBACK',
type: TypeError
name: 'TypeError'
});
common.expectsError(() => dns.lookup('nodejs.org', 4), {
assert.throws(() => dns.lookup('nodejs.org', 4), {
code: 'ERR_INVALID_CALLBACK',
type: TypeError
name: 'TypeError'
});
dns.lookup('', { family: 4, hints: 0 }, common.mustCall());
@@ -264,29 +264,29 @@ dns.lookup('', {
{
const err = {
code: 'ERR_MISSING_ARGS',
type: TypeError,
name: 'TypeError',
message: 'The "address", "port", and "callback" arguments must be ' +
'specified'
};
common.expectsError(() => dns.lookupService('0.0.0.0'), err);
assert.throws(() => dns.lookupService('0.0.0.0'), err);
err.message = 'The "address" and "port" arguments must be specified';
common.expectsError(() => dnsPromises.lookupService('0.0.0.0'), err);
assert.throws(() => dnsPromises.lookupService('0.0.0.0'), err);
}
{
const invalidAddress = 'fasdfdsaf';
const err = {
code: 'ERR_INVALID_OPT_VALUE',
type: TypeError,
name: 'TypeError',
message: `The value "${invalidAddress}" is invalid for option "address"`
};
common.expectsError(() => {
assert.throws(() => {
dnsPromises.lookupService(invalidAddress, 0);
}, err);
common.expectsError(() => {
assert.throws(() => {
dns.lookupService(invalidAddress, 0, common.mustNotCall());
}, err);
}
@@ -296,14 +296,14 @@ const portErr = (port) => {
code: 'ERR_SOCKET_BAD_PORT',
message:
`Port should be >= 0 and < 65536. Received ${port}.`,
type: RangeError
name: 'RangeError'
};
common.expectsError(() => {
assert.throws(() => {
dnsPromises.lookupService('0.0.0.0', port);
}, err);
common.expectsError(() => {
assert.throws(() => {
dns.lookupService('0.0.0.0', port, common.mustNotCall());
}, err);
};
@@ -312,11 +312,11 @@ portErr(undefined);
portErr(65538);
portErr('test');
common.expectsError(() => {
assert.throws(() => {
dns.lookupService('0.0.0.0', 80, null);
}, {
code: 'ERR_INVALID_CALLBACK',
type: TypeError
name: 'TypeError'
});
{
@@ -1,13 +1,14 @@
'use strict';
const common = require('../common');
const assert = require('assert');
process.setUncaughtExceptionCaptureCallback(common.mustNotCall());
common.expectsError(
assert.throws(
() => require('domain'),
{
code: 'ERR_DOMAIN_CALLBACK_NOT_AVAILABLE',
type: Error,
name: 'Error',
message: /^A callback was registered.*with using the `domain` module/
}
);
@@ -12,7 +12,7 @@ assert.throws(
common.expectsError(
{
code: 'ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE',
type: Error,
name: 'Error',
message: /^The `domain` module is in use, which is mutually/
}
)(err);
@@ -1,31 +0,0 @@
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
common.skipIfEslintMissing();
const RuleTester = require('../../tools/node_modules/eslint').RuleTester;
const rule = require('../../tools/eslint-rules/prefer-common-expectserror');
const message = 'Please use common.expectsError(fn, err) instead of ' +
'assert.throws(fn, common.expectsError(err)).';
new RuleTester().run('prefer-common-expectserror', rule, {
valid: [
'assert.throws(fn, /[a-z]/)',
'assert.throws(function () {}, function() {})',
'common.expectsError(function() {}, err)'
],
invalid: [
{
code: 'assert.throws(function() {}, common.expectsError(err))',
errors: [{ message }]
},
{
code: 'assert.throws(fn, common.expectsError(err))',
errors: [{ message }]
}
]
});
@@ -278,14 +278,14 @@ function resetCaptureOnThrowInError() {
function argValidation() {
function testType(obj) {
common.expectsError(() => new EventEmitter({ captureRejections: obj }), {
assert.throws(() => new EventEmitter({ captureRejections: obj }), {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
name: 'TypeError'
});
common.expectsError(() => EventEmitter.captureRejections = obj, {
assert.throws(() => EventEmitter.captureRejections = obj, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
name: 'TypeError'
});
}
@@ -86,12 +86,12 @@ const EventEmitter = require('events');
}
// Verify that the listener must be a function
common.expectsError(() => {
assert.throws(() => {
const ee = new EventEmitter();
ee.on('foo', null);
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "listener" argument must be of type function. ' +
'Received null'
});
+8 -7
View File
@@ -1,36 +1,37 @@
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
const EventEmitter = require('events');
const util = require('util');
const EE = new EventEmitter();
common.expectsError(
assert.throws(
() => EE.emit('error', 'Accepts a string'),
{
code: 'ERR_UNHANDLED_ERROR',
type: Error,
name: 'Error',
message: "Unhandled error. ('Accepts a string')"
}
);
common.expectsError(
assert.throws(
() => EE.emit('error', { message: 'Error!' }),
{
code: 'ERR_UNHANDLED_ERROR',
type: Error,
name: 'Error',
message: "Unhandled error. ({ message: 'Error!' })"
}
);
common.expectsError(
assert.throws(
() => EE.emit('error', {
message: 'Error!',
[util.inspect.custom]() { throw new Error(); }
}),
{
code: 'ERR_UNHANDLED_ERROR',
type: Error,
name: 'Error',
message: 'Unhandled error. ([object Object])'
}
);
@@ -21,6 +21,7 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const events = require('events');
const { inspect } = require('util');
const e = new events.EventEmitter();
@@ -33,21 +34,21 @@ e.setMaxListeners(42);
const throwsObjs = [NaN, -1, 'and even this'];
for (const obj of throwsObjs) {
common.expectsError(
assert.throws(
() => e.setMaxListeners(obj),
{
code: 'ERR_OUT_OF_RANGE',
type: RangeError,
name: 'RangeError',
message: 'The value of "n" is out of range. ' +
`It must be a non-negative number. Received ${inspect(obj)}`
}
);
common.expectsError(
assert.throws(
() => events.defaultMaxListeners = obj,
{
code: 'ERR_OUT_OF_RANGE',
type: RangeError,
name: 'RangeError',
message: 'The value of "defaultMaxListeners" is out of range. ' +
`It must be a non-negative number. Received ${inspect(obj)}`
}
+2 -2
View File
@@ -50,12 +50,12 @@ e.once('e', common.mustCall());
e.emit('e');
// Verify that the listener must be a function
common.expectsError(() => {
assert.throws(() => {
const ee = new EventEmitter();
ee.once('foo', null);
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "listener" argument must be of type function. ' +
'Received null'
});
+2 -2
View File
@@ -19,12 +19,12 @@ myEE.prependOnceListener('foo',
myEE.emit('foo');
// Verify that the listener must be a function
common.expectsError(() => {
assert.throws(() => {
const ee = new EventEmitter();
ee.prependOnceListener('foo', null);
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "listener" argument must be of type function. ' +
'Received null'
});
@@ -145,12 +145,12 @@ function listener2() {}
}
// Verify that the removed listener must be a function
common.expectsError(() => {
assert.throws(() => {
const ee = new EventEmitter();
ee.removeListener('foo', null);
}, {
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
name: 'TypeError',
message: 'The "listener" argument must be of type function. ' +
'Received null'
});
+3 -3
View File
@@ -20,7 +20,7 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
require('../common');
const assert = require('assert');
const path = require('path');
@@ -65,14 +65,14 @@ file
assert.strictEqual(file.bytesWritten, EXPECTED.length * 2);
callbacks.close++;
common.expectsError(
assert.throws(
() => {
console.error('write after end should not be allowed');
file.write('should not work anymore');
},
{
code: 'ERR_STREAM_WRITE_AFTER_END',
type: Error,
name: 'Error',
message: 'write after end'
}
);
+4 -4
View File
@@ -186,9 +186,9 @@ const run_test_4 = common.mustCall(function() {
code: 'ERR_OUT_OF_RANGE',
message: 'The value of "start" is out of range. ' +
'It must be >= 0 and <= 2 ** 53 - 1. Received -5',
type: RangeError
name: 'RangeError'
};
common.expectsError(fn, err);
assert.throws(fn, err);
});
@@ -201,9 +201,9 @@ const run_test_5 = common.mustCall(function() {
code: 'ERR_OUT_OF_RANGE',
message: 'The value of "start" is out of range. It must be ' +
'>= 0 and <= 2 ** 53 - 1. Received 9_007_199_254_740_992',
type: RangeError
name: 'RangeError'
};
common.expectsError(fn, err);
assert.throws(fn, err);
});
run_test_1();
+4 -4
View File
@@ -135,22 +135,22 @@ fs.promises.access(readOnlyFile, fs.F_OK | fs.R_OK)
.catch(throwNextTick);
}
common.expectsError(
assert.throws(
() => {
fs.access(__filename, fs.F_OK);
},
{
code: 'ERR_INVALID_CALLBACK',
type: TypeError
name: 'TypeError'
});
common.expectsError(
assert.throws(
() => {
fs.access(__filename, fs.F_OK, {});
},
{
code: 'ERR_INVALID_CALLBACK',
type: TypeError
name: 'TypeError'
});
// Regular access should not throw.
Loaded 100 of 392 files, more files were not shown because too many files have changed in this diff. Show more