What is the best way to append custom message to the output when pytest.raises fails?

Stack Overflow Asked by Roman Ponomaryov on December 26, 2020

What I’m aiming at is – if I ran the following test:

def test_func():
    with pytest.raises(APIError):

and the func() did not raise APIError – I want to get custom message to the output, e.g. "No APIError caught"

Pytest had a feature specifically for this:

with raises(SomeError, message="Custom message here"):
but for some reason it didn’t make it to further versions (current is 6.0.2)

One Answer

You can replicate this behavior using the function after the function you expect to raise an exception, since that will only run if an exception is not raised. The deprecation notice explains the reasoning for its removal, and offers this alternate approach:

import pytest

def func():

def test_func():
    with pytest.raises(ValueError):
        func()"Oh no!")
$ pytest

collected 1 item F                                                                                                                                                                                                   [100%]

==================================================================================================== FAILURES =====================================================================================================
____________________________________________________________________________________________________ test_func ____________________________________________________________________________________________________

    def test_func():
        with pytest.raises(ValueError):
> "Oh no!")
E           Failed: Oh no! Failed
============================================================================================= short test summary info =============================================================================================
FAILED - Failed: Oh no!
================================================================================================ 1 failed in 0.16s ================================================================================================

Correct answer by mattficke on December 26, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP