How do you test that a Python function throws an exception?

You can use the pytest.raises function to test that a Python function throws an exception. Here is an example code snippet:

import pytest

def test_example():
    def some_function():
        raise ValueError("This is an example exception.")

    with pytest.raises(ValueError):
        some_function()

In the above example, the some_function is expected to raise a ValueError exception, and the pytest.raises function is used to check that this exception is indeed raised when the some_function is called. If the some_function does not raise a ValueError, the test will fail.

Watch a course Python - The Practical Guide

Additionally you could use assert statement with context manager to check exception like this:

def test_example():
    def some_function():
        raise ValueError("This is an example exception.")
    try:
        some_function()
    except ValueError as e:
        assert str(e)=="This is an example exception."

You could also test for the exception message using this assert statement.