Skip to content

Instantly share code, notes, and snippets.

@simondlr
Created November 30, 2016 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simondlr/cd13348d0f578e2f5cd49cb7f5501801 to your computer and use it in GitHub Desktop.
Save simondlr/cd13348d0f578e2f5cd49cb7f5501801 to your computer and use it in GitHub Desktop.
Testing throws in Solidity
pragma solidity ^0.4.4;
/*
This is for testing if a transaction would throw.
Contract calls rethrow when it encounters errors.
Raw calls do not.
You wrap your contract you want to test in a ThrowProxy.
You prime it by calling the fallback function.
Then executing it.
False will be returned if it threw.
True will be return it it did not throw or OOG.
*/
contract ThrowProxy {
address public target;
bytes data;
function ThrowProxy(address _target) {
target = _target;
}
//prime the data using the fallback function.
function() {
data = msg.data;
}
function execute() returns (bool) {
return target.call(data);
}
}
contract Something {
function doThrow() {
throw;
}
function doNoThrow() {
//
}
}
contract TestSomething {
function testThrow() returns (bool) {
Something s = new Something();
ThrowProxy t = new ThrowProxy(address(s));
//prime the proxy.
Something(address(t)).doThrow();
//execute the call that is supposed to throw.
bool r = t.execute(); //r will be false if it threw. r will be true if it didn't.
//do assert here.
return r;
}
}
@simondlr
Copy link
Author

simondlr commented Dec 7, 2016

address(t).call(bytes4(bytes32(sha3("doThrow()"))));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment