assert.js 15 KB

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