3

How can I test if a function is resistant against overflow with truffle test?

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 1) test_add_max_and_10_should_return_err No events were emitted 1 failing

How can I get this test passing?

2

I actually don't know how your code can compile, this is obviously an issue

uint256 expected = "revert overflow error";

and also the errorsEqual method of the assert library is expecting two error codes

Anyway one way of going around this would be trying to make a raw call in order to test if there's a revert status inside the VM. The call method will return true in case the call has been executed correctly, false otherwise.

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");
  }
}

To get the actual value you need to invoke again the method since the raw call won't give you the return value (see the second test method).

output

  TestSafeMath
    ✓ testAdd_10_and_max_should_return_err (53ms)
    ✓ testAdd_10_and_10_should_be_ok (66ms)


  2 passing (987ms)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.