SignedMath.test.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const { BN, constants } = require('@openzeppelin/test-helpers');
  2. const { expect } = require('chai');
  3. const { MIN_INT256, MAX_INT256 } = constants;
  4. const SignedMath = artifacts.require('$SignedMath');
  5. contract('SignedMath', function () {
  6. const min = new BN('-1234');
  7. const max = new BN('5678');
  8. beforeEach(async function () {
  9. this.math = await SignedMath.new();
  10. });
  11. describe('max', function () {
  12. it('is correctly detected in first argument position', async function () {
  13. expect(await this.math.$max(max, min)).to.be.bignumber.equal(max);
  14. });
  15. it('is correctly detected in second argument position', async function () {
  16. expect(await this.math.$max(min, max)).to.be.bignumber.equal(max);
  17. });
  18. });
  19. describe('min', function () {
  20. it('is correctly detected in first argument position', async function () {
  21. expect(await this.math.$min(min, max)).to.be.bignumber.equal(min);
  22. });
  23. it('is correctly detected in second argument position', async function () {
  24. expect(await this.math.$min(max, min)).to.be.bignumber.equal(min);
  25. });
  26. });
  27. describe('average', function () {
  28. function bnAverage(a, b) {
  29. return a.add(b).divn(2);
  30. }
  31. it('is correctly calculated with various input', async function () {
  32. const valuesX = [
  33. new BN('0'),
  34. new BN('3'),
  35. new BN('-3'),
  36. new BN('4'),
  37. new BN('-4'),
  38. new BN('57417'),
  39. new BN('-57417'),
  40. new BN('42304'),
  41. new BN('-42304'),
  42. MIN_INT256,
  43. MAX_INT256,
  44. ];
  45. const valuesY = [
  46. new BN('0'),
  47. new BN('5'),
  48. new BN('-5'),
  49. new BN('2'),
  50. new BN('-2'),
  51. new BN('57417'),
  52. new BN('-57417'),
  53. new BN('42304'),
  54. new BN('-42304'),
  55. MIN_INT256,
  56. MAX_INT256,
  57. ];
  58. for (const x of valuesX) {
  59. for (const y of valuesY) {
  60. expect(await this.math.$average(x, y)).to.be.bignumber.equal(
  61. bnAverage(x, y),
  62. `Bad result for average(${x}, ${y})`,
  63. );
  64. }
  65. }
  66. });
  67. });
  68. describe('abs', function () {
  69. for (const n of [
  70. MIN_INT256,
  71. MIN_INT256.addn(1),
  72. new BN('-1'),
  73. new BN('0'),
  74. new BN('1'),
  75. MAX_INT256.subn(1),
  76. MAX_INT256,
  77. ]) {
  78. it(`correctly computes the absolute value of ${n}`, async function () {
  79. expect(await this.math.$abs(n)).to.be.bignumber.equal(n.abs());
  80. });
  81. }
  82. });
  83. });