github.com/igggame/nebulas-go@v2.1.0+incompatible/nf/nvm/v8/lib/1.0.0/assert.js (about)

     1  // Copyright Joyent, Inc. and other Node contributors. All rights reserved.
     2  // Permission is hereby granted, free of charge, to any person obtaining a copy
     3  // of this software and associated documentation files (the "Software"), to
     4  // deal in the Software without restriction, including without limitation the
     5  // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
     6  // sell copies of the Software, and to permit persons to whom the Software is
     7  // furnished to do so, subject to the following conditions:
     8  
     9  // The above copyright notice and this permission notice shall be included in
    10  // all copies or substantial portions of the Software.
    11  
    12  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    13  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    14  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    15  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    16  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    17  // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    18  // IN THE SOFTWARE.
    19  // From: https://github.com/defunctzombie/commonjs-assert
    20  'use strict';
    21  
    22  // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
    23  // original notice:
    24  
    25  /*!
    26   * The buffer module from node.js, for the browser.
    27   *
    28   * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
    29   * @license  MIT
    30   */
    31  function compare(a, b) {
    32      if (a === b) {
    33          return 0;
    34      }
    35  
    36      var x = a.length;
    37      var y = b.length;
    38  
    39      for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    40          if (a[i] !== b[i]) {
    41              x = a[i];
    42              y = b[i];
    43              break;
    44          }
    45      }
    46  
    47      if (x < y) {
    48          return -1;
    49      }
    50      if (y < x) {
    51          return 1;
    52      }
    53      return 0;
    54  }
    55  
    56  function isBuffer(b) {
    57      if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
    58          return global.Buffer.isBuffer(b);
    59      }
    60      return !!(b != null && b._isBuffer);
    61  }
    62  
    63  // based on node assert, original notice:
    64  
    65  // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
    66  //
    67  // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
    68  //
    69  // Originally from narwhal.js (http://narwhaljs.org)
    70  // Copyright (c) 2009 Thomas Robinson <280north.com>
    71  //
    72  // Permission is hereby granted, free of charge, to any person obtaining a copy
    73  // of this software and associated documentation files (the 'Software'), to
    74  // deal in the Software without restriction, including without limitation the
    75  // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
    76  // sell copies of the Software, and to permit persons to whom the Software is
    77  // furnished to do so, subject to the following conditions:
    78  //
    79  // The above copyright notice and this permission notice shall be included in
    80  // all copies or substantial portions of the Software.
    81  //
    82  // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    83  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    84  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    85  // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
    86  // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    87  // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    88  
    89  var util = require('util.js');
    90  var hasOwn = Object.prototype.hasOwnProperty;
    91  var pSlice = Array.prototype.slice;
    92  var functionsHaveNames = (function () {
    93      return function foo() {}.name === 'foo';
    94  }());
    95  
    96  function pToString(obj) {
    97      return Object.prototype.toString.call(obj);
    98  }
    99  
   100  function isView(arrbuf) {
   101      if (isBuffer(arrbuf)) {
   102          return false;
   103      }
   104      if (typeof global.ArrayBuffer !== 'function') {
   105          return false;
   106      }
   107      if (typeof ArrayBuffer.isView === 'function') {
   108          return ArrayBuffer.isView(arrbuf);
   109      }
   110      if (!arrbuf) {
   111          return false;
   112      }
   113      if (arrbuf instanceof DataView) {
   114          return true;
   115      }
   116      if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
   117          return true;
   118      }
   119      return false;
   120  }
   121  // 1. The assert module provides functions that throw
   122  // AssertionError's when particular conditions are not met. The
   123  // assert module must conform to the following interface.
   124  
   125  var assert = module.exports = ok;
   126  
   127  // 2. The AssertionError is defined in assert.
   128  // new assert.AssertionError({ message: message,
   129  //                             actual: actual,
   130  //                             expected: expected })
   131  
   132  var regex = /\s*function\s+([^\(\s]*)\s*/;
   133  // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
   134  function getName(func) {
   135      if (!util.isFunction(func)) {
   136          return;
   137      }
   138      if (functionsHaveNames) {
   139          return func.name;
   140      }
   141      var str = func.toString();
   142      var match = str.match(regex);
   143      return match && match[1];
   144  }
   145  assert.AssertionError = function AssertionError(options) {
   146      this.name = 'AssertionError';
   147      this.actual = options.actual;
   148      this.expected = options.expected;
   149      this.operator = options.operator;
   150      if (options.message) {
   151          this.message = options.message;
   152          this.generatedMessage = false;
   153      } else {
   154          this.message = getMessage(this);
   155          this.generatedMessage = true;
   156      }
   157      var stackStartFunction = options.stackStartFunction || fail;
   158      if (Error.captureStackTrace) {
   159          Error.captureStackTrace(this, stackStartFunction);
   160      } else {
   161          // non v8 browsers so we can have a stacktrace
   162          var err = new Error();
   163          if (err.stack) {
   164              var out = err.stack;
   165  
   166              // try to strip useless frames
   167              var fn_name = getName(stackStartFunction);
   168              var idx = out.indexOf('\n' + fn_name);
   169              if (idx >= 0) {
   170                  // once we have located the function frame
   171                  // we need to strip out everything before it (and its line)
   172                  var next_line = out.indexOf('\n', idx + 1);
   173                  out = out.substring(next_line + 1);
   174              }
   175  
   176              this.stack = out;
   177          }
   178      }
   179  };
   180  
   181  // assert.AssertionError instanceof Error
   182  util.inherits(assert.AssertionError, Error);
   183  
   184  function truncate(s, n) {
   185      if (typeof s === 'string') {
   186          return s.length < n ? s : s.slice(0, n);
   187      } else {
   188          return s;
   189      }
   190  }
   191  
   192  function inspect(something) {
   193      if (functionsHaveNames || !util.isFunction(something)) {
   194          return util.inspect(something);
   195      }
   196      var rawname = getName(something);
   197      var name = rawname ? ': ' + rawname : '';
   198      return '[Function' + name + ']';
   199  }
   200  
   201  function getMessage(self) {
   202      return truncate(inspect(self.actual), 128) + ' ' +
   203          self.operator + ' ' +
   204          truncate(inspect(self.expected), 128);
   205  }
   206  
   207  // At present only the three keys mentioned above are used and
   208  // understood by the spec. Implementations or sub modules can pass
   209  // other keys to the AssertionError's constructor - they will be
   210  // ignored.
   211  
   212  // 3. All of the following functions must throw an AssertionError
   213  // when a corresponding condition is not met, with a message that
   214  // may be undefined if not provided.  All assertion methods provide
   215  // both the actual and expected values to the assertion error for
   216  // display purposes.
   217  
   218  function fail(actual, expected, message, operator, stackStartFunction) {
   219      throw new assert.AssertionError({
   220          message: message,
   221          actual: actual,
   222          expected: expected,
   223          operator: operator,
   224          stackStartFunction: stackStartFunction
   225      });
   226  }
   227  
   228  // EXTENSION! allows for well behaved errors defined elsewhere.
   229  assert.fail = fail;
   230  
   231  // 4. Pure assertion tests whether a value is truthy, as determined
   232  // by !!guard.
   233  // assert.ok(guard, message_opt);
   234  // This statement is equivalent to assert.equal(true, !!guard,
   235  // message_opt);. To test strictly for the value true, use
   236  // assert.strictEqual(true, guard, message_opt);.
   237  
   238  function ok(value, message) {
   239      if (!value) fail(value, true, message, '==', assert.ok);
   240  }
   241  assert.ok = ok;
   242  
   243  // 5. The equality assertion tests shallow, coercive equality with
   244  // ==.
   245  // assert.equal(actual, expected, message_opt);
   246  
   247  assert.equal = function equal(actual, expected, message) {
   248      if (actual != expected) fail(actual, expected, message, '==', assert.equal);
   249  };
   250  
   251  // 6. The non-equality assertion tests for whether two objects are not equal
   252  // with != assert.notEqual(actual, expected, message_opt);
   253  
   254  assert.notEqual = function notEqual(actual, expected, message) {
   255      if (actual == expected) {
   256          fail(actual, expected, message, '!=', assert.notEqual);
   257      }
   258  };
   259  
   260  // 7. The equivalence assertion tests a deep equality relation.
   261  // assert.deepEqual(actual, expected, message_opt);
   262  
   263  assert.deepEqual = function deepEqual(actual, expected, message) {
   264      if (!_deepEqual(actual, expected, false)) {
   265          fail(actual, expected, message, 'deepEqual', assert.deepEqual);
   266      }
   267  };
   268  
   269  assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
   270      if (!_deepEqual(actual, expected, true)) {
   271          fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
   272      }
   273  };
   274  
   275  function _deepEqual(actual, expected, strict, memos) {
   276      // 7.1. All identical values are equivalent, as determined by ===.
   277      if (actual === expected) {
   278          return true;
   279      } else if (isBuffer(actual) && isBuffer(expected)) {
   280          return compare(actual, expected) === 0;
   281  
   282          // 7.2. If the expected value is a Date object, the actual value is
   283          // equivalent if it is also a Date object that refers to the same time.
   284      } else if (util.isDate(actual) && util.isDate(expected)) {
   285          return actual.getTime() === expected.getTime();
   286  
   287          // 7.3 If the expected value is a RegExp object, the actual value is
   288          // equivalent if it is also a RegExp object with the same source and
   289          // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
   290      } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
   291          return actual.source === expected.source &&
   292              actual.global === expected.global &&
   293              actual.multiline === expected.multiline &&
   294              actual.lastIndex === expected.lastIndex &&
   295              actual.ignoreCase === expected.ignoreCase;
   296  
   297          // 7.4. Other pairs that do not both pass typeof value == 'object',
   298          // equivalence is determined by ==.
   299      } else if ((actual === null || typeof actual !== 'object') &&
   300          (expected === null || typeof expected !== 'object')) {
   301          return strict ? actual === expected : actual == expected;
   302  
   303          // If both values are instances of typed arrays, wrap their underlying
   304          // ArrayBuffers in a Buffer each to increase performance
   305          // This optimization requires the arrays to have the same type as checked by
   306          // Object.prototype.toString (aka pToString). Never perform binary
   307          // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
   308          // bit patterns are not identical.
   309      } else if (isView(actual) && isView(expected) &&
   310          pToString(actual) === pToString(expected) &&
   311          !(actual instanceof Float32Array ||
   312              actual instanceof Float64Array)) {
   313          return compare(new Uint8Array(actual.buffer),
   314              new Uint8Array(expected.buffer)) === 0;
   315  
   316          // 7.5 For all other Object pairs, including Array objects, equivalence is
   317          // determined by having the same number of owned properties (as verified
   318          // with Object.prototype.hasOwnProperty.call), the same set of keys
   319          // (although not necessarily the same order), equivalent values for every
   320          // corresponding key, and an identical 'prototype' property. Note: this
   321          // accounts for both named and indexed properties on Arrays.
   322      } else if (isBuffer(actual) !== isBuffer(expected)) {
   323          return false;
   324      } else {
   325          memos = memos || {
   326              actual: [],
   327              expected: []
   328          };
   329  
   330          var actualIndex = memos.actual.indexOf(actual);
   331          if (actualIndex !== -1) {
   332              if (actualIndex === memos.expected.indexOf(expected)) {
   333                  return true;
   334              }
   335          }
   336  
   337          memos.actual.push(actual);
   338          memos.expected.push(expected);
   339  
   340          return objEquiv(actual, expected, strict, memos);
   341      }
   342  }
   343  
   344  function isArguments(object) {
   345      return Object.prototype.toString.call(object) == '[object Arguments]';
   346  }
   347  
   348  function objEquiv(a, b, strict, actualVisitedObjects) {
   349      if (a === null || a === undefined || b === null || b === undefined)
   350          return false;
   351      // if one is a primitive, the other must be same
   352      if (util.isPrimitive(a) || util.isPrimitive(b))
   353          return a === b;
   354      if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
   355          return false;
   356      var aIsArgs = isArguments(a);
   357      var bIsArgs = isArguments(b);
   358      if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
   359          return false;
   360      if (aIsArgs) {
   361          a = pSlice.call(a);
   362          b = pSlice.call(b);
   363          return _deepEqual(a, b, strict);
   364      }
   365      var ka = objectKeys(a);
   366      var kb = objectKeys(b);
   367      var key, i;
   368      // having the same number of owned properties (keys incorporates
   369      // hasOwnProperty)
   370      if (ka.length !== kb.length)
   371          return false;
   372      //the same set of keys (although not necessarily the same order),
   373      ka.sort();
   374      kb.sort();
   375      //~~~cheap key test
   376      for (i = ka.length - 1; i >= 0; i--) {
   377          if (ka[i] !== kb[i])
   378              return false;
   379      }
   380      //equivalent values for every corresponding key, and
   381      //~~~possibly expensive deep test
   382      for (i = ka.length - 1; i >= 0; i--) {
   383          key = ka[i];
   384          if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
   385              return false;
   386      }
   387      return true;
   388  }
   389  
   390  // 8. The non-equivalence assertion tests for any deep inequality.
   391  // assert.notDeepEqual(actual, expected, message_opt);
   392  
   393  assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
   394      if (_deepEqual(actual, expected, false)) {
   395          fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
   396      }
   397  };
   398  
   399  assert.notDeepStrictEqual = notDeepStrictEqual;
   400  
   401  function notDeepStrictEqual(actual, expected, message) {
   402      if (_deepEqual(actual, expected, true)) {
   403          fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
   404      }
   405  }
   406  
   407  
   408  // 9. The strict equality assertion tests strict equality, as determined by ===.
   409  // assert.strictEqual(actual, expected, message_opt);
   410  
   411  assert.strictEqual = function strictEqual(actual, expected, message) {
   412      if (actual !== expected) {
   413          fail(actual, expected, message, '===', assert.strictEqual);
   414      }
   415  };
   416  
   417  // 10. The strict non-equality assertion tests for strict inequality, as
   418  // determined by !==.  assert.notStrictEqual(actual, expected, message_opt);
   419  
   420  assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
   421      if (actual === expected) {
   422          fail(actual, expected, message, '!==', assert.notStrictEqual);
   423      }
   424  };
   425  
   426  function expectedException(actual, expected) {
   427      if (!actual || !expected) {
   428          return false;
   429      }
   430  
   431      if (Object.prototype.toString.call(expected) == '[object RegExp]') {
   432          return expected.test(actual);
   433      }
   434  
   435      try {
   436          if (actual instanceof expected) {
   437              return true;
   438          }
   439      } catch (e) {
   440          // Ignore.  The instanceof check doesn't work for arrow functions.
   441      }
   442  
   443      if (Error.isPrototypeOf(expected)) {
   444          return false;
   445      }
   446  
   447      return expected.call({}, actual) === true;
   448  }
   449  
   450  function _tryBlock(block) {
   451      var error;
   452      try {
   453          block();
   454      } catch (e) {
   455          error = e;
   456      }
   457      return error;
   458  }
   459  
   460  function _throws(shouldThrow, block, expected, message) {
   461      var actual;
   462  
   463      if (typeof block !== 'function') {
   464          throw new TypeError('"block" argument must be a function');
   465      }
   466  
   467      if (typeof expected === 'string') {
   468          message = expected;
   469          expected = null;
   470      }
   471  
   472      actual = _tryBlock(block);
   473  
   474      message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
   475          (message ? ' ' + message : '.');
   476  
   477      if (shouldThrow && !actual) {
   478          fail(actual, expected, 'Missing expected exception' + message);
   479      }
   480  
   481      var userProvidedMessage = typeof message === 'string';
   482      var isUnwantedException = !shouldThrow && util.isError(actual);
   483      var isUnexpectedException = !shouldThrow && actual && !expected;
   484  
   485      if ((isUnwantedException &&
   486              userProvidedMessage &&
   487              expectedException(actual, expected)) ||
   488          isUnexpectedException) {
   489          fail(actual, expected, 'Got unwanted exception' + message);
   490      }
   491  
   492      if ((shouldThrow && actual && expected &&
   493              !expectedException(actual, expected)) || (!shouldThrow && actual)) {
   494          throw actual;
   495      }
   496  }
   497  
   498  // 11. Expected to throw an error:
   499  // assert.throws(block, Error_opt, message_opt);
   500  
   501  assert.throws = function (block, /*optional*/ error, /*optional*/ message) {
   502      _throws(true, block, error, message);
   503  };
   504  
   505  // EXTENSION! This is annoying to write outside this module.
   506  assert.doesNotThrow = function (block, /*optional*/ error, /*optional*/ message) {
   507      _throws(false, block, error, message);
   508  };
   509  
   510  assert.ifError = function (err) {
   511      if (err) throw err;
   512  };
   513  
   514  var objectKeys = Object.keys || function (obj) {
   515      var keys = [];
   516      for (var key in obj) {
   517          if (hasOwn.call(obj, key)) keys.push(key);
   518      }
   519      return keys;
   520  };