Search code examples
pythontestingtry-catchthrowassertion

Asserting that a certain error occurs


Given the following code:

def fun(param):
    if param == 'a':
        assert False
    else:
        return None

# fun('a') THIS THROWS AN AssertionError
# PSEUDOCODE FOR WHAT I WANT TO DO:
# assert (fun('a') throws an AssertionError)
assert fun('b') == None

How do I assert that the first function call (fun('a')) will give me an AssertionError? Will I need a try-catch for this or is there a more elegant way?


Solution

  • You can use pytest for this:

    import pytest
    ...
    with pytest.raises(AssertionError):
        fun('a')
    

    This will raise an error if fun('a') does not raise an AssertionError.

    Or, if you are using unittest, and you are within a TestCase, you can use assert Raises:

    self.assertRaises(AssertionError, fun, 'a')
    

    Also, as other answers have mentioned, you would be better off raiseing an error than asserting False. And if you do raise an error, you could raise one that tells the user more about what went wrong, or raise your own custom exception:

    import pytest
    
    class AError(Exception):
        pass
    
    def fun(param):
        if param == 'a':
            raise AError("You passed 'a'; don't do that!")
        else:
            return None
    
    with pytest.raises(AError):
        fun('a')