pax_global_header00006660000000000000000000000064134657762210014527gustar00rootroot0000000000000052 comment=8969d8eaa74357b5285d99cdd4ade4d993a1c183 commonjs-assert-2.0.0/000077500000000000000000000000001346577622100146525ustar00rootroot00000000000000commonjs-assert-2.0.0/.airtap.yml000066400000000000000000000003621346577622100167340ustar00rootroot00000000000000browsers: - name: chrome version: latest - name: firefox version: latest - name: safari version: latest - name: ie version: latest - name: microsoftedge version: latest sauce_connect: true loopback: airtap.local commonjs-assert-2.0.0/.gitignore000066400000000000000000000001041346577622100166350ustar00rootroot00000000000000build node_modules npm-debug.log package-lock.json yarn.lock *.swp commonjs-assert-2.0.0/.travis.yml000066400000000000000000000013021346577622100167570ustar00rootroot00000000000000language: node_js node_js: - 'stable' - '12' - '10' - '8' - '6' script: - 'npm test' # Run browser tests on one node version. - 'if [ "${TRAVIS_PULL_REQUEST}" = "false" ] && [ "${TRAVIS_NODE_VERSION}" = "stable" ]; then npm run test:browsers; fi' addons: sauce_connect: true hosts: - airtap.local env: global: - secure: qThuKBZQtkooAvzaYldECGNqvKGPRTnXx62IVyhSbFlsCY1VCmjhLldhyPDiZQ3JqL1XvSkK8OMDupiHqZnNE0nGijoO4M/kaEdjBB+jpjg3f8I6te2SNU935SbkfY9KHAaFXMZwdcq7Fk932AxWEu+FMSDM+080wNKpEATXDe4= - secure: O/scKjHLRcPN5ILV5qsSkksQ7qcZQdHWEUUPItmj/4+vmCc28bHpicoUxXG5A96iHvkBbdmky/nGCg464ZaNLk68m6hfEMDAR3J6mhM2Pf5C4QI/LlFlR1fob9sQ8lztwSGOItwdK8Rfrgb30RRVV71f6FxnaJ6PKMuMNT5S1AQ= commonjs-assert-2.0.0/CHANGELOG.md000066400000000000000000000010241346577622100164600ustar00rootroot00000000000000# assert change log All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ## 2.0.0 * Sync with Node.js master. ([@lukechilds](https://github.com/lukechilds) in [#44](https://github.com/browserify/commonjs-assert/pull/44)) **Note:** Support for IE9 and IE10 has been dropped. IE11 is still supported. ## 1.5.0 * Add strict mode APIs. ([@lukechilds](https://github.com/lukechilds) in [#41](https://github.com/browserify/commonjs-assert/pull/41)) commonjs-assert-2.0.0/LICENSE000066400000000000000000000021101346577622100156510ustar00rootroot00000000000000Copyright Joyent, Inc. and other Node contributors. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. commonjs-assert-2.0.0/README.md000066400000000000000000000053631346577622100161400ustar00rootroot00000000000000# assert > The [`assert`](https://nodejs.org/api/assert.html) module from Node.js, for the browser. [![Build Status](https://travis-ci.org/browserify/commonjs-assert.svg?branch=master)](https://travis-ci.org/browserify/commonjs-assert) [![npm](https://img.shields.io/npm/dm/assert.svg)](https://www.npmjs.com/package/assert) [![npm](https://img.shields.io/npm/v/assert.svg)](https://www.npmjs.com/package/assert) With browserify, simply `require('assert')` or use the `assert` global and you will get this module. The goal is to provide an API that is as functionally identical to the [Node.js `assert` API](https://nodejs.org/api/assert.html) as possible. Read the [official docs](https://nodejs.org/api/assert.html) for API documentation. ## Install To use this module directly (without browserify), install it as a dependency: ``` npm install assert ``` ## Usage The goal is to provide an API that is as functionally identical to the [Node.js `assert` API](https://nodejs.org/api/assert.html) as possible. Read the [official docs](https://nodejs.org/api/assert.html) for API documentation. ### Inconsistencies with Node.js `assert` Due to differences between browsers, some error properties such as `message` and `stack` will be inconsistent. However the assertion behaviour is as close as possible to Node.js and the same error `code` will always be used. ## Contributing To contribute, work on the source files. Then build and run the tests against the built files. Be careful to not introduce syntax that will be transpiled down to unsupported syntax. For example, `for...of` loops will be transpiled to use `Symbol.iterator` which is unavailable in IE. ### Build scripts #### `npm run build` Builds the project into the `build` dir. #### `npm run dev` Watches source files for changes and rebuilds them into the `build` dir. #### `npm run test` Builds the source files into the `build` dir and then runs the tests against the built project. #### `npm run test:nobuild` Runs the tests against the built project without rebuilding first. This is useful if you're debugging in the transpiled code and want to re-run the tests without overwriting any changes you may have made. #### `npm run test:source` Runs the tests against the unbuilt source files. This will only work on modern Node.js versions. #### `npm run test:browsers` Run browser tests against the all targets in the cloud. Requires airtap credentials to be configured on your machine. #### `npm run test:browsers:local` Run a local browser test server. No airtap configuration required. When paired with `npm run dev` any changes you make to the source files will be automatically transpiled and served on the next request to the test server. ## License MIT © Joyent, Inc. and other Node contributors commonjs-assert-2.0.0/assert.js000066400000000000000000000422041346577622100165130ustar00rootroot00000000000000// Currently in sync with Node.js lib/assert.js // https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b // Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; const { codes: { ERR_AMBIGUOUS_ARGUMENT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_INVALID_RETURN_VALUE, ERR_MISSING_ARGS } } = require('./internal/errors'); const AssertionError = require('./internal/assert/assertion_error'); const { inspect } = require('util/'); const { isPromise, isRegExp } = require('util/').types; const objectAssign = Object.assign ? Object.assign : require('es6-object-assign').assign; const objectIs = Object.is ? Object.is : require('object-is'); const errorCache = new Map(); let isDeepEqual; let isDeepStrictEqual; let parseExpressionAt; let findNodeAround; let decoder; function lazyLoadComparison() { const comparison = require('./internal/util/comparisons'); isDeepEqual = comparison.isDeepEqual; isDeepStrictEqual = comparison.isDeepStrictEqual; } // Escape control characters but not \n and \t to keep the line breaks and // indentation intact. // eslint-disable-next-line no-control-regex const escapeSequencesRegExp = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g; const meta = [ '\\u0000', '\\u0001', '\\u0002', '\\u0003', '\\u0004', '\\u0005', '\\u0006', '\\u0007', '\\b', '', '', '\\u000b', '\\f', '', '\\u000e', '\\u000f', '\\u0010', '\\u0011', '\\u0012', '\\u0013', '\\u0014', '\\u0015', '\\u0016', '\\u0017', '\\u0018', '\\u0019', '\\u001a', '\\u001b', '\\u001c', '\\u001d', '\\u001e', '\\u001f' ]; const escapeFn = (str) => meta[str.charCodeAt(0)]; let warned = false; // The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. const assert = module.exports = ok; const NO_EXCEPTION_SENTINEL = {}; // All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function innerFail(obj) { if (obj.message instanceof Error) throw obj.message; throw new AssertionError(obj); } function fail(actual, expected, message, operator, stackStartFn) { const argsLen = arguments.length; let internalMessage; if (argsLen === 0) { internalMessage = 'Failed'; } else if (argsLen === 1) { message = actual; actual = undefined; } else { if (warned === false) { warned = true; const warn = process.emitWarning ? process.emitWarning : console.warn.bind(console); warn( 'assert.fail() with more than one argument is deprecated. ' + 'Please use assert.strictEqual() instead or only pass a message.', 'DeprecationWarning', 'DEP0094' ); } if (argsLen === 2) operator = '!='; } if (message instanceof Error) throw message; const errArgs = { actual, expected, operator: operator === undefined ? 'fail' : operator, stackStartFn: stackStartFn || fail }; if (message !== undefined) { errArgs.message = message; } const err = new AssertionError(errArgs); if (internalMessage) { err.message = internalMessage; err.generatedMessage = true; } throw err; } assert.fail = fail; // The AssertionError is defined in internal/error. assert.AssertionError = AssertionError; function innerOk(fn, argLen, value, message) { if (!value) { let generatedMessage = false; if (argLen === 0) { generatedMessage = true; message = 'No value argument passed to `assert.ok()`'; } else if (message instanceof Error) { throw message; } const err = new AssertionError({ actual: value, expected: true, message, operator: '==', stackStartFn: fn }); err.generatedMessage = generatedMessage; throw err; } } // Pure assertion tests whether a value is truthy, as determined // by !!value. function ok(...args) { innerOk(ok, args.length, ...args); } assert.ok = ok; // The equality assertion tests shallow, coercive equality with ==. /* eslint-disable no-restricted-properties */ assert.equal = function equal(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } // eslint-disable-next-line eqeqeq if (actual != expected) { innerFail({ actual, expected, message, operator: '==', stackStartFn: equal }); } }; // The non-equality assertion tests for whether two objects are not // equal with !=. assert.notEqual = function notEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } // eslint-disable-next-line eqeqeq if (actual == expected) { innerFail({ actual, expected, message, operator: '!=', stackStartFn: notEqual }); } }; // The equivalence assertion tests a deep equality relation. assert.deepEqual = function deepEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (isDeepEqual === undefined) lazyLoadComparison(); if (!isDeepEqual(actual, expected)) { innerFail({ actual, expected, message, operator: 'deepEqual', stackStartFn: deepEqual }); } }; // The non-equivalence assertion tests for any deep inequality. assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (isDeepEqual === undefined) lazyLoadComparison(); if (isDeepEqual(actual, expected)) { innerFail({ actual, expected, message, operator: 'notDeepEqual', stackStartFn: notDeepEqual }); } }; /* eslint-enable */ assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (isDeepEqual === undefined) lazyLoadComparison(); if (!isDeepStrictEqual(actual, expected)) { innerFail({ actual, expected, message, operator: 'deepStrictEqual', stackStartFn: deepStrictEqual }); } }; assert.notDeepStrictEqual = notDeepStrictEqual; function notDeepStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (isDeepEqual === undefined) lazyLoadComparison(); if (isDeepStrictEqual(actual, expected)) { innerFail({ actual, expected, message, operator: 'notDeepStrictEqual', stackStartFn: notDeepStrictEqual }); } } assert.strictEqual = function strictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (!objectIs(actual, expected)) { innerFail({ actual, expected, message, operator: 'strictEqual', stackStartFn: strictEqual }); } }; assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (objectIs(actual, expected)) { innerFail({ actual, expected, message, operator: 'notStrictEqual', stackStartFn: notStrictEqual }); } }; class Comparison { constructor(obj, keys, actual) { keys.forEach(key => { if (key in obj) { if (actual !== undefined && typeof actual[key] === 'string' && isRegExp(obj[key]) && obj[key].test(actual[key]) ) { this[key] = actual[key]; } else { this[key] = obj[key]; } } }); } } function compareExceptionKey(actual, expected, key, message, keys, fn) { if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) { if (!message) { // Create placeholder objects to create a nice output. const a = new Comparison(actual, keys); const b = new Comparison(expected, keys, actual); const err = new AssertionError({ actual: a, expected: b, operator: 'deepStrictEqual', stackStartFn: fn }); err.actual = actual; err.expected = expected; err.operator = fn.name; throw err; } innerFail({ actual, expected, message, operator: fn.name, stackStartFn: fn }); } } function expectedException(actual, expected, msg, fn) { if (typeof expected !== 'function') { if (isRegExp(expected)) return expected.test(actual); // assert.doesNotThrow does not accept objects. if (arguments.length === 2) { throw new ERR_INVALID_ARG_TYPE( 'expected', ['Function', 'RegExp'], expected ); } // Handle primitives properly. if (typeof actual !== 'object' || actual === null) { const err = new AssertionError({ actual, expected, message: msg, operator: 'deepStrictEqual', stackStartFn: fn }); err.operator = fn.name; throw err; } const keys = Object.keys(expected); // Special handle errors to make sure the name and the message are compared // as well. if (expected instanceof Error) { keys.push('name', 'message'); } else if (keys.length === 0) { throw new ERR_INVALID_ARG_VALUE('error', expected, 'may not be an empty object'); } if (isDeepEqual === undefined) lazyLoadComparison(); keys.forEach(key => { if ( typeof actual[key] === 'string' && isRegExp(expected[key]) && expected[key].test(actual[key]) ) { return; } compareExceptionKey(actual, expected, key, msg, keys, fn); }); return true; } // Guard instanceof against arrow functions as they don't have a prototype. if (expected.prototype !== undefined && actual instanceof expected) { return true; } if (Error.isPrototypeOf(expected)) { return false; } return expected.call({}, actual) === true; } function getActual(fn) { if (typeof fn !== 'function') { throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn); } try { fn(); } catch (e) { return e; } return NO_EXCEPTION_SENTINEL; } function checkIsPromise(obj) { // Accept native ES6 promises and promises that are implemented in a similar // way. Do not accept thenables that use a function as `obj` and that have no // `catch` handler. // TODO: thenables are checked up until they have the correct methods, // but according to documentation, the `then` method should receive // the `fulfill` and `reject` arguments as well or it may be never resolved. return isPromise(obj) || obj !== null && typeof obj === 'object' && typeof obj.then === 'function' && typeof obj.catch === 'function'; } function waitForActual(promiseFn) { return Promise.resolve().then(() => { let resultPromise; if (typeof promiseFn === 'function') { // Return a rejected promise if `promiseFn` throws synchronously. resultPromise = promiseFn(); // Fail in case no promise is returned. if (!checkIsPromise(resultPromise)) { throw new ERR_INVALID_RETURN_VALUE('instance of Promise', 'promiseFn', resultPromise); } } else if (checkIsPromise(promiseFn)) { resultPromise = promiseFn; } else { throw new ERR_INVALID_ARG_TYPE('promiseFn', ['Function', 'Promise'], promiseFn); } return Promise.resolve().then(() => resultPromise) .then(() => NO_EXCEPTION_SENTINEL) .catch(e => e); }); } function expectsError(stackStartFn, actual, error, message) { if (typeof error === 'string') { if (arguments.length === 4) { throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); } if (typeof actual === 'object' && actual !== null) { if (actual.message === error) { throw new ERR_AMBIGUOUS_ARGUMENT( 'error/message', `The error message "${actual.message}" is identical to the message.` ); } } else if (actual === error) { throw new ERR_AMBIGUOUS_ARGUMENT( 'error/message', `The error "${actual}" is identical to the message.` ); } message = error; error = undefined; } else if (error != null && typeof error !== 'object' && typeof error !== 'function') { throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); } if (actual === NO_EXCEPTION_SENTINEL) { let details = ''; if (error && error.name) { details += ` (${error.name})`; } details += message ? `: ${message}` : '.'; const fnType = stackStartFn.name === 'rejects' ? 'rejection' : 'exception'; innerFail({ actual: undefined, expected: error, operator: stackStartFn.name, message: `Missing expected ${fnType}${details}`, stackStartFn }); } if (error && !expectedException(actual, error, message, stackStartFn)) { throw actual; } } function expectsNoError(stackStartFn, actual, error, message) { if (actual === NO_EXCEPTION_SENTINEL) return; if (typeof error === 'string') { message = error; error = undefined; } if (!error || expectedException(actual, error)) { const details = message ? `: ${message}` : '.'; const fnType = stackStartFn.name === 'doesNotReject' ? 'rejection' : 'exception'; innerFail({ actual, expected: error, operator: stackStartFn.name, message: `Got unwanted ${fnType}${details}\n` + `Actual message: "${actual && actual.message}"`, stackStartFn }); } throw actual; } assert.throws = function throws(promiseFn, ...args) { expectsError(throws, getActual(promiseFn), ...args); }; assert.rejects = function rejects(promiseFn, ...args) { return waitForActual(promiseFn).then(result => { return expectsError(rejects, result, ...args); }); }; assert.doesNotThrow = function doesNotThrow(fn, ...args) { expectsNoError(doesNotThrow, getActual(fn), ...args); }; assert.doesNotReject = function doesNotReject(fn, ...args) { return waitForActual(fn).then(result => { return expectsNoError(doesNotReject, result, ...args); }); }; assert.ifError = function ifError(err) { if (err !== null && err !== undefined) { let message = 'ifError got unwanted exception: '; if (typeof err === 'object' && typeof err.message === 'string') { if (err.message.length === 0 && err.constructor) { message += err.constructor.name; } else { message += err.message; } } else { message += inspect(err); } const newErr = new AssertionError({ actual: err, expected: null, operator: 'ifError', message, stackStartFn: ifError }); // Make sure we actually have a stack trace! const origStack = err.stack; if (typeof origStack === 'string') { // This will remove any duplicated frames from the error frames taken // from within `ifError` and add the original error frames to the newly // created ones. const tmp2 = origStack.split('\n'); tmp2.shift(); // Filter all frames existing in err.stack. let tmp1 = newErr.stack.split('\n'); for (var i = 0; i < tmp2.length; i++) { // Find the first occurrence of the frame. const pos = tmp1.indexOf(tmp2[i]); if (pos !== -1) { // Only keep new frames. tmp1 = tmp1.slice(0, pos); break; } } newErr.stack = `${tmp1.join('\n')}\n${tmp2.join('\n')}`; } throw newErr; } }; // Expose a strict only variant of assert function strict(...args) { innerOk(strict, args.length, ...args); } assert.strict = objectAssign(strict, assert, { equal: assert.strictEqual, deepEqual: assert.deepStrictEqual, notEqual: assert.notStrictEqual, notDeepEqual: assert.notDeepStrictEqual }); assert.strict.strict = assert.strict; commonjs-assert-2.0.0/babel.config.js000066400000000000000000000003331346577622100175200ustar00rootroot00000000000000const presets = [ [ "@babel/env", { targets: { edge: "18", firefox: "66", chrome: "73", safari: "12", ie: "11" } }, ], ]; module.exports = {presets}; commonjs-assert-2.0.0/internal/000077500000000000000000000000001346577622100164665ustar00rootroot00000000000000commonjs-assert-2.0.0/internal/assert/000077500000000000000000000000001346577622100177675ustar00rootroot00000000000000commonjs-assert-2.0.0/internal/assert/assertion_error.js000066400000000000000000000375401346577622100235560ustar00rootroot00000000000000// Currently in sync with Node.js lib/internal/assert/assertion_error.js // https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c 'use strict'; const { inspect } = require('util/'); const { codes: { ERR_INVALID_ARG_TYPE } } = require('../errors'); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat function repeat(str, count) { count = Math.floor(count); if (str.length == 0 || count == 0) return ''; var maxCount = str.length * count; count = Math.floor(Math.log(count) / Math.log(2)); while (count) { str += str; count--; } str += str.substring(0, maxCount - str.length); return str; } let blue = ''; let green = ''; let red = ''; let white = ''; const kReadableOperator = { deepStrictEqual: 'Expected values to be strictly deep-equal:', strictEqual: 'Expected values to be strictly equal:', strictEqualObject: 'Expected "actual" to be reference-equal to "expected":', deepEqual: 'Expected values to be loosely deep-equal:', equal: 'Expected values to be loosely equal:', notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:', notStrictEqual: 'Expected "actual" to be strictly unequal to:', notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":', notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:', notEqual: 'Expected "actual" to be loosely unequal to:', notIdentical: 'Values identical but not reference-equal:', }; // Comparing short primitives should just show === / !== instead of using the // diff. const kMaxShortLength = 10; function copyError(source) { const keys = Object.keys(source); const target = Object.create(Object.getPrototypeOf(source)); keys.forEach(key => { target[key] = source[key]; }); Object.defineProperty(target, 'message', { value: source.message }); return target; } function inspectValue(val) { // The util.inspect default values could be changed. This makes sure the // error messages contain the necessary information nevertheless. return inspect( val, { compact: false, customInspect: false, depth: 1000, maxArrayLength: Infinity, // Assert compares only enumerable properties (with a few exceptions). showHidden: false, // Having a long line as error is better than wrapping the line for // comparison for now. // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we // have meta information about the inspected properties (i.e., know where // in what line the property starts and ends). breakLength: Infinity, // Assert does not detect proxies currently. showProxy: false, sorted: true, // Inspect getters as we also check them when comparing entries. getters: true } ); } function createErrDiff(actual, expected, operator) { let other = ''; let res = ''; let lastPos = 0; let end = ''; let skipped = false; const actualInspected = inspectValue(actual); const actualLines = actualInspected.split('\n'); const expectedLines = inspectValue(expected).split('\n'); let i = 0; let indicator = ''; // In case both values are objects explicitly mark them as not reference equal // for the `strictEqual` operator. if (operator === 'strictEqual' && typeof actual === 'object' && typeof expected === 'object' && actual !== null && expected !== null) { operator = 'strictEqualObject'; } // If "actual" and "expected" fit on a single line and they are not strictly // equal, check further special handling. if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) { const inputLength = actualLines[0].length + expectedLines[0].length; // If the character length of "actual" and "expected" together is less than // kMaxShortLength and if neither is an object and at least one of them is // not `zero`, use the strict equal comparison to visualize the output. if (inputLength <= kMaxShortLength) { if ((typeof actual !== 'object' || actual === null) && (typeof expected !== 'object' || expected === null) && (actual !== 0 || expected !== 0)) { // -0 === +0 return `${kReadableOperator[operator]}\n\n` + `${actualLines[0]} !== ${expectedLines[0]}\n`; } } else if (operator !== 'strictEqualObject') { // If the stderr is a tty and the input length is lower than the current // columns per line, add a mismatch indicator below the output. If it is // not a tty, use a default value of 80 characters. const maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80; if (inputLength < maxLength) { while (actualLines[0][i] === expectedLines[0][i]) { i++; } // Ignore the first characters. if (i > 2) { // Add position indicator for the first mismatch in case it is a // single line and the input length is less than the column length. indicator = `\n ${repeat(' ', i)}^`; i = 0; } } } } // Remove all ending lines that match (this optimizes the output for // readability by reducing the number of total changed lines). let a = actualLines[actualLines.length - 1]; let b = expectedLines[expectedLines.length - 1]; while (a === b) { if (i++ < 2) { end = `\n ${a}${end}`; } else { other = a; } actualLines.pop(); expectedLines.pop(); if (actualLines.length === 0 || expectedLines.length === 0) break; a = actualLines[actualLines.length - 1]; b = expectedLines[expectedLines.length - 1]; } const maxLines = Math.max(actualLines.length, expectedLines.length); // Strict equal with identical objects that are not identical by reference. // E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() }) if (maxLines === 0) { // We have to get the result again. The lines were all removed before. const actualLines = actualInspected.split('\n'); // Only remove lines in case it makes sense to collapse those. // TODO: Accept env to always show the full error. if (actualLines.length > 30) { actualLines[26] = `${blue}...${white}`; while (actualLines.length > 27) { actualLines.pop(); } } return `${kReadableOperator.notIdentical}\n\n${actualLines.join('\n')}\n`; } if (i > 3) { end = `\n${blue}...${white}${end}`; skipped = true; } if (other !== '') { end = `\n ${other}${end}`; other = ''; } let printedLines = 0; const msg = kReadableOperator[operator] + `\n${green}+ actual${white} ${red}- expected${white}`; const skippedMsg = ` ${blue}...${white} Lines skipped`; for (i = 0; i < maxLines; i++) { // Only extra expected lines exist const cur = i - lastPos; if (actualLines.length < i + 1) { // If the last diverging line is more than one line above and the // current line is at least line three, add some of the former lines and // also add dots to indicate skipped entries. if (cur > 1 && i > 2) { if (cur > 4) { res += `\n${blue}...${white}`; skipped = true; } else if (cur > 3) { res += `\n ${expectedLines[i - 2]}`; printedLines++; } res += `\n ${expectedLines[i - 1]}`; printedLines++; } // Mark the current line as the last diverging one. lastPos = i; // Add the expected line to the cache. other += `\n${red}-${white} ${expectedLines[i]}`; printedLines++; // Only extra actual lines exist } else if (expectedLines.length < i + 1) { // If the last diverging line is more than one line above and the // current line is at least line three, add some of the former lines and // also add dots to indicate skipped entries. if (cur > 1 && i > 2) { if (cur > 4) { res += `\n${blue}...${white}`; skipped = true; } else if (cur > 3) { res += `\n ${actualLines[i - 2]}`; printedLines++; } res += `\n ${actualLines[i - 1]}`; printedLines++; } // Mark the current line as the last diverging one. lastPos = i; // Add the actual line to the result. res += `\n${green}+${white} ${actualLines[i]}`; printedLines++; // Lines diverge } else { const expectedLine = expectedLines[i]; let actualLine = actualLines[i]; // If the lines diverge, specifically check for lines that only diverge by // a trailing comma. In that case it is actually identical and we should // mark it as such. let divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ',') || actualLine.slice(0, -1) !== expectedLine); // If the expected line has a trailing comma but is otherwise identical, // add a comma at the end of the actual line. Otherwise the output could // look weird as in: // // [ // 1 // No comma at the end! // + 2 // ] // if (divergingLines && endsWith(expectedLine, ',') && expectedLine.slice(0, -1) === actualLine) { divergingLines = false; actualLine += ','; } if (divergingLines) { // If the last diverging line is more than one line above and the // current line is at least line three, add some of the former lines and // also add dots to indicate skipped entries. if (cur > 1 && i > 2) { if (cur > 4) { res += `\n${blue}...${white}`; skipped = true; } else if (cur > 3) { res += `\n ${actualLines[i - 2]}`; printedLines++; } res += `\n ${actualLines[i - 1]}`; printedLines++; } // Mark the current line as the last diverging one. lastPos = i; // Add the actual line to the result and cache the expected diverging // line so consecutive diverging lines show up as +++--- and not +-+-+-. res += `\n${green}+${white} ${actualLine}`; other += `\n${red}-${white} ${expectedLine}`; printedLines += 2; // Lines are identical } else { // Add all cached information to the result before adding other things // and reset the cache. res += other; other = ''; // If the last diverging line is exactly one line above or if it is the // very first line, add the line to the result. if (cur === 1 || i === 0) { res += `\n ${actualLine}`; printedLines++; } } } // Inspected object to big (Show ~20 rows max) if (printedLines > 20 && i < maxLines - 2) { return `${msg}${skippedMsg}\n${res}\n${blue}...${white}${other}\n` + `${blue}...${white}`; } } return `${msg}${skipped ? skippedMsg : ''}\n${res}${other}${end}${indicator}`; } class AssertionError extends Error { constructor(options) { if (typeof options !== 'object' || options === null) { throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); } const { message, operator, stackStartFn } = options; let { actual, expected } = options; const limit = Error.stackTraceLimit; Error.stackTraceLimit = 0; if (message != null) { super(String(message)); } else { if (process.stderr && process.stderr.isTTY) { // Reset on each call to make sure we handle dynamically set environment // variables correct. if ( process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1 ) { blue = '\u001b[34m'; green = '\u001b[32m'; white = '\u001b[39m'; red = '\u001b[31m'; } else { blue = ''; green = ''; white = ''; red = ''; } } // Prevent the error stack from being visible by duplicating the error // in a very close way to the original in case both sides are actually // instances of Error. if (typeof actual === 'object' && actual !== null && typeof expected === 'object' && expected !== null && 'stack' in actual && actual instanceof Error && 'stack' in expected && expected instanceof Error) { actual = copyError(actual); expected = copyError(expected); } if (operator === 'deepStrictEqual' || operator === 'strictEqual') { super(createErrDiff(actual, expected, operator)); } else if (operator === 'notDeepStrictEqual' || operator === 'notStrictEqual') { // In case the objects are equal but the operator requires unequal, show // the first object and say A equals B let base = kReadableOperator[operator]; const res = inspectValue(actual).split('\n'); // In case "actual" is an object, it should not be reference equal. if (operator === 'notStrictEqual' && typeof actual === 'object' && actual !== null) { base = kReadableOperator.notStrictEqualObject; } // Only remove lines in case it makes sense to collapse those. // TODO: Accept env to always show the full error. if (res.length > 30) { res[26] = `${blue}...${white}`; while (res.length > 27) { res.pop(); } } // Only print a single input. if (res.length === 1) { super(`${base} ${res[0]}`); } else { super(`${base}\n\n${res.join('\n')}\n`); } } else { let res = inspectValue(actual); let other = ''; const knownOperators = kReadableOperator[operator]; if (operator === 'notDeepEqual' || operator === 'notEqual') { res = `${kReadableOperator[operator]}\n\n${res}`; if (res.length > 1024) { res = `${res.slice(0, 1021)}...`; } } else { other = `${inspectValue(expected)}`; if (res.length > 512) { res = `${res.slice(0, 509)}...`; } if (other.length > 512) { other = `${other.slice(0, 509)}...`; } if (operator === 'deepEqual' || operator === 'equal') { res = `${knownOperators}\n\n${res}\n\nshould equal\n\n`; } else { other = ` ${operator} ${other}`; } } super(`${res}${other}`); } } Error.stackTraceLimit = limit; this.generatedMessage = !message; Object.defineProperty(this, 'name', { value: 'AssertionError [ERR_ASSERTION]', enumerable: false, writable: true, configurable: true }); this.code = 'ERR_ASSERTION'; this.actual = actual; this.expected = expected; this.operator = operator; if (Error.captureStackTrace) { // eslint-disable-next-line no-restricted-syntax Error.captureStackTrace(this, stackStartFn); } // Create error message including the error code in the name. this.stack; // Reset the name. this.name = 'AssertionError'; } toString() { return `${this.name} [${this.code}]: ${this.message}`; } [inspect.custom](recurseTimes, ctx) { // This limits the `actual` and `expected` property default inspection to // the minimum depth. Otherwise those values would be too verbose compared // to the actual error message which contains a combined view of these two // input values. return inspect(this, { ...ctx, customInspect: false, depth: 0 }); } } module.exports = AssertionError; commonjs-assert-2.0.0/internal/errors.js000066400000000000000000000115521346577622100203440ustar00rootroot00000000000000// Currently in sync with Node.js lib/internal/errors.js // https://github.com/nodejs/node/commit/3b044962c48fe313905877a96b5d0894a5404f6f /* eslint node-core/documented-errors: "error" */ /* eslint node-core/alphabetize-errors: "error" */ /* eslint node-core/prefer-util-format-errors: "error" */ 'use strict'; // The whole point behind this internal module is to allow Node.js to no // longer be forced to treat every error message change as a semver-major // change. The NodeError classes here all expose a `code` property whose // value statically and permanently identifies the error. While the error // message may change, the code should not. const codes = {}; // Lazy loaded let assert; let util; function createErrorType(code, message, Base) { if (!Base) { Base = Error } function getMessage (arg1, arg2, arg3) { if (typeof message === 'string') { return message } else { return message(arg1, arg2, arg3) } } class NodeError extends Base { constructor (arg1, arg2, arg3) { super(getMessage(arg1, arg2, arg3)); this.code = code; } } codes[code] = NodeError; } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js function oneOf(expected, thing) { if (Array.isArray(expected)) { const len = expected.length; expected = expected.map((i) => String(i)); if (len > 2) { return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + expected[len - 1]; } else if (len === 2) { return `one of ${thing} ${expected[0]} or ${expected[1]}`; } else { return `of ${thing} ${expected[0]}`; } } else { return `of ${thing} ${String(expected)}`; } } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes function includes(str, search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError); createErrorType('ERR_INVALID_ARG_TYPE', (name, expected, actual) => { if (assert === undefined) assert = require('../assert'); assert(typeof name === 'string', "'name' must be a string"); // determiner: 'must be' or 'must not be' let determiner; if (typeof expected === 'string' && startsWith(expected, 'not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } let msg; if (endsWith(name, ' argument')) { // For cases like 'first argument' msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; } else { const type = includes(name, '.') ? 'property' : 'argument'; msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; } // TODO(BridgeAR): Improve the output by showing `null` and similar. msg += `. Received type ${typeof actual}`; return msg; }, TypeError); createErrorType('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => { if (util === undefined) util = require('util/'); let inspected = util.inspect(value); if (inspected.length > 128) { inspected = `${inspected.slice(0, 128)}...`; } return `The argument '${name}' ${reason}. Received ${inspected}`; }, TypeError, RangeError); createErrorType('ERR_INVALID_RETURN_VALUE', (input, name, value) => { let type; if (value && value.constructor && value.constructor.name) { type = `instance of ${value.constructor.name}`; } else { type = `type ${typeof value}`; } return `Expected ${input} to be returned from the "${name}"` + ` function but got ${type}.`; }, TypeError); createErrorType('ERR_MISSING_ARGS', (...args) => { if (assert === undefined) assert = require('../assert'); assert(args.length > 0, 'At least one arg needs to be specified'); let msg = 'The '; const len = args.length; args = args.map((a) => `"${a}"`); switch (len) { case 1: msg += `${args[0]} argument`; break; case 2: msg += `${args[0]} and ${args[1]} arguments`; break; default: msg += args.slice(0, len - 1).join(', '); msg += `, and ${args[len - 1]} arguments`; break; } return `${msg} must be specified`; }, TypeError); module.exports.codes = codes; commonjs-assert-2.0.0/internal/util/000077500000000000000000000000001346577622100174435ustar00rootroot00000000000000commonjs-assert-2.0.0/internal/util/comparisons.js000066400000000000000000000454641346577622100223530ustar00rootroot00000000000000// Currently in sync with Node.js lib/internal/util/comparisons.js // https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 'use strict'; const regexFlagsSupported = /a/g.flags !== undefined; const arrayFromSet = set => { const array = []; set.forEach(value => array.push(value)); return array; }; const arrayFromMap = map => { const array = []; map.forEach((value, key) => array.push([key, value])); return array; }; const objectIs = Object.is ? Object.is : require('object-is'); const objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : () => []; const numberIsNaN = Number.isNaN ? Number.isNaN : require('is-nan'); function uncurryThis(f) { return f.call.bind(f); } const hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); const propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); const objectToString = uncurryThis(Object.prototype.toString); const { isAnyArrayBuffer, isArrayBufferView, isDate, isMap, isRegExp, isSet, isNativeError, isBoxedPrimitive, isNumberObject, isStringObject, isBooleanObject, isBigIntObject, isSymbolObject, isFloat32Array, isFloat64Array } = require('util/').types; function isNonIndex(key) { if (key.length === 0 || key.length > 10) return true; for (var i = 0; i < key.length; i++) { const code = key.charCodeAt(i); if (code < 48 || code > 57) return true; } // The maximum size for an array is 2 ** 32 -1. return key.length === 10 && key >= 2 ** 32; } function getOwnNonIndexProperties(value) { return Object.keys(value) .filter(isNonIndex) .concat( objectGetOwnPropertySymbols(value) .filter(Object.prototype.propertyIsEnumerable.bind(value)) ); } // Taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js // original notice: /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ function compare(a, b) { if (a === b) { return 0; } var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) { return -1; } if (y < x) { return 1; } return 0; } const ONLY_ENUMERABLE = undefined; const kStrict = true; const kLoose = false; const kNoIterator = 0; const kIsArray = 1; const kIsSet = 2; const kIsMap = 3; // Check if they have the same source and flags function areSimilarRegExps(a, b) { return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b); } function areSimilarFloatArrays(a, b) { if (a.byteLength !== b.byteLength) { return false; } for (var offset = 0; offset < a.byteLength; offset++) { if (a[offset] !== b[offset]) { return false; } } return true; } function areSimilarTypedArrays(a, b) { if (a.byteLength !== b.byteLength) { return false; } return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0; } function areEqualArrayBuffers(buf1, buf2) { return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0; } function isEqualBoxedPrimitive(val1, val2) { if (isNumberObject(val1)) { return isNumberObject(val2) && objectIs(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2)); } if (isStringObject(val1)) { return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2); } if (isBooleanObject(val1)) { return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2); } if (isBigIntObject(val1)) { return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2); } return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2); } // Notes: Type tags are historical [[Class]] properties that can be set by // FunctionTemplate::SetClassName() in C++ or Symbol.toStringTag in JS // and retrieved using Object.prototype.toString.call(obj) in JS // See https://tc39.github.io/ecma262/#sec-object.prototype.tostring // for a list of tags pre-defined in the spec. // There are some unspecified tags in the wild too (e.g. typed array tags). // Since tags can be altered, they only serve fast failures // // Typed arrays and buffers are checked by comparing the content in their // underlying ArrayBuffer. This optimization requires that it's // reasonable to interpret their underlying memory in the same way, // which is checked by comparing their type tags. // (e.g. a Uint8Array and a Uint16Array with the same memory content // could still be different because they will be interpreted differently). // // For strict comparison, objects should have // a) The same built-in type tags // b) The same prototypes. function innerDeepEqual(val1, val2, strict, memos) { // All identical values are equivalent, as determined by ===. if (val1 === val2) { if (val1 !== 0) return true; return strict ? objectIs(val1, val2) : true; } // Check more closely if val1 and val2 are equal. if (strict) { if (typeof val1 !== 'object') { return typeof val1 === 'number' && numberIsNaN(val1) && numberIsNaN(val2); } if (typeof val2 !== 'object' || val1 === null || val2 === null) { return false; } if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) { return false; } } else { if (val1 === null || typeof val1 !== 'object') { if (val2 === null || typeof val2 !== 'object') { // eslint-disable-next-line eqeqeq return val1 == val2; } return false; } if (val2 === null || typeof val2 !== 'object') { return false; } } const val1Tag = objectToString(val1); const val2Tag = objectToString(val2); if (val1Tag !== val2Tag) { return false; } if (Array.isArray(val1)) { // Check for sparse arrays and general fast path if (val1.length !== val2.length) { return false; } const keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); const keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); if (keys1.length !== keys2.length) { return false; } return keyCheck(val1, val2, strict, memos, kIsArray, keys1); } // [browserify] This triggers on certain types in IE (Map/Set) so we don't // wan't to early return out of the rest of the checks. However we can check // if the second value is one of these values and the first isn't. if (val1Tag === '[object Object]') { // return keyCheck(val1, val2, strict, memos, kNoIterator); if ( (!isMap(val1) && isMap(val2)) || (!isSet(val1) && isSet(val2)) ) { return false; } } if (isDate(val1)) { if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) { return false; } } else if (isRegExp(val1)) { if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) { return false; } } else if (isNativeError(val1) || val1 instanceof Error) { // Do not compare the stack as it might differ even though the error itself // is otherwise identical. if (val1.message !== val2.message || val1.name !== val2.name) { return false; } } else if (isArrayBufferView(val1)) { if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) { if (!areSimilarFloatArrays(val1, val2)) { return false; } } else if (!areSimilarTypedArrays(val1, val2)) { return false; } // Buffer.compare returns true, so val1.length === val2.length. If they both // only contain numeric keys, we don't need to exam further than checking // the symbols. const keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); const keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); if (keys1.length !== keys2.length) { return false; } return keyCheck(val1, val2, strict, memos, kNoIterator, keys1); } else if (isSet(val1)) { if (!isSet(val2) || val1.size !== val2.size) { return false; } return keyCheck(val1, val2, strict, memos, kIsSet); } else if (isMap(val1)) { if (!isMap(val2) || val1.size !== val2.size) { return false; } return keyCheck(val1, val2, strict, memos, kIsMap); } else if (isAnyArrayBuffer(val1)) { if (!areEqualArrayBuffers(val1, val2)) { return false; } } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) { return false; } return keyCheck(val1, val2, strict, memos, kNoIterator); } function getEnumerables(val, keys) { return keys.filter((k) => propertyIsEnumerable(val, k)); } function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { // For all remaining Object pairs, including Array, objects and Maps, // equivalence is determined by having: // a) The same number of owned enumerable properties // b) The same set of keys/indexes (although not necessarily the same order) // c) Equivalent values for every corresponding key/index // d) For Sets and Maps, equal contents // Note: this accounts for both named and indexed properties on Arrays. if (arguments.length === 5) { aKeys = Object.keys(val1); const bKeys = Object.keys(val2); // The pair must have the same number of owned properties. if (aKeys.length !== bKeys.length) { return false; } } // Cheap key test let i = 0; for (; i < aKeys.length; i++) { if (!hasOwnProperty(val2, aKeys[i])) { return false; } } if (strict && arguments.length === 5) { const symbolKeysA = objectGetOwnPropertySymbols(val1); if (symbolKeysA.length !== 0) { let count = 0; for (i = 0; i < symbolKeysA.length; i++) { const key = symbolKeysA[i]; if (propertyIsEnumerable(val1, key)) { if (!propertyIsEnumerable(val2, key)) { return false; } aKeys.push(key); count++; } else if (propertyIsEnumerable(val2, key)) { return false; } } const symbolKeysB = objectGetOwnPropertySymbols(val2); if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) { return false; } } else { const symbolKeysB = objectGetOwnPropertySymbols(val2); if (symbolKeysB.length !== 0 && getEnumerables(val2, symbolKeysB).length !== 0) { return false; } } } if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) { return true; } // Use memos to handle cycles. if (memos === undefined) { memos = { val1: new Map(), val2: new Map(), position: 0 }; } else { // We prevent up to two map.has(x) calls by directly retrieving the value // and checking for undefined. The map can only contain numbers, so it is // safe to check for undefined only. const val2MemoA = memos.val1.get(val1); if (val2MemoA !== undefined) { const val2MemoB = memos.val2.get(val2); if (val2MemoB !== undefined) { return val2MemoA === val2MemoB; } } memos.position++; } memos.val1.set(val1, memos.position); memos.val2.set(val2, memos.position); const areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType); memos.val1.delete(val1); memos.val2.delete(val2); return areEq; } function setHasEqualElement(set, val1, strict, memo) { // Go looking. const setValues = arrayFromSet(set); for (let i = 0; i < setValues.length; i++) { const val2 = setValues[i]; if (innerDeepEqual(val1, val2, strict, memo)) { // Remove the matching element to make sure we do not check that again. set.delete(val2); return true; } } return false; } // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using // Sadly it is not possible to detect corresponding values properly in case the // type is a string, number, bigint or boolean. The reason is that those values // can match lots of different string values (e.g., 1n == '+00001'). function findLooseMatchingPrimitives(prim) { switch (typeof prim) { case 'undefined': return null; case 'object': // Only pass in null as object! return undefined; case 'symbol': return false; case 'string': prim = +prim; // Loose equal entries exist only if the string is possible to convert to // a regular number and not NaN. // Fall through case 'number': if (numberIsNaN(prim)) { return false; } } return true; } function setMightHaveLoosePrim(a, b, prim) { const altValue = findLooseMatchingPrimitives(prim); if (altValue != null) return altValue; return b.has(altValue) && !a.has(altValue); } function mapMightHaveLoosePrim(a, b, prim, item, memo) { const altValue = findLooseMatchingPrimitives(prim); if (altValue != null) { return altValue; } const curB = b.get(altValue); if (curB === undefined && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) { return false; } return !a.has(altValue) && innerDeepEqual(item, curB, false, memo); } function setEquiv(a, b, strict, memo) { // This is a lazily initiated Set of entries which have to be compared // pairwise. let set = null; const aValues = arrayFromSet(a); for (let i = 0; i < aValues.length; i++) { const val = aValues[i]; // Note: Checking for the objects first improves the performance for object // heavy sets but it is a minor slow down for primitives. As they are fast // to check this improves the worst case scenario instead. if (typeof val === 'object' && val !== null) { if (set === null) { set = new Set(); } // If the specified value doesn't exist in the second set its an not null // object (or non strict only: a not matching primitive) we'll need to go // hunting for something thats deep-(strict-)equal to it. To make this // O(n log n) complexity we have to copy these values in a new set first. set.add(val); } else if (!b.has(val)) { if (strict) return false; // Fast path to detect missing string, symbol, undefined and null values. if (!setMightHaveLoosePrim(a, b, val)) { return false; } if (set === null) { set = new Set(); } set.add(val); } } if (set !== null) { const bValues = arrayFromSet(b); for (let i = 0; i < bValues.length; i++) { const val = bValues[i]; // We have to check if a primitive value is already // matching and only if it's not, go hunting for it. if (typeof val === 'object' && val !== null) { if (!setHasEqualElement(set, val, strict, memo)) return false; } else if (!strict && !a.has(val) && !setHasEqualElement(set, val, strict, memo)) { return false; } } return set.size === 0; } return true; } function mapHasEqualEntry(set, map, key1, item1, strict, memo) { // To be able to handle cases like: // Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']]) // ... we need to consider *all* matching keys, not just the first we find. const setValues = arrayFromSet(set); for (let i = 0; i < setValues.length; i++) { const key2 = setValues[i]; if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map.get(key2), strict, memo)) { set.delete(key2); return true; } } return false; } function mapEquiv(a, b, strict, memo) { let set = null; const aEntries = arrayFromMap(a); for (let i = 0; i < aEntries.length; i++) { const [key, item1] = aEntries[i]; if (typeof key === 'object' && key !== null) { if (set === null) { set = new Set(); } set.add(key); } else { // By directly retrieving the value we prevent another b.has(key) check in // almost all possible cases. const item2 = b.get(key); if ((item2 === undefined && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo))) { if (strict) return false; // Fast path to detect missing string, symbol, undefined and null // keys. if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false; if (set === null) { set = new Set(); } set.add(key); } } } if (set !== null) { const bEntries = arrayFromMap(b); for (let i = 0; i < bEntries.length; i++) { const [key, item] = bEntries[i]; if (typeof key === 'object' && key !== null) { if (!mapHasEqualEntry(set, a, key, item, strict, memo)) return false; } else if (!strict && (!a.has(key) || !innerDeepEqual(a.get(key), item, false, memo)) && !mapHasEqualEntry(set, a, key, item, false, memo)) { return false; } } return set.size === 0; } return true; } function objEquiv(a, b, strict, keys, memos, iterationType) { // Sets and maps don't have their entries accessible via normal object // properties. let i = 0; if (iterationType === kIsSet) { if (!setEquiv(a, b, strict, memos)) { return false; } } else if (iterationType === kIsMap) { if (!mapEquiv(a, b, strict, memos)) { return false; } } else if (iterationType === kIsArray) { for (; i < a.length; i++) { if (hasOwnProperty(a, i)) { if (!hasOwnProperty(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) { return false; } } else if (hasOwnProperty(b, i)) { return false; } else { // Array is sparse. const keysA = Object.keys(a); for (; i < keysA.length; i++) { const key = keysA[i]; if (!hasOwnProperty(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) { return false; } } if (keysA.length !== Object.keys(b).length) { return false; } return true; } } } // The pair must have equivalent values for every corresponding key. // Possibly expensive deep test: for (i = 0; i < keys.length; i++) { const key = keys[i]; if (!innerDeepEqual(a[key], b[key], strict, memos)) { return false; } } return true; } function isDeepEqual(val1, val2) { return innerDeepEqual(val1, val2, kLoose); } function isDeepStrictEqual(val1, val2) { return innerDeepEqual(val1, val2, kStrict); } module.exports = { isDeepEqual, isDeepStrictEqual }; commonjs-assert-2.0.0/package.json000066400000000000000000000026151346577622100171440ustar00rootroot00000000000000{ "name": "assert", "version": "2.0.0", "description": "The assert module from Node.js, for the browser.", "main": "build/assert.js", "files": [ "build/assert.js", "build/internal" ], "license": "MIT", "homepage": "https://github.com/browserify/commonjs-assert", "repository": "browserify/commonjs-assert", "scripts": { "build": "babel assert.js test.js --out-dir build && babel internal --out-dir build/internal && babel test --out-dir build/test", "prepare": "npm run build", "dev": "babel assert.js test.js --watch --out-dir build & babel internal --watch --out-dir build/internal & babel test --watch --out-dir build/test", "test": "npm run build && npm run test:nobuild", "test:nobuild": "node build/test.js", "test:source": "node test.js", "test:browsers": "airtap build/test.js", "test:browsers:local": "npm run test:browsers -- --local" }, "keywords": [ "assert", "browser" ], "devDependencies": { "@babel/cli": "^7.4.4", "@babel/core": "^7.4.4", "@babel/preset-env": "^7.4.4", "airtap": "^2.0.2", "array-fill": "^1.2.0", "core-js": "^3.0.1", "cross-env": "^5.2.0", "object.entries": "^1.1.0", "object.getownpropertydescriptors": "^2.0.3", "tape": "^4.10.1" }, "dependencies": { "es6-object-assign": "^1.1.0", "is-nan": "^1.2.1", "object-is": "^1.0.1", "util": "^0.12.0" } } commonjs-assert-2.0.0/test.js000066400000000000000000000030511346577622100161660ustar00rootroot00000000000000const test = require('tape'); // Conditionally load polyfills required for testing if (typeof Promise === 'undefined') { console.log('Loading Promise polyfill'); require('core-js/features/promise'); } const testPaths = [ ['test-assert-async.js', () => require('./test/parallel/test-assert-async.js')], ['test-assert-checktag.js', () => require('./test/parallel/test-assert-checktag.js')], ['test-assert-deep.js', () => require('./test/parallel/test-assert-deep.js')], ['test-assert-fail-deprecation.js', () => require('./test/parallel/test-assert-fail-deprecation.js')], ['test-assert-fail.js', () => require('./test/parallel/test-assert-fail.js')], ['test-assert-if-error.js', () => require('./test/parallel/test-assert-if-error.js')], ['test-assert-typedarray-deepequal.js', () => require('./test/parallel/test-assert-typedarray-deepequal.js')], ['test-assert.js', () => require('./test/parallel/test-assert.js')], ['test-assert-colors.js', () => require('./test/pseudo-tty/test-assert-colors.js')], ['test-assert-no-color.js', () => require('./test/pseudo-tty/test-assert-no-color.js')], ['test-assert-position-indicator.js', () => require('./test/pseudo-tty/test-assert-position-indicator.js')] ]; testPaths.forEach(([testName, requireTest]) => { test(testName, t => { t.plan(2) let result; t.doesNotThrow(() => { result = requireTest(); }); Promise.resolve(result) .then(() => false) .catch(error => error) .then(resolved => t.error(resolved, 'should not resolve to rejected Promise')); }); }); commonjs-assert-2.0.0/test/000077500000000000000000000000001346577622100156315ustar00rootroot00000000000000commonjs-assert-2.0.0/test/common/000077500000000000000000000000001346577622100171215ustar00rootroot00000000000000commonjs-assert-2.0.0/test/common/index.js000066400000000000000000000177431346577622100206020ustar00rootroot00000000000000const assert = require('../../assert'); const getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ? Object.getOwnPropertyDescriptors : require('object.getownpropertydescriptors'); const objectEntries = Object.entries ? Object.entries : require('object.entries'); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat function repeat(str, count) { count = Math.floor(count); if (str.length == 0 || count == 0) return ''; var maxCount = str.length * count; count = Math.floor(Math.log(count) / Math.log(2)); while (count) { str += str; count--; } str += str.substring(0, maxCount - str.length); return str; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes function includes(str, search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } const isBrowser = typeof window !== 'undefined'; const bigIntSupported = typeof BigInt !== 'undefined'; const symbolSupported = typeof Symbol !== 'undefined'; const symbolToStringTagSupported = symbolSupported && typeof Symbol.toStringTag !== 'undefined'; const noop = () => {}; const mustCallChecks = []; function runCallChecks(exitCode) { if (exitCode !== 0) return; const failed = mustCallChecks.filter(function(context) { if ('minimum' in context) { context.messageSegment = `at least ${context.minimum}`; return context.actual < context.minimum; } else { context.messageSegment = `exactly ${context.exact}`; return context.actual !== context.exact; } }); failed.forEach(function(context) { console.log('Mismatched %s function calls. Expected %s, actual %d.', context.name, context.messageSegment, context.actual); console.log(context.stack.split('\n').slice(2).join('\n')); }); if (failed.length) process.exit(1); } function mustCall(fn, exact) { return _mustCallInner(fn, exact, 'exact'); } function mustCallAtLeast(fn, minimum) { return _mustCallInner(fn, minimum, 'minimum'); } function _mustCallInner(fn, criteria = 1, field) { if (process._exiting) throw new Error('Cannot use common.mustCall*() in process exit handler'); if (typeof fn === 'number') { criteria = fn; fn = noop; } else if (fn === undefined) { fn = noop; } if (typeof criteria !== 'number') throw new TypeError(`Invalid ${field} value: ${criteria}`); const context = { [field]: criteria, actual: 0, stack: (new Error()).stack, name: fn.name || '' }; // Add the exit listener only once to avoid listener leak warnings if (mustCallChecks.length === 0) process.on('exit', runCallChecks); mustCallChecks.push(context); return function() { context.actual++; return fn.apply(this, arguments); }; } function mustNotCall(msg) { return function mustNotCall() { assert.fail( `${msg || 'function should not have been called'}`); }; } function _expectWarning(name, expected, code) { if (typeof expected === 'string') { expected = [[expected, code]]; } else if (!Array.isArray(expected)) { expected = objectEntries(expected).map(([a, b]) => [b, a]); } else if (!(Array.isArray(expected[0]))) { expected = [[expected[0], expected[1]]]; } // Deprecation codes are mandatory, everything else is not. if (name === 'DeprecationWarning') { expected.forEach(([_, code]) => assert(code, expected)); } return mustCall((warning) => { const [ message, code ] = expected.shift(); assert.strictEqual(warning.name, name); if (typeof message === 'string') { assert.strictEqual(warning.message, message); } else { assert(message.test(warning.message)); } assert.strictEqual(warning.code, code); }, expected.length); } let catchWarning; // Accepts a warning name and description or array of descriptions or a map of // warning names to description(s) ensures a warning is generated for each // name/description pair. // The expected messages have to be unique per `expectWarning()` call. function expectWarning(nameOrMap, expected, code) { if (catchWarning === undefined) { catchWarning = {}; // [browserify] Don't bother actually catching warnings for now as it breaks // the tests when catchWarning[warning.name] is undefined for // ExperimentalWarning: queueMicrotask() is experimental. // process.on('warning', (warning) => catchWarning[warning.name](warning)); } if (typeof nameOrMap === 'string') { catchWarning[nameOrMap] = _expectWarning(nameOrMap, expected, code); } else { Object.keys(nameOrMap).forEach((name) => { catchWarning[name] = _expectWarning(name, nameOrMap[name]); }); } } class Comparison { constructor(obj, keys) { keys.forEach(key => { 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) { // Do not use `assert.strictEqual()` to prevent `util.inspect` from // always being called. assert.fail(`Expected one argument, got ${util.inspect(arguments)}`); } 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, getOwnPropertyDescriptors(settings)); // Visualize the message as identical in case of other errors. innerSettings.message = error.message; } const isDeepStrictEqual = (actual, expected) => { const assert = require('../../assert'); try { assert.deepStrictEqual(actual, expected); return true; } catch(e) { return false; } }; // Check all error properties. const keys = Object.keys(settings); keys.forEach(key => { if (!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 }); } }); return true; } if (fn) { assert.throws(fn, innerFn); return; } return mustCall(innerFn, exact); } const crashOnUnhandledRejection = (err) => { throw err; }; process.on('unhandledRejection', crashOnUnhandledRejection); module.exports = { getOwnPropertyDescriptors, repeat, includes, isBrowser, bigIntSupported, symbolToStringTagSupported, mustNotCall, mustCall, expectWarning, expectsError }; commonjs-assert-2.0.0/test/parallel/000077500000000000000000000000001346577622100174255ustar00rootroot00000000000000commonjs-assert-2.0.0/test/parallel/test-assert-async.js000066400000000000000000000160211346577622100233540ustar00rootroot00000000000000// Currently in sync with Node.js test/parallel/test-assert-async.js // https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b // [browserify] // Most `err.message` and `err.stack` tests are commented out because they are // inconsistent between browsers. // // `err.operator` tests are commented out because its always `undefined` in IE. // If we drop IE support we can uncomment these tests. 'use strict'; const common = require('../common'); const assert = require('../../assert'); // Run all tests in parallel and check their outcome at the end. const promises = []; // Thenable object without `catch` method, // shouldn't be considered as a valid Thenable const invalidThenable = { then: (fulfill, reject) => { fulfill(); }, }; // Function that returns a Thenable function, // a function with `catch` and `then` methods attached, // shouldn't be considered as a valid Thenable. const invalidThenableFunc = () => { function f() {} f.then = (fulfill, reject) => { fulfill(); }; f.catch = () => {}; return f; }; // Test assert.rejects() and assert.doesNotReject() by checking their // expected output and by verifying that they do not work sync // Check `assert.rejects`. { const rejectingFn = () => Promise.resolve().then(() => assert.fail()); const errObj = { code: 'ERR_ASSERTION', name: 'AssertionError', message: 'Failed' }; // `assert.rejects` accepts a function or a promise // or a thenable as first argument. promises.push(assert.rejects(rejectingFn, errObj)); promises.push(assert.rejects(rejectingFn(), errObj)); const validRejectingThenable = { then: (fulfill, reject) => { reject({ code: 'FAIL' }); }, catch: () => {} }; promises.push(assert.rejects(validRejectingThenable, { code: 'FAIL' })); // `assert.rejects` should not accept thenables that // use a function as `obj` and that have no `catch` handler. promises.push(assert.rejects( assert.rejects(invalidThenable, {}), { code: 'ERR_INVALID_ARG_TYPE' }) ); promises.push(assert.rejects( assert.rejects(invalidThenableFunc, {}), { code: 'ERR_INVALID_RETURN_VALUE' }) ); } { const handler = (err) => { assert(err instanceof assert.AssertionError, `${err.name} is not instance of AssertionError`); assert.strictEqual(err.code, 'ERR_ASSERTION'); // assert.strictEqual(err.message, // 'Missing expected rejection (mustNotCall).'); // assert.strictEqual(err.operator, 'rejects'); assert.ok(!common.includes(err.stack, 'at Function.rejects')); return true; }; let promise = assert.rejects(() => Promise.resolve({}), common.mustNotCall()); promises.push(assert.rejects(promise, common.mustCall(handler))); promise = assert.rejects(() => {}, common.mustNotCall()); promises.push(assert.rejects(promise, { name: 'TypeError', code: 'ERR_INVALID_RETURN_VALUE', message: 'Expected instance of Promise to be returned ' + 'from the "promiseFn" function but got type undefined.' })); promise = assert.rejects(Promise.resolve(), common.mustNotCall()); promises.push(assert.rejects(promise, common.mustCall(handler))); } { const THROWN_ERROR = new Error(); promises.push(assert.rejects(() => { throw THROWN_ERROR; }, {}).catch(common.mustCall((err) => { assert.strictEqual(err, THROWN_ERROR); }))); } promises.push(assert.rejects( assert.rejects('fail', {}), { code: 'ERR_INVALID_ARG_TYPE', message: 'The "promiseFn" argument must be one of type ' + 'Function or Promise. Received type string' } )); // Check `assert.doesNotReject`. { // `assert.doesNotReject` accepts a function or a promise // or a thenable as first argument. const promise = assert.doesNotReject(() => new Map(), common.mustNotCall()); promises.push(assert.rejects(promise, { // message: 'Expected instance of Promise to be returned ' + // 'from the "promiseFn" function but got instance of Map.', code: 'ERR_INVALID_RETURN_VALUE', name: 'TypeError' })); promises.push(assert.doesNotReject(() => Promise.resolve({}))); promises.push(assert.doesNotReject(Promise.resolve())); // `assert.doesNotReject` should not accept thenables that // use a function as `obj` and that have no `catch` handler. const validFulfillingThenable = { then: (fulfill, reject) => { fulfill(); }, catch: () => {} }; promises.push(assert.doesNotReject(validFulfillingThenable)); promises.push(assert.rejects( assert.doesNotReject(invalidThenable), { code: 'ERR_INVALID_ARG_TYPE' }) ); promises.push(assert.rejects( assert.doesNotReject(invalidThenableFunc), { code: 'ERR_INVALID_RETURN_VALUE' }) ); } { const handler1 = (err) => { assert(err instanceof assert.AssertionError, `${err.name} is not instance of AssertionError`); assert.strictEqual(err.code, 'ERR_ASSERTION'); assert.strictEqual(err.message, 'Failed'); return true; }; const handler2 = (err) => { assert(err instanceof assert.AssertionError, `${err.name} is not instance of AssertionError`); assert.strictEqual(err.code, 'ERR_ASSERTION'); // assert.strictEqual(err.message, // 'Got unwanted rejection.\nActual message: "Failed"'); // assert.strictEqual(err.operator, 'doesNotReject'); assert.ok(err.stack); assert.ok(!common.includes(err.stack, 'at Function.doesNotReject')); return true; }; const rejectingFn = () => Promise.resolve().then(() => assert.fail()); let promise = assert.doesNotReject(rejectingFn, common.mustCall(handler1)); promises.push(assert.rejects(promise, common.mustCall(handler2))); promise = assert.doesNotReject(rejectingFn(), common.mustCall(handler1)); promises.push(assert.rejects(promise, common.mustCall(handler2))); promise = assert.doesNotReject(() => assert.fail(), common.mustNotCall()); promises.push(assert.rejects(promise, common.mustCall(handler1))); } promises.push(assert.rejects( assert.doesNotReject(123), { code: 'ERR_INVALID_ARG_TYPE', message: 'The "promiseFn" argument must be one of type ' + 'Function or Promise. Received type number' } )); { const handler = (generated, actual, err) => { assert.strictEqual(err.generatedMessage, generated); assert.strictEqual(err.code, 'ERR_ASSERTION'); assert.strictEqual(err.actual, actual); // assert.strictEqual(err.operator, 'rejects'); // assert(/rejects/.test(err.stack)); return true; }; const err = new Error(); promises.push(assert.rejects( assert.rejects(Promise.reject(null), { code: 'FOO' }), handler.bind(null, true, null) )); promises.push(assert.rejects( assert.rejects(Promise.reject(5), { code: 'FOO' }, 'AAAAA'), handler.bind(null, false, 5) )); promises.push(assert.rejects( assert.rejects(Promise.reject(err), { code: 'FOO' }, 'AAAAA'), handler.bind(null, false, err) )); } // Make sure all async code gets properly executed. module.exports = Promise.all(promises).then(common.mustCall()); commonjs-assert-2.0.0/test/parallel/test-assert-checktag.js000066400000000000000000000046521346577622100240170ustar00rootroot00000000000000// Currently in sync with Node.js test/parallel/test-assert-checktag.js // https://github.com/nodejs/node/commit/7493db21b667ed746d39c9b54357eac4287232e3 // [browserify] // Most `err.message` tests are commented out because they are // inconsistent between browsers. 'use strict'; const {isBrowser} = require('../common'); const assert = require('../../assert'); // Disable colored output to prevent color codes from breaking assertion // message comparisons. This should only be an issue when process.stdout // is a TTY. if (process.stdout && process.stdout.isTTY) process.env.NODE_DISABLE_COLORS = '1'; // Turn off no-restricted-properties because we are testing deepEqual! /* eslint-disable no-restricted-properties */ // See https://github.com/nodejs/node/issues/10258 { const date = new Date('2016'); function FakeDate() {} FakeDate.prototype = Date.prototype; const fake = new FakeDate(); assert.notDeepEqual(date, fake); assert.notDeepEqual(fake, date); // For deepStrictEqual we check the runtime type, // then reveal the fakeness of the fake date assert.throws( () => assert.deepStrictEqual(date, fake), // { // message: 'Expected values to be strictly deep-equal:\n' + // '+ actual - expected\n\n+ 2016-01-01T00:00:00.000Z\n- Date {}' // } ); assert.throws( () => assert.deepStrictEqual(fake, date), // { // message: 'Expected values to be strictly deep-equal:\n' + // '+ actual - expected\n\n+ Date {}\n- 2016-01-01T00:00:00.000Z' // } ); } if (!isBrowser) { // At the moment global has its own type tag const fakeGlobal = {}; Object.setPrototypeOf(fakeGlobal, Object.getPrototypeOf(global)); Object.keys(global).forEach(prop => { fakeGlobal[prop] = global[prop]; }); assert.notDeepEqual(fakeGlobal, global); // Message will be truncated anyway, don't validate assert.throws(() => assert.deepStrictEqual(fakeGlobal, global), assert.AssertionError); } if (!isBrowser) { // At the moment process has its own type tag const fakeProcess = {}; Object.setPrototypeOf(fakeProcess, Object.getPrototypeOf(process)); Object.keys(process).forEach(prop => { fakeProcess[prop] = process[prop]; }); assert.notDeepEqual(fakeProcess, process); // Message will be truncated anyway, don't validate assert.throws(() => assert.deepStrictEqual(fakeProcess, process), assert.AssertionError); } /* eslint-enable */ commonjs-assert-2.0.0/test/parallel/test-assert-deep.js000066400000000000000000000710001346577622100231520ustar00rootroot00000000000000// Currently in sync with Node.js test/parallel/test-assert-deep.js // https://github.com/nodejs/node/commit/1ed3c54ecbd72a33693e5954f86bcc9fd9b1cc09 // [browserify] // Most `err.message` tests are commented out because they are // inconsistent between browsers. 'use strict'; const common = require('../common'); const assert = require('../../assert'); const util = require('util/'); const { AssertionError } = assert; const defaultMsgStart = 'Expected values to be strictly deep-equal:\n'; const defaultMsgStartFull = `${defaultMsgStart}+ actual - expected`; const objectEntries = require('object.entries'); const arrayFromSet = set => { const array = []; set.forEach(value => array.push(value)); return array; }; // Disable colored output to prevent color codes from breaking assertion // message comparisons. This should only be an issue when process.stdout // is a TTY. if (process.stdout && process.stdout.isTTY) process.env.NODE_DISABLE_COLORS = '1'; // Allows us to create Sets/Maps from arrays in IE const createSet = (values = []) => { const set = new Set(); values.forEach(value => set.add(value)); return set; }; const createMap = (values = []) => { const map = new Map(); values.forEach(([key, value]) => map.set(key, value)); return map; }; // Template tag function turning an error message into a RegExp // for assert.throws() function re(literals, ...values) { let result = 'Expected values to be loosely deep-equal:\n\n'; values.forEach((value, i) => { const str = util.inspect(value, { compact: false, depth: 1000, customInspect: false, maxArrayLength: Infinity, breakLength: Infinity, sorted: true, getters: true }); // Need to escape special characters. result += str; result += literals[i + 1]; }); return { code: 'ERR_ASSERTION', message: result }; } // The following deepEqual tests might seem very weird. // They just describe what it is now. // That is why we discourage using deepEqual in our own tests. // Turn off no-restricted-properties because we are testing deepEqual! /* eslint-disable no-restricted-properties */ const arr = new Uint8Array([120, 121, 122, 10]); const buf = Buffer.from(arr); // They have different [[Prototype]] assert.throws( () => assert.deepStrictEqual(arr, buf), // { // code: 'ERR_ASSERTION', // message: `${defaultMsgStartFull} ... Lines skipped\n\n` + // '+ Uint8Array [\n' + // '- Buffer [Uint8Array] [\n 120,\n...\n 10\n ]' // } ); assert.deepEqual(arr, buf); { const buf2 = Buffer.from(arr); buf2.prop = 1; assert.throws( () => assert.deepStrictEqual(buf2, buf), { code: 'ERR_ASSERTION', // message: `${defaultMsgStartFull} ... Lines skipped\n\n` + // ' Buffer [Uint8Array] [\n' + // ' 120,\n' + // '...\n' + // ' 10,\n' + // '+ prop: 1\n' + // ' ]' } ); assert.notDeepEqual(buf2, buf); } { const arr2 = new Uint8Array([120, 121, 122, 10]); arr2.prop = 5; assert.throws( () => assert.deepStrictEqual(arr, arr2), { code: 'ERR_ASSERTION', // message: `${defaultMsgStartFull} ... Lines skipped\n\n` + // ' Uint8Array [\n' + // ' 120,\n' + // '...\n' + // ' 10,\n' + // '- prop: 5\n' + // ' ]' } ); assert.notDeepEqual(arr, arr2); } const date = new Date('2016'); class MyDate extends Date { constructor(...args) { super(...args); this[0] = '1'; } } const date2 = new MyDate('2016'); // deepEqual returns true as long as the time are the same, // but deepStrictEqual checks own properties assert.notDeepEqual(date, date2); assert.notDeepEqual(date2, date); assert.throws( () => assert.deepStrictEqual(date, date2), { code: 'ERR_ASSERTION', // message: `${defaultMsgStartFull}\n\n` + // '+ 2016-01-01T00:00:00.000Z\n- MyDate 2016-01-01T00:00:00.000Z' + // " {\n- '0': '1'\n- }" } ); assert.throws( () => assert.deepStrictEqual(date2, date), { code: 'ERR_ASSERTION', // message: `${defaultMsgStartFull}\n\n` + // '+ MyDate 2016-01-01T00:00:00.000Z {\n' + // "+ '0': '1'\n+ }\n- 2016-01-01T00:00:00.000Z" } ); class MyRegExp extends RegExp { constructor(...args) { super(...args); this[0] = '1'; } } const re1 = new RegExp('test'); const re2 = new MyRegExp('test'); // deepEqual returns true as long as the regexp-specific properties // are the same, but deepStrictEqual checks all properties assert.notDeepEqual(re1, re2); assert.throws( () => assert.deepStrictEqual(re1, re2), { code: 'ERR_ASSERTION', // message: `${defaultMsgStartFull}\n\n` + // "+ /test/\n- MyRegExp /test/ {\n- '0': '1'\n- }" } ); // For these weird cases, deepEqual should pass (at least for now), // but deepStrictEqual should throw. { const similar = createSet([ { 0: 1 }, // Object new String('1'), // Object [1], // Array date2, // Date with this[0] = '1' re2, // RegExp with this[0] = '1' new Int8Array([1]), // Int8Array new Int16Array([1]), // Int16Array new Uint16Array([1]), // Uint16Array new Int32Array([1]), // Int32Array new Uint32Array([1]), // Uint32Array Buffer.from([1]), // Uint8Array (function() { return arguments; })(1) ]); arrayFromSet(similar).forEach(a => { arrayFromSet(similar).forEach(b => { if (a !== b) { assert.notDeepEqual(a, b); assert.throws( () => assert.deepStrictEqual(a, b), { code: 'ERR_ASSERTION' } ); } }); }); } function assertDeepAndStrictEqual(a, b) { assert.deepEqual(a, b); assert.deepStrictEqual(a, b); assert.deepEqual(b, a); assert.deepStrictEqual(b, a); } function assertNotDeepOrStrict(a, b, err) { assert.throws( () => assert.deepEqual(a, b), err || re`${a}\n\nshould equal\n\n${b}` ); assert.throws( () => assert.deepStrictEqual(a, b), err || { code: 'ERR_ASSERTION' } ); assert.throws( () => assert.deepEqual(b, a), err || re`${b}\n\nshould equal\n\n${a}` ); assert.throws( () => assert.deepStrictEqual(b, a), err || { code: 'ERR_ASSERTION' } ); } function assertOnlyDeepEqual(a, b, err) { assert.deepEqual(a, b); assert.throws( () => assert.deepStrictEqual(a, b), err || { code: 'ERR_ASSERTION' } ); assert.deepEqual(b, a); assert.throws( () => assert.deepStrictEqual(b, a), err || { code: 'ERR_ASSERTION' } ); } // es6 Maps and Sets assertDeepAndStrictEqual(createSet(), createSet()); assertDeepAndStrictEqual(createMap(), createMap()); assertDeepAndStrictEqual(createSet([1, 2, 3]), createSet([1, 2, 3])); assertNotDeepOrStrict(createSet([1, 2, 3]), createSet([1, 2, 3, 4])); assertNotDeepOrStrict(createSet([1, 2, 3, 4]), createSet([1, 2, 3])); assertDeepAndStrictEqual(createSet(['1', '2', '3']), createSet(['1', '2', '3'])); assertDeepAndStrictEqual(createSet([[1, 2], [3, 4]]), createSet([[3, 4], [1, 2]])); assertNotDeepOrStrict(createSet([{ a: 0 }]), createSet([{ a: 1 }])); if (common.symbolSupported) { assertNotDeepOrStrict(createSet([Symbol()]), createSet([Symbol()])); } { const a = [ 1, 2 ]; const b = [ 3, 4 ]; const c = [ 1, 2 ]; const d = [ 3, 4 ]; assertDeepAndStrictEqual( { a: a, b: b, s: createSet([a, b]) }, { a: c, b: d, s: createSet([d, c]) } ); } assertDeepAndStrictEqual(createMap([[1, 1], [2, 2]]), createMap([[1, 1], [2, 2]])); assertDeepAndStrictEqual(createMap([[1, 1], [2, 2]]), createMap([[2, 2], [1, 1]])); assertNotDeepOrStrict(createMap([[1, 1], [2, 2]]), createMap([[1, 2], [2, 1]])); assertNotDeepOrStrict( createMap([[[1], 1], [{}, 2]]), createMap([[[1], 2], [{}, 1]]) ); assertNotDeepOrStrict(createSet([1]), [1]); assertNotDeepOrStrict(createSet(), []); assertNotDeepOrStrict(createSet(), {}); assertNotDeepOrStrict(createMap([['a', 1]]), { a: 1 }); assertNotDeepOrStrict(createMap(), []); assertNotDeepOrStrict(createMap(), {}); assertOnlyDeepEqual(createSet(['1']), createSet([1])); assertOnlyDeepEqual(createMap([['1', 'a']]), createMap([[1, 'a']])); assertOnlyDeepEqual(createMap([['a', '1']]), createMap([['a', 1]])); assertNotDeepOrStrict(createMap([['a', '1']]), createMap([['a', 2]])); assertDeepAndStrictEqual(createSet([{}]), createSet([{}])); // Ref: https://github.com/nodejs/node/issues/13347 assertNotDeepOrStrict( createSet([{ a: 1 }, { a: 1 }]), createSet([{ a: 1 }, { a: 2 }]) ); assertNotDeepOrStrict( createSet([{ a: 1 }, { a: 1 }, { a: 2 }]), createSet([{ a: 1 }, { a: 2 }, { a: 2 }]) ); assertNotDeepOrStrict( createMap([[{ x: 1 }, 5], [{ x: 1 }, 5]]), createMap([[{ x: 1 }, 5], [{ x: 2 }, 5]]) ); assertNotDeepOrStrict(createSet([3, '3']), createSet([3, 4])); assertNotDeepOrStrict(createMap([[3, 0], ['3', 0]]), createMap([[3, 0], [4, 0]])); assertNotDeepOrStrict( createSet([{ a: 1 }, { a: 1 }, { a: 2 }]), createSet([{ a: 1 }, { a: 2 }, { a: 2 }]) ); // Mixed primitive and object keys assertDeepAndStrictEqual( createMap([[1, 'a'], [{}, 'a']]), createMap([[1, 'a'], [{}, 'a']]) ); assertDeepAndStrictEqual( createSet([1, 'a', [{}, 'a']]), createSet([1, 'a', [{}, 'a']]) ); // This is an awful case, where a map contains multiple equivalent keys: assertOnlyDeepEqual( createMap([[1, 'a'], ['1', 'b']]), createMap([['1', 'a'], [true, 'b']]) ); assertNotDeepOrStrict( createSet(['a']), createSet(['b']) ); assertDeepAndStrictEqual( createMap([[{}, 'a'], [{}, 'b']]), createMap([[{}, 'b'], [{}, 'a']]) ); assertOnlyDeepEqual( createMap([[true, 'a'], ['1', 'b'], [1, 'a']]), createMap([['1', 'a'], [1, 'b'], [true, 'a']]) ); assertNotDeepOrStrict( createMap([[true, 'a'], ['1', 'b'], [1, 'c']]), createMap([['1', 'a'], [1, 'b'], [true, 'a']]) ); // Similar object keys assertNotDeepOrStrict( createSet([{}, {}]), createSet([{}, 1]) ); assertNotDeepOrStrict( createSet([[{}, 1], [{}, 1]]), createSet([[{}, 1], [1, 1]]) ); assertNotDeepOrStrict( createMap([[{}, 1], [{}, 1]]), createMap([[{}, 1], [1, 1]]) ); assertOnlyDeepEqual( createMap([[{}, 1], [true, 1]]), createMap([[{}, 1], [1, 1]]) ); // Similar primitive key / values assertNotDeepOrStrict( createSet([1, true, false]), createSet(['1', 0, '0']) ); assertNotDeepOrStrict( createMap([[1, 5], [true, 5], [false, 5]]), createMap([['1', 5], [0, 5], ['0', 5]]) ); // Undefined value in Map assertDeepAndStrictEqual( createMap([[1, undefined]]), createMap([[1, undefined]]) ); assertOnlyDeepEqual( createMap([[1, null], ['', '0']]), createMap([['1', undefined], [false, 0]]) ); assertNotDeepOrStrict( createMap([[1, undefined]]), createMap([[2, undefined]]) ); // null as key assertDeepAndStrictEqual( createMap([[null, 3]]), createMap([[null, 3]]) ); if (common.bigIntSupported) { assertOnlyDeepEqual( createMap([[undefined, null], eval("['+000', 2n]")]), createMap([[null, undefined], [false, '2']]), ); assertOnlyDeepEqual( createSet(eval("[null, '', 1n, 5, 2n, false]")), createSet(eval("[undefined, 0, 5n, true, '2', '-000']")) ); } assertNotDeepOrStrict( createSet(['']), createSet(['0']) ); assertOnlyDeepEqual( createMap([[1, {}]]), createMap([[true, {}]]) ); assertOnlyDeepEqual( createMap([[undefined, true]]), createMap([[null, true]]) ); assertNotDeepOrStrict( createMap([[undefined, true]]), createMap([[true, true]]) ); // GH-6416. Make sure circular refs don't throw. { const b = {}; b.b = b; const c = {}; c.b = c; assertDeepAndStrictEqual(b, c); const d = {}; d.a = 1; d.b = d; const e = {}; e.a = 1; e.b = {}; assertNotDeepOrStrict(d, e); } // GH-14441. Circular structures should be consistent { const a = {}; const b = {}; a.a = a; b.a = {}; b.a.a = a; assertDeepAndStrictEqual(a, b); } { const a = createSet(); const b = createSet(); const c = createSet(); a.add(a); b.add(b); c.add(a); assertDeepAndStrictEqual(b, c); } // https://github.com/nodejs/node-v0.x-archive/pull/7178 // Ensure reflexivity of deepEqual with `arguments` objects. { const args = (function() { return arguments; })(); assertNotDeepOrStrict([], args); } // More checking that arguments objects are handled correctly { // eslint-disable-next-line func-style const returnArguments = function() { return arguments; }; const someArgs = returnArguments('a'); const sameArgs = returnArguments('a'); const diffArgs = returnArguments('b'); assertNotDeepOrStrict(someArgs, ['a']); assertNotDeepOrStrict(someArgs, { '0': 'a' }); assertNotDeepOrStrict(someArgs, diffArgs); assertDeepAndStrictEqual(someArgs, sameArgs); } { const values = [ 123, Infinity, 0, null, undefined, false, true, {}, [], () => {}, ]; assertDeepAndStrictEqual(createSet(values), createSet(values)); assertDeepAndStrictEqual(createSet(values), createSet(values.reverse())); const mapValues = values.map((v) => [v, { a: 5 }]); assertDeepAndStrictEqual(createMap(mapValues), createMap(mapValues)); assertDeepAndStrictEqual(createMap(mapValues), createMap(mapValues.reverse())); } { const s1 = createSet(); const s2 = createSet(); s1.add(1); s1.add(2); s2.add(2); s2.add(1); assertDeepAndStrictEqual(s1, s2); } { const m1 = createMap(); const m2 = createMap(); const obj = { a: 5, b: 6 }; m1.set(1, obj); m1.set(2, 'hi'); m1.set(3, [1, 2, 3]); m2.set(2, 'hi'); // different order m2.set(1, obj); m2.set(3, [1, 2, 3]); // Deep equal, but not reference equal. assertDeepAndStrictEqual(m1, m2); } { const m1 = createMap(); const m2 = createMap(); // m1 contains itself. m1.set(1, m1); m2.set(1, createMap()); assertNotDeepOrStrict(m1, m2); } { const map1 = createMap([[1, 1]]); const map2 = createMap([[1, '1']]); assert.deepEqual(map1, map2); assert.throws( () => assert.deepStrictEqual(map1, map2), { code: 'ERR_ASSERTION', // message: `${defaultMsgStartFull}\n\n` + // " Map {\n+ 1 => 1\n- 1 => '1'\n }" } ); } { // Two equivalent sets / maps with different key/values applied shouldn't be // the same. This is a terrible idea to do in practice, but deepEqual should // still check for it. const s1 = createSet(); const s2 = createSet(); s1.x = 5; assertNotDeepOrStrict(s1, s2); const m1 = createMap(); const m2 = createMap(); m1.x = 5; assertNotDeepOrStrict(m1, m2); } { // Circular references. const s1 = createSet(); s1.add(s1); const s2 = createSet(); s2.add(s2); assertDeepAndStrictEqual(s1, s2); const m1 = createMap(); m1.set(2, m1); const m2 = createMap(); m2.set(2, m2); assertDeepAndStrictEqual(m1, m2); const m3 = createMap(); m3.set(m3, 2); const m4 = createMap(); m4.set(m4, 2); assertDeepAndStrictEqual(m3, m4); } // Handle sparse arrays. { assertDeepAndStrictEqual([1, , , 3], [1, , , 3]); assertNotDeepOrStrict([1, , , 3], [1, , , 3, , , ]); const a = new Array(3); const b = new Array(3); a[2] = true; b[1] = true; assertNotDeepOrStrict(a, b); b[2] = true; assertNotDeepOrStrict(a, b); a[0] = true; assertNotDeepOrStrict(a, b); } // Handle different error messages { const err1 = new Error('foo1'); assertNotDeepOrStrict(err1, new Error('foo2'), assert.AssertionError); assertNotDeepOrStrict(err1, new TypeError('foo1'), assert.AssertionError); // [browserify] Objects will not be strictly equal in some browsers due to // different `line`/`column` properties // assertDeepAndStrictEqual(err1, new Error('foo1')); assertNotDeepOrStrict(err1, {}, AssertionError); } // Handle NaN assert.notDeepEqual(NaN, NaN); assert.deepStrictEqual(NaN, NaN); assert.deepStrictEqual({ a: NaN }, { a: NaN }); assert.deepStrictEqual([ 1, 2, NaN, 4 ], [ 1, 2, NaN, 4 ]); // Handle boxed primitives if (common.symbolSupported) { const boxedString = new String('test'); const boxedSymbol = Object(Symbol()); assertNotDeepOrStrict(new Boolean(true), Object(false)); assertNotDeepOrStrict(Object(true), new Number(1)); assertNotDeepOrStrict(new Number(2), new Number(1)); assertNotDeepOrStrict(boxedSymbol, Object(Symbol())); assertNotDeepOrStrict(boxedSymbol, {}); assertDeepAndStrictEqual(boxedSymbol, boxedSymbol); assertDeepAndStrictEqual(Object(true), Object(true)); assertDeepAndStrictEqual(Object(2), Object(2)); assertDeepAndStrictEqual(boxedString, Object('test')); boxedString.slow = true; assertNotDeepOrStrict(boxedString, Object('test')); boxedSymbol.slow = true; assertNotDeepOrStrict(boxedSymbol, {}); } // Minus zero assertOnlyDeepEqual(0, -0); assertDeepAndStrictEqual(-0, -0); // Handle symbols (enumerable only) if (common.symbolSupported) { const symbol1 = Symbol(); const obj1 = { [symbol1]: 1 }; const obj2 = { [symbol1]: 1 }; const obj3 = { [Symbol()]: 1 }; // Add a non enumerable symbol as well. It is going to be ignored! Object.defineProperty(obj2, Symbol(), { value: 1 }); assertOnlyDeepEqual(obj1, obj3); assertDeepAndStrictEqual(obj1, obj2); obj2[Symbol()] = true; assertOnlyDeepEqual(obj1, obj2); // TypedArrays have a fast path. Test for this as well. const a = new Uint8Array(4); const b = new Uint8Array(4); a[symbol1] = true; b[symbol1] = false; assertNotDeepOrStrict(a, b); b[symbol1] = true; assertDeepAndStrictEqual(a, b); // The same as TypedArrays is valid for boxed primitives const boxedStringA = new String('test'); const boxedStringB = new String('test'); boxedStringA[symbol1] = true; assertOnlyDeepEqual(boxedStringA, boxedStringB); boxedStringA[symbol1] = true; assertDeepAndStrictEqual(a, b); } assert.deepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)); assert.throws(() => { assert.deepEqual(new Date(), new Date(2000, 3, 14)); }, AssertionError, 'deepEqual(new Date(), new Date(2000, 3, 14))'); assert.throws( () => { assert.notDeepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)); }, AssertionError, 'notDeepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))' ); assert.throws( () => { assert.notDeepEqual(common.repeat('a', 1024), common.repeat('a', 1024)); }, AssertionError, 'notDeepEqual("a".repeat(1024), "a".repeat(1024))' ); assert.notDeepEqual(new Date(), new Date(2000, 3, 14)); assertDeepAndStrictEqual(/a/, /a/); assertDeepAndStrictEqual(/a/g, /a/g); assertDeepAndStrictEqual(/a/i, /a/i); assertDeepAndStrictEqual(/a/m, /a/m); assertDeepAndStrictEqual(/a/igm, /a/igm); assertNotDeepOrStrict(/ab/, /a/); assertNotDeepOrStrict(/a/g, /a/); assertNotDeepOrStrict(/a/i, /a/); assertNotDeepOrStrict(/a/m, /a/); assertNotDeepOrStrict(/a/igm, /a/im); { const re1 = /a/g; re1.lastIndex = 3; assert.deepEqual(re1, /a/g); } assert.deepEqual(4, '4'); assert.deepEqual(true, 1); assert.throws(() => assert.deepEqual(4, '5'), AssertionError, 'deepEqual( 4, \'5\')'); // Having the same number of owned properties && the same set of keys. assert.deepEqual({ a: 4 }, { a: 4 }); assert.deepEqual({ a: 4, b: '2' }, { a: 4, b: '2' }); assert.deepEqual([4], ['4']); assert.throws( () => assert.deepEqual({ a: 4 }, { a: 4, b: true }), AssertionError); assert.notDeepEqual(['a'], { 0: 'a' }); assert.deepEqual({ a: 4, b: '1' }, { b: '1', a: 4 }); const a1 = [1, 2, 3]; const a2 = [1, 2, 3]; a1.a = 'test'; a1.b = true; a2.b = true; a2.a = 'test'; assert.throws(() => assert.deepEqual(Object.keys(a1), Object.keys(a2)), AssertionError); assert.deepEqual(a1, a2); // Having an identical prototype property. const nbRoot = { toString() { return `${this.first} ${this.last}`; } }; function nameBuilder(first, last) { this.first = first; this.last = last; return this; } nameBuilder.prototype = nbRoot; function nameBuilder2(first, last) { this.first = first; this.last = last; return this; } nameBuilder2.prototype = nbRoot; const nb1 = new nameBuilder('Ryan', 'Dahl'); let nb2 = new nameBuilder2('Ryan', 'Dahl'); assert.deepEqual(nb1, nb2); nameBuilder2.prototype = Object; nb2 = new nameBuilder2('Ryan', 'Dahl'); assert.deepEqual(nb1, nb2); // Primitives assertNotDeepOrStrict(null, {}); assertNotDeepOrStrict(undefined, {}); assertNotDeepOrStrict('a', ['a']); assertNotDeepOrStrict('a', { 0: 'a' }); assertNotDeepOrStrict(1, {}); assertNotDeepOrStrict(true, {}); if (common.symbolSupported) { assertNotDeepOrStrict(Symbol(), {}); assertNotDeepOrStrict(Symbol(), Symbol()); } assertOnlyDeepEqual(4, '4'); assertOnlyDeepEqual(true, 1); if (common.symbolSupported) { const s = Symbol(); assertDeepAndStrictEqual(s, s); } // Primitive wrappers and object. assertNotDeepOrStrict(new String('a'), ['a']); assertNotDeepOrStrict(new String('a'), { 0: 'a' }); assertNotDeepOrStrict(new Number(1), {}); assertNotDeepOrStrict(new Boolean(true), {}); // Same number of keys but different key names. assertNotDeepOrStrict({ a: 1 }, { b: 1 }); assert.deepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)); assert.throws( () => assert.deepStrictEqual(new Date(), new Date(2000, 3, 14)), AssertionError, 'deepStrictEqual(new Date(), new Date(2000, 3, 14))' ); assert.throws( () => assert.notDeepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)), { name: 'AssertionError', // message: 'Expected "actual" not to be strictly deep-equal to: ' + // util.inspect(new Date(2000, 3, 14)) } ); assert.notDeepStrictEqual(new Date(), new Date(2000, 3, 14)); assert.throws( () => assert.deepStrictEqual(/ab/, /a/), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: `${defaultMsgStartFull}\n\n+ /ab/\n- /a/` }); assert.throws( () => assert.deepStrictEqual(/a/g, /a/), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: `${defaultMsgStartFull}\n\n+ /a/g\n- /a/` }); assert.throws( () => assert.deepStrictEqual(/a/i, /a/), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: `${defaultMsgStartFull}\n\n+ /a/i\n- /a/` }); assert.throws( () => assert.deepStrictEqual(/a/m, /a/), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: `${defaultMsgStartFull}\n\n+ /a/m\n- /a/` }); assert.throws( () => assert.deepStrictEqual(/a/igm, /a/im), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: `${defaultMsgStartFull}\n\n+ /a/gim\n- /a/im\n ^` }); { const re1 = /a/; re1.lastIndex = 3; assert.deepStrictEqual(re1, /a/); } assert.throws( () => assert.deepStrictEqual(4, '4'), // { message: `${defaultMsgStart}\n4 !== '4'\n` } ); assert.throws( () => assert.deepStrictEqual(true, 1), // { message: `${defaultMsgStart}\ntrue !== 1\n` } ); // Having the same number of owned properties && the same set of keys. assert.deepStrictEqual({ a: 4 }, { a: 4 }); assert.deepStrictEqual({ a: 4, b: '2' }, { a: 4, b: '2' }); assert.throws(() => assert.deepStrictEqual([4], ['4']), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: `${defaultMsgStartFull}\n\n [\n+ 4\n- '4'\n ]` }); assert.throws( () => assert.deepStrictEqual({ a: 4 }, { a: 4, b: true }), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: `${defaultMsgStartFull}\n\n ` + // '{\n a: 4,\n- b: true\n }' }); assert.throws( () => assert.deepStrictEqual(['a'], { 0: 'a' }), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: `${defaultMsgStartFull}\n\n` + // "+ [\n+ 'a'\n+ ]\n- {\n- '0': 'a'\n- }" }); /* eslint-enable */ assert.deepStrictEqual({ a: 4, b: '1' }, { b: '1', a: 4 }); assert.throws( () => assert.deepStrictEqual([0, 1, 2, 'a', 'b'], [0, 1, 2, 'b', 'a']), AssertionError); assert.deepStrictEqual(a1, a2); // Prototype check. function Constructor1(first, last) { this.first = first; this.last = last; } function Constructor2(first, last) { this.first = first; this.last = last; } const obj1 = new Constructor1('Ryan', 'Dahl'); let obj2 = new Constructor2('Ryan', 'Dahl'); assert.throws(() => assert.deepStrictEqual(obj1, obj2), AssertionError); Constructor2.prototype = Constructor1.prototype; obj2 = new Constructor2('Ryan', 'Dahl'); assert.deepStrictEqual(obj1, obj2); // Check extra properties on errors. { const a = new TypeError('foo'); const b = new TypeError('foo'); a.foo = 'bar'; b.foo = 'baz'; assert.throws( () => assert.deepStrictEqual(a, b), // { // message: `${defaultMsgStartFull}\n\n` + // ' [TypeError: foo] {\n+ foo: \'bar\'\n- foo: \'baz\'\n }' // } ); } // Check proxies. { // TODO(BridgeAR): Check if it would not be better to detect proxies instead // of just using the proxy value. if (typeof Proxy !== 'undefined') { const arrProxy = new Proxy([1, 2], {}); assert.deepStrictEqual(arrProxy, [1, 2]); const tmp = util.inspect.defaultOptions; util.inspect.defaultOptions = { showProxy: true }; assert.throws( () => assert.deepStrictEqual(arrProxy, [1, 2, 3]), // { message: `${defaultMsgStartFull}\n\n` + // ' [\n 1,\n 2,\n- 3\n ]' } ); util.inspect.defaultOptions = tmp; } // [browserify] Safari fails this test due to the proxy. Chrome and Firefox pass. // const invalidTrap = new Proxy([1, 2, 3], { // ownKeys() { return []; } // }); // assert.throws( // () => assert.deepStrictEqual(invalidTrap, [1, 2, 3]), // { // name: 'TypeError', // // message: "'ownKeys' on proxy: trap result did not include 'length'" // } // ); } // Strict equal with identical objects that are not identical // by reference and longer than 30 elements // E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() }) if (common.symbolSupported) { const a = {}; const b = {}; for (let i = 0; i < 35; i++) { a[`symbol${i}`] = Symbol(); b[`symbol${i}`] = Symbol(); } assert.throws( () => assert.deepStrictEqual(a, b), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: /\.\.\./g } ); } // Basic valueOf check. { const a = new String(1); a.valueOf = undefined; assertNotDeepOrStrict(a, new String(1)); } // Basic array out of bounds check. { const arr = [1, 2, 3]; arr[2 ** 32] = true; assertNotDeepOrStrict(arr, [1, 2, 3]); } assert.throws( () => assert.deepStrictEqual([1, 2, 3], [1, 2]), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: `${defaultMsgStartFull}\n\n` + // ' [\n' + // ' 1,\n' + // ' 2,\n' + // '+ 3\n' + // ' ]' } ); // Verify that manipulating the `getTime()` function has no impact on the time // verification. { const a = new Date('2000'); const b = new Date('2000'); Object.defineProperty(a, 'getTime', { value: () => 5 }); assert.deepStrictEqual(a, b); } // Verify that extra keys will be tested for when using fake arrays. if (common.symbolToStringTagSupported) { const a = { 0: 1, 1: 1, 2: 'broken' }; Object.setPrototypeOf(a, Object.getPrototypeOf([])); Object.defineProperty(a, Symbol.toStringTag, { value: 'Array', }); Object.defineProperty(a, 'length', { value: 2 }); assert.notDeepStrictEqual(a, [1, 1]); } // Verify that changed tags will still check for the error message. if (common.symbolToStringTagSupported) { const err = new Error('foo'); err[Symbol.toStringTag] = 'Foobar'; const err2 = new Error('bar'); err2[Symbol.toStringTag] = 'Foobar'; assertNotDeepOrStrict(err, err2, AssertionError); } // Check for non-native errors. if (common.symbolToStringTagSupported) { const source = new Error('abc'); const err = Object.create( Object.getPrototypeOf(source), common.getOwnPropertyDescriptors(source)); Object.defineProperty(err, 'message', { value: 'foo' }); const err2 = Object.create( Object.getPrototypeOf(source), common.getOwnPropertyDescriptors(source)); Object.defineProperty(err2, 'message', { value: 'bar' }); err[Symbol.toStringTag] = 'Foo'; err2[Symbol.toStringTag] = 'Foo'; assert.notDeepStrictEqual(err, err2); } // Verify that `valueOf` is not called for boxed primitives. { const a = new Number(5); const b = new Number(5); Object.defineProperty(a, 'valueOf', { value: () => { throw new Error('failed'); } }); Object.defineProperty(b, 'valueOf', { value: () => { throw new Error('failed'); } }); assertDeepAndStrictEqual(a, b); } // Check getters. { const a = { get a() { return 5; } }; const b = { get a() { return 6; } }; assert.throws( () => assert.deepStrictEqual(a, b), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: /a: \[Getter: 5]\n- a: \[Getter: 6]\n / } ); // The descriptor is not compared. assertDeepAndStrictEqual(a, { a: 5 }); } commonjs-assert-2.0.0/test/parallel/test-assert-fail-deprecation.js000066400000000000000000000033671346577622100254560ustar00rootroot00000000000000// Currently in sync with Node.js test/parallel/test-assert-fail-deprecation.js // https://github.com/nodejs/node/commit/1ed3c54ecbd72a33693e5954f86bcc9fd9b1cc09 'use strict'; const common = require('../common'); const assert = require('../../assert'); common.expectWarning( 'DeprecationWarning', 'assert.fail() with more than one argument is deprecated. ' + 'Please use assert.strictEqual() instead or only pass a message.', 'DEP0094' ); // Two args only, operator defaults to '!=' assert.throws(() => { assert.fail('first', 'second'); }, { code: 'ERR_ASSERTION', name: 'AssertionError', message: '\'first\' != \'second\'', operator: '!=', actual: 'first', expected: 'second', generatedMessage: true }); // Three args assert.throws(() => { assert.fail('ignored', 'ignored', 'another custom message'); }, { code: 'ERR_ASSERTION', name: 'AssertionError', message: 'another custom message', operator: 'fail', actual: 'ignored', expected: 'ignored', generatedMessage: false }); // Three args with custom Error assert.throws(() => { assert.fail(typeof 1, 'object', new TypeError('another custom message')); }, { name: 'TypeError', message: 'another custom message' }); // No third arg (but a fourth arg) assert.throws(() => { assert.fail('first', 'second', undefined, 'operator'); }, { code: 'ERR_ASSERTION', name: 'AssertionError', message: '\'first\' operator \'second\'', operator: 'operator', actual: 'first', expected: 'second' }); // [broserify] Don't worry if some browsers have less accurate stacks // // The stackFrameFunction should exclude the foo frame // assert.throws( // function foo() { assert.fail('first', 'second', 'message', '!==', foo); }, // (err) => !/^\s*at\sfoo\b/m.test(err.stack) // ); commonjs-assert-2.0.0/test/parallel/test-assert-fail.js000066400000000000000000000015511346577622100231540ustar00rootroot00000000000000// Currently in sync with Node.js test/parallel/test-assert-fail.js // https://github.com/nodejs/node/commit/1ed3c54ecbd72a33693e5954f86bcc9fd9b1cc09 'use strict'; require('../common'); const assert = require('../../assert'); // No args assert.throws( () => { assert.fail(); }, { code: 'ERR_ASSERTION', name: 'AssertionError', message: 'Failed', operator: 'fail', actual: undefined, expected: undefined, generatedMessage: true } ); // One arg = message assert.throws(() => { assert.fail('custom message'); }, { code: 'ERR_ASSERTION', name: 'AssertionError', message: 'custom message', operator: 'fail', actual: undefined, expected: undefined, generatedMessage: false }); // One arg = Error assert.throws(() => { assert.fail(new TypeError('custom message')); }, { name: 'TypeError', message: 'custom message' }); commonjs-assert-2.0.0/test/parallel/test-assert-if-error.js000066400000000000000000000042301346577622100237630ustar00rootroot00000000000000// Currently in sync with Node.js test/parallel/test-assert-if-error.js // https://github.com/nodejs/node/commit/644fdd60d4be49ffa66d0bda1702c4459f607635 // [browserify] // Most `err.message` and `err.stack` tests are commented out because they are // inconsistent between browsers. 'use strict'; require('../common'); const assert = require('../../assert').strict; /* eslint-disable no-restricted-properties */ // Test that assert.ifError has the correct stack trace of both stacks. let err; // Create some random error frames. (function a() { (function b() { (function c() { err = new Error('test error'); })(); })(); })(); const msg = err.message; const stack = err.stack; (function x() { (function y() { (function z() { let threw = false; try { assert.ifError(err); } catch (e) { assert.equal(e.message, 'ifError got unwanted exception: test error'); assert.equal(err.message, msg); assert.equal(e.actual, err); assert.equal(e.actual.stack, stack); assert.equal(e.expected, null); assert.equal(e.operator, 'ifError'); threw = true; } assert(threw); })(); })(); })(); // assert.throws( // () => assert.ifError(new TypeError()), // { // message: 'ifError got unwanted exception: TypeError' // } // ); assert.throws( () => assert.ifError({ stack: false }), { message: 'ifError got unwanted exception: { stack: false }' } ); assert.throws( () => assert.ifError({ constructor: null, message: '' }), { message: 'ifError got unwanted exception: ' } ); assert.throws( () => { assert.ifError(false); }, { message: 'ifError got unwanted exception: false' } ); // Should not throw. assert.ifError(null); assert.ifError(); assert.ifError(undefined); // https://github.com/nodejs/node-v0.x-archive/issues/2893 { let threw = false; try { // eslint-disable-next-line no-restricted-syntax assert.throws(() => { assert.ifError(null); }); } catch (e) { threw = true; assert.strictEqual(e.message, 'Missing expected exception.'); // assert(!e.stack.includes('throws'), e.stack); } assert(threw); } commonjs-assert-2.0.0/test/parallel/test-assert-typedarray-deepequal.js000066400000000000000000000107321346577622100263710ustar00rootroot00000000000000// Currently in sync with Node.js test/parallel/test-assert-typedarray-deepequal.js // https://github.com/nodejs/node/commit/7493db21b667ed746d39c9b54357eac4287232e3 'use strict'; require('../common'); const assert = require('../../assert'); function makeBlock(f) { const args = Array.prototype.slice.call(arguments, 1); return function() { return f.apply(this, args); }; } const equalArrayPairs = [ [() => new Uint8Array(1e5), () => new Uint8Array(1e5)], [() => new Uint16Array(1e5), () => new Uint16Array(1e5)], [() => new Uint32Array(1e5), () => new Uint32Array(1e5)], [() => new Uint8ClampedArray(1e5), () => new Uint8ClampedArray(1e5)], [() => new Int8Array(1e5), () => new Int8Array(1e5)], [() => new Int16Array(1e5), () => new Int16Array(1e5)], [() => new Int32Array(1e5), () => new Int32Array(1e5)], [() => new Float32Array(1e5), () => new Float32Array(1e5)], [() => new Float64Array(1e5), () => new Float64Array(1e5)], [() => new Float32Array([+0.0]), () => new Float32Array([+0.0])], [() => new Uint8Array([1, 2, 3, 4]).subarray(1), () => new Uint8Array([2, 3, 4])], [() => new Uint16Array([1, 2, 3, 4]).subarray(1), () => new Uint16Array([2, 3, 4])], [() => new Uint32Array([1, 2, 3, 4]).subarray(1, 3), () => new Uint32Array([2, 3])], [() => new ArrayBuffer(3), () => new ArrayBuffer(3)], [() => new SharedArrayBuffer(3), () => new SharedArrayBuffer(3)] ]; const looseEqualArrayPairs = [ [() => new Float32Array([+0.0]), () => new Float32Array([-0.0])], [() => new Float64Array([+0.0]), () => new Float64Array([-0.0])] ]; const notEqualArrayPairs = [ [() => new ArrayBuffer(3), () => new SharedArrayBuffer(3)], [() => new Int16Array(256), () => new Uint16Array(256)], [() => new Int16Array([256]), () => new Uint16Array([256])], [() => new Float64Array([+0.0]), () => new Float32Array([-0.0])], [() => new Uint8Array(2), () => new Uint8Array(3)], [() => new Uint8Array([1, 2, 3]), () => new Uint8Array([4, 5, 6])], [() => new Uint8ClampedArray([300, 2, 3]), () => new Uint8Array([300, 2, 3])], [() => new Uint16Array([2]), () => new Uint16Array([3])], [() => new Uint16Array([0]), () => new Uint16Array([256])], [() => new Int16Array([0]), () => new Uint16Array([256])], [() => new Int16Array([-256]), () => new Uint16Array([0xff00])], // same bits [() => new Int32Array([-256]), () => new Uint32Array([0xffffff00])], // ditto [() => new Float32Array([0.1]), () => new Float32Array([0.0])], [() => new Float32Array([0.1]), () => new Float32Array([0.1, 0.2])], [() => new Float64Array([0.1]), () => new Float64Array([0.0])], [() => new Uint8Array([1, 2, 3]).buffer, () => new Uint8Array([4, 5, 6]).buffer], [ () => new Uint8Array(new SharedArrayBuffer(3)).fill(1).buffer, () => new Uint8Array(new SharedArrayBuffer(3)).fill(2).buffer ], [() => new ArrayBuffer(2), () => new ArrayBuffer(3)], [() => new SharedArrayBuffer(2), () => new SharedArrayBuffer(3)], [() => new ArrayBuffer(2), () => new SharedArrayBuffer(3)], [ () => new Uint8Array(new ArrayBuffer(3)).fill(1).buffer, () => new Uint8Array(new SharedArrayBuffer(3)).fill(2).buffer ] ]; console.log('equalArrayPairs'); equalArrayPairs.forEach((arrayPair) => { let array0; let array1; try { array0 = arrayPair[0](); array1 = arrayPair[1](); } catch(e) { console.log('Skipping unsupported typed array:', e.message); return; } // eslint-disable-next-line no-restricted-properties assert.deepEqual(array0, array1); assert.deepStrictEqual(array0, array1); }); console.log('looseEqualArrayPairs'); looseEqualArrayPairs.forEach((arrayPair) => { let array0; let array1; try { array0 = arrayPair[0](); array1 = arrayPair[1](); } catch(e) { console.log('Skipping unsupported typed array:', e.message); return; } // eslint-disable-next-line no-restricted-properties assert.deepEqual(array0, array1); assert.throws( makeBlock(assert.deepStrictEqual, array0, array1), assert.AssertionError ); }); console.log('notEqualArrayPairs'); notEqualArrayPairs.forEach((arrayPair) => { let array0; let array1; try { array0 = arrayPair[0](); array1 = arrayPair[1](); } catch(e) { console.log('Skipping unsupported typed array:', e.message); return; } assert.throws( // eslint-disable-next-line no-restricted-properties makeBlock(assert.deepEqual, array0, array1), assert.AssertionError ); assert.throws( makeBlock(assert.deepStrictEqual, array0, array1), assert.AssertionError ); }); commonjs-assert-2.0.0/test/parallel/test-assert.js000066400000000000000000000765631346577622100222620ustar00rootroot00000000000000// Currently in sync with Node.js test/parallel/test-assert.js // https://github.com/nodejs/node/commit/1ed3c54ecbd72a33693e5954f86bcc9fd9b1cc09 // Flags: --expose-internals // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // [browserify] // Most `err.message` and `err.stack` tests are commented out because they are // inconsistent between browsers. // // `err.operator` tests are commented out because its always `undefined` in IE. // If we drop IE support we can uncomment these tests. 'use strict'; const arrayFill = require('array-fill'); const common = require('../common'); const assert = require('../../assert'); const { inspect } = require('util/'); // [browserify] // const { internalBinding } = require('internal/test/binding'); const a = assert; // Disable colored output to prevent color codes from breaking assertion // message comparisons. This should only be an issue when process.stdout // is a TTY. if (process.stdout && process.stdout.isTTY) process.env.NODE_DISABLE_COLORS = '1'; const strictEqualMessageStart = 'Expected values to be strictly equal:\n'; const start = 'Expected values to be strictly deep-equal:'; const actExp = '+ actual - expected'; assert.ok(a.AssertionError.prototype instanceof Error, 'a.AssertionError instanceof Error'); assert.throws(() => a(false), a.AssertionError, 'ok(false)'); assert.throws(() => a.ok(false), a.AssertionError, 'ok(false)'); a(true); a('test', 'ok(\'test\')'); a.ok(true); a.ok('test'); assert.throws(() => a.equal(true, false), a.AssertionError, 'equal(true, false)'); a.equal(null, null); a.equal(undefined, undefined); a.equal(null, undefined); a.equal(true, true); a.equal(2, '2'); a.notEqual(true, false); assert.throws(() => a.notEqual(true, true), a.AssertionError, 'notEqual(true, true)'); assert.throws(() => a.strictEqual(2, '2'), a.AssertionError, 'strictEqual(2, \'2\')'); /* eslint-disable no-restricted-syntax */ assert.throws(() => a.strictEqual(null, undefined), a.AssertionError, 'strictEqual(null, undefined)'); assert.throws( () => a.notStrictEqual(2, 2), { // message: 'Expected "actual" to be strictly unequal to: 2', name: 'AssertionError' } ); assert.throws( () => a.notStrictEqual(common.repeat('a ', 30), common.repeat('a ', 30)), { // message: 'Expected "actual" to be strictly unequal to: ' + // `'${'a '.repeat(30)}'`, name: 'AssertionError' } ); a.notStrictEqual(2, '2'); // Testing the throwing. function thrower(errorConstructor) { throw new errorConstructor({}); } // The basic calls work. assert.throws(() => thrower(a.AssertionError), a.AssertionError, 'message'); assert.throws(() => thrower(a.AssertionError), a.AssertionError); assert.throws(() => thrower(a.AssertionError)); // If not passing an error, catch all. assert.throws(() => thrower(TypeError)); // When passing a type, only catch errors of the appropriate type. { let threw = false; try { a.throws(() => thrower(TypeError), a.AssertionError); } catch (e) { threw = true; assert.ok(e instanceof TypeError, 'type'); } assert.ok(threw, 'a.throws with an explicit error is eating extra errors'); } // doesNotThrow should pass through all errors. { let threw = false; try { a.doesNotThrow(() => thrower(TypeError), a.AssertionError); } catch (e) { threw = true; assert.ok(e instanceof TypeError); } assert(threw, 'a.doesNotThrow with an explicit error is eating extra errors'); } // Key difference is that throwing our correct error makes an assertion error. { let threw = false; try { a.doesNotThrow(() => thrower(TypeError), TypeError); } catch (e) { threw = true; assert.ok(e instanceof a.AssertionError); assert.ok(!common.includes(e.stack, 'at Function.doesNotThrow')); } assert.ok(threw, 'a.doesNotThrow is not catching type matching errors'); } assert.throws( () => a.doesNotThrow(() => thrower(Error), 'user message'), { name: 'AssertionError', code: 'ERR_ASSERTION', // operator: 'doesNotThrow', // message: 'Got unwanted exception: user message\n' + // 'Actual message: "[object Object]"' } ); assert.throws( () => a.doesNotThrow(() => thrower(Error)), { code: 'ERR_ASSERTION', // message: 'Got unwanted exception.\nActual message: "[object Object]"' } ); // Make sure that validating using constructor really works. { let threw = false; try { assert.throws( () => { throw ({}); // eslint-disable-line no-throw-literal }, Array ); } catch(e) { threw = true; } assert.ok(threw, 'wrong constructor validation'); } // Use a RegExp to validate the error message. a.throws(() => thrower(TypeError), /\[object Object\]/); // Use a fn to validate the error object. a.throws(() => thrower(TypeError), (err) => { if ((err instanceof TypeError) && /\[object Object\]/.test(err)) { return true; } }); // https://github.com/nodejs/node/issues/3188 { let threw = false; let AnotherErrorType; try { const ES6Error = class extends Error {}; AnotherErrorType = class extends Error {}; assert.throws(() => { throw new AnotherErrorType('foo'); }, ES6Error); } catch (e) { threw = true; assert(e instanceof AnotherErrorType, `expected AnotherErrorType, received ${e}`); } assert.ok(threw); } // Check messages from assert.throws(). { const noop = () => {}; assert.throws( () => { a.throws((noop)); }, { code: 'ERR_ASSERTION', // message: 'Missing expected exception.', // operator: 'throws', actual: undefined, expected: undefined }); assert.throws( () => { a.throws(noop, TypeError); }, { code: 'ERR_ASSERTION', // message: 'Missing expected exception (TypeError).', actual: undefined, expected: TypeError }); assert.throws( () => { a.throws(noop, 'fhqwhgads'); }, { code: 'ERR_ASSERTION', // message: 'Missing expected exception: fhqwhgads', actual: undefined, expected: undefined }); assert.throws( () => { a.throws(noop, TypeError, 'fhqwhgads'); }, { code: 'ERR_ASSERTION', // message: 'Missing expected exception (TypeError): fhqwhgads', actual: undefined, expected: TypeError }); let threw = false; try { a.throws(noop); } catch (e) { threw = true; assert.ok(e instanceof a.AssertionError); assert.ok(!common.includes(e.stack, 'at Function.throws')); } assert.ok(threw); } const circular = { y: 1 }; circular.x = circular; function testAssertionMessage(actual, expected, msg) { assert.throws( () => assert.strictEqual(actual, ''), // { // // generatedMessage: true, // // message: msg || strictEqualMessageStart + // // `+ actual - expected\n\n+ ${expected}\n- ''` // } ); } function testShortAssertionMessage(actual, expected) { testAssertionMessage(actual, expected, strictEqualMessageStart + `\n${inspect(actual)} !== ''\n`); } testShortAssertionMessage(null, 'null'); testShortAssertionMessage(true, 'true'); testShortAssertionMessage(false, 'false'); testShortAssertionMessage(100, '100'); testShortAssertionMessage(NaN, 'NaN'); testShortAssertionMessage(Infinity, 'Infinity'); testShortAssertionMessage('a', '"a"'); testShortAssertionMessage('foo', '\'foo\''); testShortAssertionMessage(0, '0'); if (common.symbolSupported) { testShortAssertionMessage(Symbol(), 'Symbol()'); } testAssertionMessage([], '[]'); testAssertionMessage(/a/, '/a/'); testAssertionMessage(/abc/gim, '/abc/gim'); testAssertionMessage({}, '{}'); testAssertionMessage(undefined, 'undefined'); testAssertionMessage(-Infinity, '-Infinity'); testAssertionMessage([1, 2, 3], '[\n+ 1,\n+ 2,\n+ 3\n+ ]'); testAssertionMessage(function f() {}, '[Function: f]'); testAssertionMessage(function() {}, '[Function]'); testAssertionMessage(circular, '{\n+ x: [Circular],\n+ y: 1\n+ }'); testAssertionMessage({ a: undefined, b: null }, '{\n+ a: undefined,\n+ b: null\n+ }'); testAssertionMessage({ a: NaN, b: Infinity, c: -Infinity }, '{\n+ a: NaN,\n+ b: Infinity,\n+ c: -Infinity\n+ }'); // https://github.com/nodejs/node-v0.x-archive/issues/5292 try { assert.strictEqual(1, 2); } catch (e) { assert.strictEqual( e.message, `${strictEqualMessageStart}\n1 !== 2\n` ); assert.ok(e.generatedMessage, 'Message not marked as generated'); } try { assert.strictEqual(1, 2, 'oh no'); } catch (e) { assert.strictEqual(e.message, 'oh no'); // Message should not be marked as generated. assert.strictEqual(e.generatedMessage, false); } { let threw = false; const rangeError = new RangeError('my range'); // Verify custom errors. try { assert.strictEqual(1, 2, rangeError); } catch (e) { assert.strictEqual(e, rangeError); threw = true; assert.ok(e instanceof RangeError, 'Incorrect error type thrown'); } assert.ok(threw); threw = false; // Verify AssertionError is the result from doesNotThrow with custom Error. try { a.doesNotThrow(() => { throw new TypeError('wrong type'); }, TypeError, rangeError); } catch (e) { threw = true; assert.ok(common.includes(e.message, rangeError.message)); assert.ok(e instanceof assert.AssertionError); // [browserify] // This fails because `doesNotThrow` appears in the stack trace. // I'm not quite sure why that's an issue if the error message is set // and the above tests pass so commenting out for now. // assert.ok(!common.includes(e.stack, 'doesNotThrow'), e.stack); } assert.ok(threw); } { // Verify that throws() and doesNotThrow() throw on non-functions. const testBlockTypeError = (method, fn) => { common.expectsError( () => method(fn), { code: 'ERR_INVALID_ARG_TYPE', // type: TypeError, // message: 'The "fn" argument must be of type Function. Received ' + // `type ${typeof fn}` } ); }; testBlockTypeError(assert.throws, 'string'); testBlockTypeError(assert.doesNotThrow, 'string'); testBlockTypeError(assert.throws, 1); testBlockTypeError(assert.doesNotThrow, 1); testBlockTypeError(assert.throws, true); testBlockTypeError(assert.doesNotThrow, true); testBlockTypeError(assert.throws, false); testBlockTypeError(assert.doesNotThrow, false); testBlockTypeError(assert.throws, []); testBlockTypeError(assert.doesNotThrow, []); testBlockTypeError(assert.throws, {}); testBlockTypeError(assert.doesNotThrow, {}); testBlockTypeError(assert.throws, /foo/); testBlockTypeError(assert.doesNotThrow, /foo/); testBlockTypeError(assert.throws, null); testBlockTypeError(assert.doesNotThrow, null); testBlockTypeError(assert.throws, undefined); testBlockTypeError(assert.doesNotThrow, undefined); } // https://github.com/nodejs/node/issues/3275 // eslint-disable-next-line no-throw-literal assert.throws(() => { throw 'error'; }, (err) => err === 'error'); assert.throws(() => { throw new Error(); }, (err) => err instanceof Error); // Long values should be truncated for display. assert.throws(() => { assert.strictEqual(common.repeat('A', 1000), ''); }, { code: 'ERR_ASSERTION', // message: `${strictEqualMessageStart}+ actual - expected\n\n` + // `+ '${'A'.repeat(1000)}'\n- ''` }); if (common.symbolSupported) { // Bad args to AssertionError constructor should throw TypeError. const args = [1, true, false, '', null, Infinity, Symbol('test'), undefined]; args.forEach((input) => { assert.throws( () => new assert.AssertionError(input), { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', // message: 'The "options" argument must be of type Object. ' + // `Received type ${typeof input}` }); }); } assert.throws( () => assert.strictEqual(new Error('foo'), new Error('foobar')), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: 'Expected "actual" to be reference-equal to "expected":\n' + // '+ actual - expected\n\n' + // '+ [Error: foo]\n- [Error: foobar]' } ); // Test strict assert. { const a = require('../../assert'); const assert = require('../../assert').strict; /* eslint-disable no-restricted-properties */ assert.throws(() => assert.equal(1, true), assert.AssertionError); assert.notEqual(0, false); assert.throws(() => assert.deepEqual(1, true), assert.AssertionError); assert.notDeepEqual(0, false); assert.equal(assert.strict, assert.strict.strict); assert.equal(assert.equal, assert.strictEqual); assert.equal(assert.deepEqual, assert.deepStrictEqual); assert.equal(assert.notEqual, assert.notStrictEqual); assert.equal(assert.notDeepEqual, assert.notDeepStrictEqual); assert.equal(Object.keys(assert).length, Object.keys(a).length); assert(7); assert.throws( () => assert(...[]), { // message: 'No value argument passed to `assert.ok()`', name: 'AssertionError', // generatedMessage: true } ); assert.throws( () => a(), { // message: 'No value argument passed to `assert.ok()`', name: 'AssertionError' } ); // Test setting the limit to zero and that assert.strict works properly. const tmpLimit = Error.stackTraceLimit; Error.stackTraceLimit = 0; common.expectsError( () => { assert.ok( typeof 123 === 'string' ); }, { code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'The expression evaluated to a falsy value:\n\n ' + // "assert.ok(\n typeof 123 === 'string'\n )\n" } ); Error.stackTraceLimit = tmpLimit; // Test error diffs. let message = [ start, `${actExp} ... Lines skipped`, '', ' [', ' [', '...', ' 2,', '+ 3', "- '3'", ' ]', '...', ' 5', ' ]'].join('\n'); assert.throws( () => assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]), // { message } ); message = [ start, `${actExp} ... Lines skipped`, '', ' [', ' 1,', '...', ' 0,', '- 1,', ' 1,', '...', ' 1', ' ]' ].join('\n'); assert.throws( () => assert.deepEqual( [1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1]), // { message } ); message = [ start, `${actExp} ... Lines skipped`, '', ' [', ' 1,', '...', ' 0,', '+ 1,', ' 1,', '...', ' 1', ' ]' ].join('\n'); assert.throws( () => assert.deepEqual( [1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1]), // { message } ); message = [ start, actExp, '', ' [', ' 1,', '+ 2,', '- 1,', ' 1,', ' 1,', ' 0,', '+ 1,', ' 1', ' ]' ].join('\n'); assert.throws( () => assert.deepEqual( [1, 2, 1, 1, 0, 1, 1], [1, 1, 1, 1, 0, 1]), // { message } ); message = [ start, actExp, '', '+ [', '+ 1,', '+ 2,', '+ 1', '+ ]', '- undefined', ].join('\n'); assert.throws( () => assert.deepEqual([1, 2, 1], undefined), // { message } ); message = [ start, actExp, '', ' [', '+ 1,', ' 2,', ' 1', ' ]' ].join('\n'); assert.throws( () => assert.deepEqual([1, 2, 1], [2, 1]), // { message } ); message = `${start}\n` + `${actExp} ... Lines skipped\n` + '\n' + ' [\n' + common.repeat('+ 1,\n', 10) + '...\n' + common.repeat('- 2,\n', 10) + '...'; assert.throws( () => assert.deepEqual(arrayFill(Array(12), 1), arrayFill(Array(12), 2)), // { message } ); const obj1 = {}; const obj2 = { loop: 'forever' }; obj2[inspect.custom] = () => '{}'; // No infinite loop and no custom inspect. assert.throws( () => assert.deepEqual(obj1, obj2), // { // message: `${start}\n` + // `${actExp}\n` + // '\n' + // '+ {}\n' + // '- {\n' + // '- [Symbol(nodejs.util.inspect.custom)]: [Function],\n' + // "- loop: 'forever'\n" + // '- }' // } ); // notDeepEqual tests assert.throws( () => assert.notDeepEqual([1], [1]), // { // message: 'Expected "actual" not to be strictly deep-equal to:\n\n' + // '[\n 1\n]\n' // } ); message = 'Expected "actual" not to be strictly deep-equal to:' + `\n\n[${common.repeat('\n 1,', 25)}\n...\n`; const data = arrayFill(Array(31), 1); assert.throws( () => assert.notDeepEqual(data, data), // { message } ); /* eslint-enable no-restricted-properties */ } common.expectsError( () => assert.ok(null), { code: 'ERR_ASSERTION', // type: assert.AssertionError, // generatedMessage: true, // message: 'The expression evaluated to a falsy value:\n\n ' + // 'assert.ok(null)\n' } ); common.expectsError( () => assert(typeof 123 === 'string'), { code: 'ERR_ASSERTION', // type: assert.AssertionError, // generatedMessage: true, // message: 'The expression evaluated to a falsy value:\n\n ' + // "assert(typeof 123 === 'string')\n" } ); if (common.symbolSupported) { common.expectsError( () => assert(false, Symbol('foo')), { code: 'ERR_ASSERTION', // type: assert.AssertionError, generatedMessage: false, // message: 'Symbol(foo)' } ); } // [browserify] // This test uses internal Node.js functionality so we have to skip it. // { // // Test caching. // const fs = internalBinding('fs'); // const tmp = fs.close; // fs.close = common.mustCall(tmp, 1); // function throwErr() { // assert( // (Buffer.from('test') instanceof Error) // ); // } // common.expectsError( // () => throwErr(), // { // code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'The expression evaluated to a falsy value:\n\n ' + // "assert(\n (Buffer.from('test') instanceof Error)\n )\n" // } // ); // common.expectsError( // () => throwErr(), // { // code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'The expression evaluated to a falsy value:\n\n ' + // "assert(\n (Buffer.from('test') instanceof Error)\n )\n" // } // ); // fs.close = tmp; // } common.expectsError( () => { a( (() => 'string')() // eslint-disable-next-line operator-linebreak === 123 instanceof Buffer ); }, { code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'The expression evaluated to a falsy value:\n\n' + // ' a(\n' + // ' (() => \'string\')()\n' + // ' // eslint-disable-next-line operator-linebreak\n' + // ' ===\n' + // ' 123 instanceof\n' + // ' Buffer\n' + // ' )\n' } ); common.expectsError( () => { a( (() => 'string')() // eslint-disable-next-line operator-linebreak === 123 instanceof Buffer ); }, { code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'The expression evaluated to a falsy value:\n\n' + // ' a(\n' + // ' (() => \'string\')()\n' + // ' // eslint-disable-next-line operator-linebreak\n' + // ' ===\n' + // ' 123 instanceof\n' + // ' Buffer\n' + // ' )\n' } ); /* eslint-disable indent */ common.expectsError(() => { a(( () => 'string')() === 123 instanceof Buffer ); }, { code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'The expression evaluated to a falsy value:\n\n' + // ' a((\n' + // ' () => \'string\')() ===\n' + // ' 123 instanceof\n' + // ' Buffer\n' + // ' )\n' } ); /* eslint-enable indent */ common.expectsError( () => { assert(true); assert(null, undefined); }, { code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'The expression evaluated to a falsy value:\n\n ' + // 'assert(null, undefined)\n' } ); common.expectsError( () => { assert .ok(null, undefined); }, { code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'The expression evaluated to a falsy value:\n\n ' + // 'ok(null, undefined)\n' } ); common.expectsError( // eslint-disable-next-line dot-notation, quotes () => assert['ok']["apply"](null, [0]), { code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'The expression evaluated to a falsy value:\n\n ' + // 'assert[\'ok\']["apply"](null, [0])\n' } ); common.expectsError( () => { const wrapper = (fn, value) => fn(value); wrapper(assert, false); }, { code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'The expression evaluated to a falsy value:\n\n fn(value)\n' } ); common.expectsError( () => assert.ok.call(null, 0), { code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'The expression evaluated to a falsy value:\n\n ' + // 'assert.ok.call(null, 0)\n', // generatedMessage: true } ); common.expectsError( () => assert.ok.call(null, 0, 'test'), { code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'test', generatedMessage: false } ); // Works in eval. common.expectsError( () => new Function('assert', 'assert(1 === 2);')(assert), { code: 'ERR_ASSERTION', // type: assert.AssertionError, // message: 'false == true' } ); common.expectsError( () => assert.throws(() => {}, 'Error message', 'message'), { code: 'ERR_INVALID_ARG_TYPE', // type: TypeError, // message: 'The "error" argument must be one of type Object, Error, ' + // 'Function, or RegExp. Received type string' } ); if (common.symbolSupported) { [ 1, false, Symbol() ].forEach((input) => { assert.throws( () => assert.throws(() => {}, input), { code: 'ERR_INVALID_ARG_TYPE', // message: 'The "error" argument must be one of type Object, Error, ' + // `Function, or RegExp. Received type ${typeof input}` } ); }); } { assert.throws( () => { assert.ok((() => Boolean('' === false))()); }, // { // message: 'The expression evaluated to a falsy value:\n\n' + // " assert.ok((() => Boolean('\\u0001' === false))())\n" // } ); const errFn = () => { const err = new TypeError('Wrong value'); err.code = 404; throw err; }; const errObj = { name: 'TypeError', // message: 'Wrong value' }; assert.throws(errFn, errObj); errObj.code = 404; assert.throws(errFn, errObj); // Fail in case a expected property is undefined and not existent on the // error. errObj.foo = undefined; assert.throws( () => assert.throws(errFn, errObj), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: `${start}\n${actExp}\n\n` + // ' Comparison {\n' + // ' code: 404,\n' + // '- foo: undefined,\n' + // " message: 'Wrong value',\n" + // " name: 'TypeError'\n" + // ' }' } ); // Show multiple wrong properties at the same time. errObj.code = '404'; assert.throws( () => assert.throws(errFn, errObj), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: `${start}\n${actExp}\n\n` + // ' Comparison {\n' + // '+ code: 404,\n' + // "- code: '404',\n" + // '- foo: undefined,\n' + // " message: 'Wrong value',\n" + // " name: 'TypeError'\n" + // ' }' } ); common.expectsError( () => assert.throws(() => { throw new Error(); }, { foo: 'bar' }, 'foobar'), { // type: assert.AssertionError, code: 'ERR_ASSERTION', // message: 'foobar' } ); common.expectsError( () => a.doesNotThrow(() => { throw new Error(); }, { foo: 'bar' }), { // type: TypeError, code: 'ERR_INVALID_ARG_TYPE', // message: 'The "expected" argument must be one of type Function or ' + // 'RegExp. Received type object' } ); // [browserify] Error objects will not be strictly equal in some browsers due // to different `line`/`column` properties. // assert.throws(() => { throw new Error('e'); }, new Error('e')); assert.throws( () => assert.throws(() => { throw new TypeError('e'); }, new Error('e')), { name: 'AssertionError', code: 'ERR_ASSERTION', // message: `${start}\n${actExp}\n\n` + // ' Comparison {\n' + // " message: 'e',\n" + // "+ name: 'TypeError'\n" + // "- name: 'Error'\n" + // ' }' } ); assert.throws( () => assert.throws(() => { throw new Error('foo'); }, new Error('')), { name: 'AssertionError', code: 'ERR_ASSERTION', // generatedMessage: true, // message: `${start}\n${actExp}\n\n` + // ' Comparison {\n' + // "+ message: 'foo',\n" + // "- message: '',\n" + // " name: 'Error'\n" + // ' }' } ); // eslint-disable-next-line no-throw-literal assert.throws(() => { throw undefined; }, /undefined/); assert.throws( // eslint-disable-next-line no-throw-literal () => a.doesNotThrow(() => { throw undefined; }), { name: 'AssertionError', code: 'ERR_ASSERTION', // message: 'Got unwanted exception.\nActual message: "undefined"' } ); } assert.throws( () => assert.throws(() => { throw new Error(); }, {}), { // message: "The argument 'error' may not be an empty object. Received {}", code: 'ERR_INVALID_ARG_VALUE' } ); assert.throws( () => a.throws( // eslint-disable-next-line no-throw-literal () => { throw 'foo'; }, 'foo' ), { code: 'ERR_AMBIGUOUS_ARGUMENT', // message: 'The "error/message" argument is ambiguous. ' + // 'The error "foo" is identical to the message.' } ); assert.throws( () => a.throws( () => { throw new TypeError('foo'); }, 'foo' ), { code: 'ERR_AMBIGUOUS_ARGUMENT', // message: 'The "error/message" argument is ambiguous. ' + // 'The error message "foo" is identical to the message.' } ); /* eslint-enable no-restricted-syntax */ // Should not throw. // eslint-disable-next-line no-restricted-syntax, no-throw-literal assert.throws(() => { throw null; }, 'foo'); assert.throws( () => assert.strictEqual([], []), // { // message: 'Values identical but not reference-equal:\n\n[]\n' // } ); { const args = (function() { return arguments; })('a'); assert.throws( () => assert.strictEqual(args, { 0: 'a' }), // { // message: 'Expected "actual" to be reference-equal to "expected":\n' + // '+ actual - expected\n\n' + // "+ [Arguments] {\n- {\n '0': 'a'\n }" // } ); } assert.throws( () => { throw new TypeError('foobar'); }, { // message: /foo/, name: /^TypeError$/ } ); assert.throws( () => assert.throws( () => { throw new TypeError('foobar'); }, { message: /fooa/, name: /^TypeError$/ } ), // { // message: `${start}\n${actExp}\n\n` + // ' Comparison {\n' + // "+ message: 'foobar',\n" + // '- message: /fooa/,\n' + // " name: 'TypeError'\n" + // ' }' // } ); { let actual = null; const expected = { message: 'foo' }; assert.throws( () => assert.throws( () => { throw actual; }, expected ), { // operator: 'throws', actual, expected, // generatedMessage: true, // message: `${start}\n${actExp}\n\n` + // '+ null\n' + // '- {\n' + // "- message: 'foo'\n" + // '- }' } ); actual = 'foobar'; const message = 'message'; assert.throws( () => assert.throws( () => { throw actual; }, { message: 'foobar' }, message ), { actual, message, // operator: 'throws', generatedMessage: false } ); } // Indicate where the strings diverge. assert.throws( () => assert.strictEqual('test test', 'test foobar'), { code: 'ERR_ASSERTION', name: 'AssertionError', // message: strictEqualMessageStart + // '+ actual - expected\n\n' + // "+ 'test test'\n" + // "- 'test foobar'\n" + // ' ^' } ); // Check for reference-equal objects in `notStrictEqual()` assert.throws( () => { const obj = {}; assert.notStrictEqual(obj, obj); }, { code: 'ERR_ASSERTION', name: 'AssertionError', // message: 'Expected "actual" not to be reference-equal to "expected": {}' } ); assert.throws( () => { const obj = { a: true }; assert.notStrictEqual(obj, obj); }, { code: 'ERR_ASSERTION', name: 'AssertionError', // message: 'Expected "actual" not to be reference-equal to "expected":\n\n' + // '{\n a: true\n}\n' } ); { let threw = false; try { assert.deepStrictEqual(arrayFill(Array(100), 1), 'foobar'); } catch (err) { threw = true; // assert(/actual: \[Array],\n expected: 'foobar',/.test(inspect(err))); } assert(threw); } assert.throws( () => a.equal(1), { code: 'ERR_MISSING_ARGS' } ); assert.throws( () => a.deepEqual(/a/), { code: 'ERR_MISSING_ARGS' } ); assert.throws( () => a.notEqual(null), { code: 'ERR_MISSING_ARGS' } ); assert.throws( () => a.notDeepEqual('test'), { code: 'ERR_MISSING_ARGS' } ); assert.throws( () => a.strictEqual({}), { code: 'ERR_MISSING_ARGS' } ); if (common.symbolSupported) { assert.throws( () => a.deepStrictEqual(Symbol()), { code: 'ERR_MISSING_ARGS' } ); } if (common.bigIntSupported) { assert.throws( () => a.notStrictEqual(eval('5n')), { code: 'ERR_MISSING_ARGS' } ); } assert.throws( () => a.notDeepStrictEqual(undefined), { code: 'ERR_MISSING_ARGS' } ); assert.throws( () => a.strictEqual(), { code: 'ERR_MISSING_ARGS' } ); assert.throws( () => a.deepStrictEqual(), { code: 'ERR_MISSING_ARGS' } ); commonjs-assert-2.0.0/test/pseudo-tty/000077500000000000000000000000001346577622100177465ustar00rootroot00000000000000commonjs-assert-2.0.0/test/pseudo-tty/test-assert-colors.js000066400000000000000000000022211346577622100240560ustar00rootroot00000000000000// Currently in sync with Node.js test/pseudo-tty/test-assert-colors.js // https://github.com/nodejs/node/commit/7f2d2cdc0cb45b8c97abf152b5cce6ec43aaaf79 'use strict'; require('../common'); const assert = require('../../assert').strict; try { // Activate colors even if the tty does not support colors. process.env.COLORTERM = '1'; // Make sure TERM is not set to e.g., 'dumb' and NODE_DISABLE_COLORS is not // active. process.env.TERM = 'FOOBAR'; delete process.env.NODE_DISABLE_COLORS; assert.deepStrictEqual([1, 2, 2, 2], [2, 2, 2, 2]); } catch (err) { const expected = 'Expected values to be strictly deep-equal:\n' + '\u001b[32m+ actual\u001b[39m \u001b[31m- expected\u001b[39m' + ' \u001b[34m...\u001b[39m Lines skipped\n\n' + ' [\n' + '\u001b[32m+\u001b[39m 1,\n' + '\u001b[31m-\u001b[39m 2,\n' + ' 2,\n' + '\u001b[34m...\u001b[39m\n' + ' 2\n' + ' ]'; // [browserify] // Don't test the exact message, it's inconstent between browsers. // assert.strictEqual(err.message, expected); if(process.stderr && process.stderr.getColorDepth) { assert(err.message.indexOf('[32m') > -1); } } commonjs-assert-2.0.0/test/pseudo-tty/test-assert-no-color.js000066400000000000000000000013171346577622100243120ustar00rootroot00000000000000// Currently in sync with Node.js test/pseudo-tty/test-assert-no-color.js // https://github.com/nodejs/node/commit/a2c2c78e097c4e1036eb24abd620a52c709a9467 'use strict'; require('../common'); const assert = require('../../assert').strict; process.env.NODE_DISABLE_COLORS = true; try { assert.deepStrictEqual({}, { foo: 'bar' }); } catch (error) { const expected = 'Expected values to be strictly deep-equal:\n' + '+ actual - expected\n' + '\n' + '+ {}\n' + '- {\n' + '- foo: \'bar\'\n' + '- }'; // [browserify] // Don't test the exact message, it's inconstent between browsers. // assert.strictEqual(error.message, expected); assert(error.message.indexOf('[32m') === -1); } commonjs-assert-2.0.0/test/pseudo-tty/test-assert-position-indicator.js000066400000000000000000000013561346577622100264030ustar00rootroot00000000000000// Currently in sync with Node.js test/pseudo-tty/test-assert-position-indicator.js // https://github.com/nodejs/node/commit/40a8a7391664e7a5d8a264a1d85d059f9c05063b 'use strict'; const common = require('../common'); const assert = require('../../assert'); process.env.NODE_DISABLE_COLORS = true; if (!process.stderr) { process.stderr = {}; } process.stderr.isTTY = true; process.stderr.columns = 20; // Confirm that there is no position indicator. assert.throws( () => { assert.deepStrictEqual('a'.repeat(30), 'a'.repeat(31)); }, (err) => !common.includes(err.message, '^') ); // Confirm that there is a position indicator. assert.throws( () => { assert.deepStrictEqual('aaa', 'aaaa'); }, (err) => common.includes(err.message, '^') );