SignedMath.test.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 (accounts) {
  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. });