Search code examples
pythontry-catchpytesttry-except

How to test the exception of try/except block using pytest


How can I properly test if the correct code has executed once an exception has been triggered in a try/except block?

import pytest


def my_func(string):
    try:
        assert string == "pass"
        print("String is `pass`")
    except AssertionError:
        print("String is not 'pass'")



def test_my_func():
    with pytest.raises(AssertionError) as exc_info:
        my_func("fail")

    assert str(exc_info.value) == "String is not 'pass'"

Clearly, this test fails with Failed: DID NOT RAISE <class 'AssertionError'> as I caught the error in the try/except block. But how can/should I test if the correct phrase has been printed? This could especially be useful if you have more than one possible except block.


Solution

  • You can use the capsys fixture to capture standard output and then make assertions with it:

    def my_func(string):
        try:
            assert string == "pass"
            print("String is `pass`")
        except AssertionError:
            print("String is not 'pass'")
    
    
    
    def test_my_func(capsys):
        my_func("fail")
        captured = capsys.readouterr()
        assert captured.out == "String is not 'pass'\n"