3 - Asssertions#

assert can be used to check whether a function returns a specific value. If the assertion fails, we see the return value of the function call.

You can also include a message to print if the assert fails:

def is_even(x: int) -> bool:
    """Note, this actually returns the opposite of what we want"""
    return x % 2 == 1

def test_is_even():
    assert f(4) == True, "value was odd, should be even"
!pytest -q test_sample.py::test_is_even
F                                                                        [100%]
================================== FAILURES ===================================
________________________________ test_is_even _________________________________

    def test_is_even():
>       assert is_even(4) == True, "value was odd, should be even"
E       AssertionError: value was odd, should be even
E       assert False == True
E        +  where False = is_even(4)

test_sample.py:15: AssertionError
=========================== short test summary info ===========================
FAILED test_sample.py::test_is_even - AssertionError: value was odd, should be even
1 failed in 0.07s
!pytest -q test_sample.py::test_is_actually_even
.                                                                        [100%]
1 passed in 0.01s

Assertions about expected exceptions#

We use pytest.raises() to detect exceptions that we expect to throw:

import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0
!pytest -q test_sample.py::test_zero_division
.                                                                        [100%]
1 passed in 0.01s

You can also access actual exception info:

def test_recursion_depth():
    with pytest.raises(RuntimeError) as excinfo:

        def f():
            f()

        f()
    assert "maximum recursion" in str(excinfo.value)
!pytest -q test_sample.py::test_recursion_depth
.                                                                        [100%]
1 passed in 0.01s

Assertions about expected exception groups#

When expecting a BaseExceptionGroup or ExceptionGroup you can use pytest.RaisesGroup:

def test_exception_in_group():
    with pytest.RaisesGroup(ValueError):
        raise ExceptionGroup("group msg", [ValueError("value msg")])
    with pytest.RaisesGroup(ValueError, TypeError):
        raise ExceptionGroup("msg", [ValueError("foo"), TypeError("bar")])