6

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");        
    }
}
4
  • Same question is already asked for Truffle also here, and this one does have an answer. Does it help? Commented Jun 14, 2020 at 4:00
  • Sorry I did not see the other answer an updated my question based on that.
    – alper
    Commented Jun 14, 2020 at 9:34
  • NP, feel free to edit the answer and change deployed in the 3rd line to invoked :) Commented Jun 14, 2020 at 9:48
  • Done, I also mark duplicated for the question I linked before to your answer.
    – alper
    Commented Jun 14, 2020 at 9:54

1 Answer 1

7

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.

4
  • Does it also catch if the transaction is reverted because of out of gas issue?
    – alper
    Commented Jun 14, 2020 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
    Commented Jun 14, 2020 at 9:31
  • 1
    @alper I've answered your second question here - ethereum.stackexchange.com/questions/84259/… Commented Jun 14, 2020 at 10:00
  • For out of gas, the error string will be "out of gas" Commented Jun 14, 2020 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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