Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

assert.js 16KB

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