简体   繁体   中英

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM