SafeCast.test.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. const { BN, expectRevert } = require('@openzeppelin/test-helpers');
  2. const { expect } = require('chai');
  3. const SafeCastMock = artifacts.require('SafeCastMock');
  4. contract('SafeCast', async () => {
  5. beforeEach(async function () {
  6. this.safeCast = await SafeCastMock.new();
  7. });
  8. function testToUint (bits) {
  9. describe(`toUint${bits}`, () => {
  10. const maxValue = new BN('2').pow(new BN(bits)).subn(1);
  11. it('downcasts 0', async function () {
  12. expect(await this.safeCast[`toUint${bits}`](0)).to.be.bignumber.equal('0');
  13. });
  14. it('downcasts 1', async function () {
  15. expect(await this.safeCast[`toUint${bits}`](1)).to.be.bignumber.equal('1');
  16. });
  17. it(`downcasts 2^${bits} - 1 (${maxValue})`, async function () {
  18. expect(await this.safeCast[`toUint${bits}`](maxValue)).to.be.bignumber.equal(maxValue);
  19. });
  20. it(`reverts when downcasting 2^${bits} (${maxValue.addn(1)})`, async function () {
  21. await expectRevert(
  22. this.safeCast[`toUint${bits}`](maxValue.addn(1)),
  23. `SafeCast: value doesn't fit in ${bits} bits`
  24. );
  25. });
  26. it(`reverts when downcasting 2^${bits} + 1 (${maxValue.addn(2)})`, async function () {
  27. await expectRevert(
  28. this.safeCast[`toUint${bits}`](maxValue.addn(2)),
  29. `SafeCast: value doesn't fit in ${bits} bits`
  30. );
  31. });
  32. });
  33. }
  34. [8, 16, 32, 64, 128].forEach(bits => testToUint(bits));
  35. });