Safe Casting Library from uint256 to uintXX (#1926)
* Include Safe Casting Library with complete and exhaustive test-suite. * linting test file. * Typo in SafeCast import statement * Update test/utils/SafeCast.test.js * Rename `castUXX` to `toUintXX` from suggestion * Tackling the quick and easy suggestions regarding error string improvements etc. * typo and changelog update. * Improve SafeCast tests * Update test/utils/SafeCast.test.js * Update test/utils/SafeCast.test.js * incorrect import * add SafeCast to docs site * Update CHANGELOG.md * Update SafeCast.sol
This commit is contained in:
committed by
Nicolás Venturo
parent
bfca6bd379
commit
2c11ed59fa
45
test/utils/SafeCast.test.js
Normal file
45
test/utils/SafeCast.test.js
Normal file
@ -0,0 +1,45 @@
|
||||
const { BN, expectRevert } = require('@openzeppelin/test-helpers');
|
||||
|
||||
const { expect } = require('chai');
|
||||
|
||||
const SafeCastMock = artifacts.require('SafeCastMock');
|
||||
|
||||
contract('SafeCast', async () => {
|
||||
beforeEach(async function () {
|
||||
this.safeCast = await SafeCastMock.new();
|
||||
});
|
||||
|
||||
function testToUint (bits) {
|
||||
describe(`toUint${bits}`, () => {
|
||||
const maxValue = new BN('2').pow(new BN(bits)).subn(1);
|
||||
|
||||
it('downcasts 0', async function () {
|
||||
expect(await this.safeCast[`toUint${bits}`](0)).to.be.bignumber.equal('0');
|
||||
});
|
||||
|
||||
it('downcasts 1', async function () {
|
||||
expect(await this.safeCast[`toUint${bits}`](1)).to.be.bignumber.equal('1');
|
||||
});
|
||||
|
||||
it(`downcasts 2^${bits} - 1 (${maxValue})`, async function () {
|
||||
expect(await this.safeCast[`toUint${bits}`](maxValue)).to.be.bignumber.equal(maxValue);
|
||||
});
|
||||
|
||||
it(`reverts when downcasting 2^${bits} (${maxValue.addn(1)})`, async function () {
|
||||
await expectRevert(
|
||||
this.safeCast[`toUint${bits}`](maxValue.addn(1)),
|
||||
`SafeCast: value doesn't fit in ${bits} bits`
|
||||
);
|
||||
});
|
||||
|
||||
it(`reverts when downcasting 2^${bits} + 1 (${maxValue.addn(2)})`, async function () {
|
||||
await expectRevert(
|
||||
this.safeCast[`toUint${bits}`](maxValue.addn(2)),
|
||||
`SafeCast: value doesn't fit in ${bits} bits`
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
[8, 16, 32, 64, 128].forEach(bits => testToUint(bits));
|
||||
});
|
||||
Reference in New Issue
Block a user