SafeCast.test.js 1.5 KB

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