1

I'm trying to add some unit tests to make sure that the correct Error is being thrown (my function either throws KeyError or RuntimeError).

I've tried assert func(bad_param) == KeyError and assert isinstance(func(bad_param), KeyError) but neither of these are correct, how am I supposed to write unit tests for this / what's the correct way to assert that this function, when passed a bad parameter, will raise the correct Exception?

EDIT: I'm NOT using the unittest library, I'm asking about purely the assert function that comes with Python std lib (https://docs.python.org/3/reference/simple_stmts.html)

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
omgirok
  • 178
  • 2
  • 11
  • 1
    Does this answer your question? [How do you test that a Python function throws an exception?](https://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception) – maciek97x Jun 24 '20 at 22:22
  • @maciek97x sorry I should've clarified that I'm not using the unittest library – omgirok Jun 24 '20 at 22:27
  • Reopening because the linked question was not specific to *pytest*. – Jonathon Reinhart Jun 24 '20 at 22:32

4 Answers4

3

You can use the pytest.raises context manager:

with pytest.raises(ExpectedErrorType):
    unit_under_test()

See pytest docs for more details.

I haven't found any example in the docs that would explain how to expect multiple exception types, but you can do that manually by inspecting the exception info object:

with pytest.raises(Exception) as exc_info:
    unit_under_test()

assert issubclass(exc_info.type, (KeyError, RuntimeError))

# alternative more strict assertion
assert exc_info.type in (KeyError, RuntimeError)
plamut
  • 3,085
  • 10
  • 29
  • 40
3

I already done something like this and I used try ... except statement :

try:
    # Code to test
except KeyError:
    assert True
assert False

Here is a minimal working example (for pytest-like unitary test) :

def fun():
    raise KeyError

def test():
    try:
        fun()
    except KeyError:
        assert True
        return
    assert False
lavalade
  • 329
  • 2
  • 11
0

You can use try except to catch exception like

def foo():
    raise ValueError
    
rightExceptionRaised = False
try:
    foo()
except ValueError:
    rightExceptionRaised = True
except:
    pass

assert rightExceptionRaised
maciek97x
  • 2,251
  • 2
  • 10
  • 21
0

EDIT: Refer to post written by @plamut

I found an answer that might be more aligned with how pytest intended to check for it!

def foo():
    raise KeyError

def test_foo_error():
    with pytest.raise(KeyError)
        foo()
omgirok
  • 178
  • 2
  • 11