Solidity
松露測試:如何測試 SafeMath 庫是否溢出
如何通過松露測試來測試一個函式是否可以防止溢出?
contract SafeMath{ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract TestSafeMath{ function test_add_10_and_max_should_return_err() { uint256 max = 2**256 - 1; uint256 expected = "revert overflow error"; Assert.errorsEqual(SafeMathExt.add(10, max), expected, "Addition of 10 and max should revert"); } }
`TestSafeMath
- test_add_max_and_10_should_return_err No events were emitted 1 failing`
我怎樣才能通過這個測試?
我實際上不知道您的程式碼如何編譯,這顯然是一個問題
uint256 expected = "revert overflow error";
並且assert 庫的errorsEqual方法需要兩個錯誤程式碼
無論如何,解決此問題的一種方法是嘗試進行原始呼叫以測試 VM 內部是否存在恢復狀態。如果呼叫已正確執行,則 call 方法將返回 true,否則返回 false。
pragma solidity ^0.4.19; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/SafeMath.sol"; contract TestSafeMath { SafeMath instance; constructor() public { instance = SafeMath(DeployedAddresses.SafeMath()); } function testAdd_10_and_max_should_return_err() public { uint256 max = 2**256 - 1; bool passed = address(instance).call(bytes4(keccak256("add(uint256,uint256)")), 10, max); Assert.isFalse(passed, "test should fail"); } function testAdd_10_and_10_should_be_ok() public { uint256 value = 10; bool passed = address(instance).call(bytes4(keccak256("add(uint256,uint256)")), 10, value); Assert.isTrue(passed, "test should not fail"); Assert.equal(instance.add(10, value), value + 10, "should be 20"); } }
要獲得實際值,您需要再次呼叫該方法,因為原始呼叫不會給您返回值(請參閱第二個測試方法)。
輸出
TestSafeMath ✓ testAdd_10_and_max_should_return_err (53ms) ✓ testAdd_10_and_10_should_be_ok (66ms) 2 passing (987ms)