Asserting that a certain error occurs

121 views Asked by At

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?

2

There are 2 answers

1
elethan On BEST ANSWER

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')
0
oliversm On

Throwing assertions is likely a better approach. As an example:

def fun(param):
    if param == 'a':
        raise AssertionError('Param is equal to \'a\'.')
    else:
        return None

try:
    fun('b')
    print('Equalling \'b\' worked fine.')
    fun('a')
    print('This line is not printed...')
except AssertionError as err:
    print('An assertion error has been raised:')
    print(err)

gives:

Equalling 'b' worked fine.
An assertion error has been raised:
Param is equal to 'a'.