assert.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. const assert = {
  3. _isSameValue(a, b) {
  4. if (a === b) {
  5. // Handle +/-0 vs. -/+0
  6. return a !== 0 || 1 / a === 1 / b;
  7. }
  8. // Handle NaN vs. NaN
  9. return a !== a && b !== b;
  10. },
  11. _toString(value) {
  12. try {
  13. if (value === 0 && 1 / value === -Infinity) {
  14. return '-0';
  15. }
  16. return String(value);
  17. } catch (err) {
  18. if (err.name === 'TypeError') {
  19. return Object.prototype.toString.call(value);
  20. }
  21. throw err;
  22. }
  23. },
  24. sameValue(actual, expected, message) {
  25. if (assert._isSameValue(actual, expected)) {
  26. return;
  27. }
  28. if (message === undefined) {
  29. message = '';
  30. } else {
  31. message += ' ';
  32. }
  33. message += 'Expected SameValue(«' + assert._toString(actual) + '», «' + assert._toString(expected) + '») to be true';
  34. throw new Error(message);
  35. },
  36. throws(f, ctor, message) {
  37. if (message === undefined) {
  38. message = '';
  39. } else {
  40. message += ' ';
  41. }
  42. try {
  43. f();
  44. } catch (e) {
  45. if (e.constructor !== ctor) {
  46. throw new Error(message + "Wrong exception type was thrown: " + e.constructor.name);
  47. }
  48. return;
  49. }
  50. throw new Error(message + "No exception was thrown");
  51. },
  52. throwsNodeError(f, ctor, code, message) {
  53. if (message === undefined) {
  54. message = '';
  55. } else {
  56. message += ' ';
  57. }
  58. try {
  59. f();
  60. } catch (e) {
  61. if (e.constructor !== ctor) {
  62. throw new Error(message + "Wrong exception type was thrown: " + e.constructor.name);
  63. }
  64. if (e.code !== code) {
  65. throw new Error(message + "Wrong exception code was thrown: " + e.code);
  66. }
  67. return;
  68. }
  69. throw new Error(message + "No exception was thrown");
  70. }
  71. }
  72. module.exports = assert;