日々精進

新しく学んだことを書き留めていきます

pytestでraiseされた例外をテストする

例外が発生するケースのテストをしたい場合は以下のように with pytest.raises を使う。

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

        def f():
            f()

        f()
    assert "maximum recursion" in str(excinfo.value)

as excinfoを使うとちゃんと例外の中身もassertできるし、いいね!

参考:

docs.pytest.org