SafeMath.test.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import assertJump from '../helpers/assertJump';
  2. const BigNumber = web3.BigNumber;
  3. const SafeMathMock = artifacts.require('SafeMathMock');
  4. require('chai')
  5. .use(require('chai-bignumber')(BigNumber))
  6. .should();
  7. contract('SafeMath', () => {
  8. const MAX_UINT = new BigNumber('115792089237316195423570985008687907853269984665640564039457584007913129639935');
  9. before(async function () {
  10. this.safeMath = await SafeMathMock.new();
  11. });
  12. describe('add', function () {
  13. it('adds correctly', async function () {
  14. const a = new BigNumber(5678);
  15. const b = new BigNumber(1234);
  16. const result = await this.safeMath.add(a, b);
  17. result.should.be.bignumber.equal(a.plus(b));
  18. });
  19. it('throws an error on addition overflow', async function () {
  20. const a = MAX_UINT;
  21. const b = new BigNumber(1);
  22. await assertJump(this.safeMath.add(a, b));
  23. });
  24. });
  25. describe('sub', function () {
  26. it('subtracts correctly', async function () {
  27. const a = new BigNumber(5678);
  28. const b = new BigNumber(1234);
  29. const result = await this.safeMath.sub(a, b);
  30. result.should.be.bignumber.equal(a.minus(b));
  31. });
  32. it('throws an error if subtraction result would be negative', async function () {
  33. const a = new BigNumber(1234);
  34. const b = new BigNumber(5678);
  35. await assertJump(this.safeMath.sub(a, b));
  36. });
  37. });
  38. describe('mul', function () {
  39. it('multiplies correctly', async function () {
  40. const a = new BigNumber(1234);
  41. const b = new BigNumber(5678);
  42. const result = await this.safeMath.mul(a, b);
  43. result.should.be.bignumber.equal(a.times(b));
  44. });
  45. it('handles a zero product correctly', async function () {
  46. const a = new BigNumber(0);
  47. const b = new BigNumber(5678);
  48. const result = await this.safeMath.mul(a, b);
  49. result.should.be.bignumber.equal(a.times(b));
  50. });
  51. it('throws an error on multiplication overflow', async function () {
  52. const a = MAX_UINT;
  53. const b = new BigNumber(2);
  54. await assertJump(this.safeMath.mul(a, b));
  55. });
  56. });
  57. describe('div', function () {
  58. it('divides correctly', async function () {
  59. const a = new BigNumber(5678);
  60. const b = new BigNumber(5678);
  61. const result = await this.safeMath.div(a, b);
  62. result.should.be.bignumber.equal(a.div(b));
  63. });
  64. it('throws an error on zero division', async function () {
  65. const a = new BigNumber(5678);
  66. const b = new BigNumber(0);
  67. await assertJump(this.safeMath.div(a, b));
  68. });
  69. });
  70. });