5

I am using Brownie to develop my smart contracts, which helps me to intract with the smart contracts, please see doc.

When my call Example.greet() is there any way to return the error message and act based on it during my tests? Also find out is it reverted because the transaction is out of gas or not.

Similar question is answered for Truffle: [how to catch “revert” error in truffle test javascript?].


Example of a simple contract with a revert() message:

contract Example{
    function greet(){
        revert("Hello World");        
    }
}
  • Same question is already asked for Truffle also here, and this one does have an answer. Does it help? – goodvibration Jun 14 at 4:00
  • Sorry I did not see the other answer an updated my question based on that. – alper Jun 14 at 9:34
  • NP, feel free to edit the answer and change deployed in the 3rd line to invoked :) – goodvibration Jun 14 at 9:48
  • Done, I also mark duplicated for the question I linked before to your answer. – alper Jun 14 at 9:54
  • Thanks!!!!!!!!! – goodvibration Jun 14 at 10:06
5

The brownie.reverts context manager handles exactly this use case. The syntax is very similar to pytest.raises:

import brownie

def test_greet(example):
    with brownie.reverts("Hello World"):
         example.greet()

Including the error string is optional, if you omit it you can catch any revert regardless of the message returned.

| improve this answer | |
  • Does it also catch if the transaction is reverted because of out of gas issue? – alper Jun 14 at 8:37
  • Also if my revert() function is without a message but commented next to it to save some gas like: revert(); // dev: Hello World, can it also catch the error message (even it is commented out)? – alper Jun 14 at 9:31
  • 1
    @alper I've answered your second question here - ethereum.stackexchange.com/questions/84259/… – iamdefinitelyahuman Jun 14 at 10:00
  • For out of gas, the error string will be "out of gas" – iamdefinitelyahuman Jun 14 at 10:01

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.