SignedMath.test.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const { BN, constants } = require('@openzeppelin/test-helpers');
  2. const { expect } = require('chai');
  3. const { MIN_INT256, MAX_INT256 } = constants;
  4. const SignedMathMock = artifacts.require('SignedMathMock');
  5. contract('SignedMath', function () {
  6. const min = new BN('-1234');
  7. const max = new BN('5678');
  8. beforeEach(async function () {
  9. this.math = await SignedMathMock.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))
  61. .to.be.bignumber.equal(bnAverage(x, y), `Bad result for average(${x}, ${y})`);
  62. }
  63. }
  64. });
  65. });
  66. describe('abs', function () {
  67. for (const n of [
  68. MIN_INT256,
  69. MIN_INT256.addn(1),
  70. new BN('-1'),
  71. new BN('0'),
  72. new BN('1'),
  73. MAX_INT256.subn(1),
  74. MAX_INT256,
  75. ]) {
  76. it(`correctly computes the absolute value of ${n}`, async function () {
  77. expect(await this.math.abs(n)).to.be.bignumber.equal(n.abs());
  78. });
  79. }
  80. });
  81. });