I want to wrap each of my test functions into a try-except block to execute code in the except block. This code should only be executed if the test is failing.
I want to achieve this without altering the test functions, but instead use some kind of decorator/fixture. Unfortunately I can not find any examples.
Example of what I'm trying to achieve:
def test_1():
some_method_that_might_throw_an_exception()
I have multiple tests and all of them should run a function run_only_if_exception_was_thrown()
if an exception was thrown by the test.
I want to achieve this without using a try/catch block inside the tests.
My current approach is to use sys.last_value
inside a fixture to check if an exception was thrown:
@pytest.fixture
def fix():
yield X()
try:
if sys.last_value:
# error
except AttributeError:
# no error thrown
def test1(fix):
some_method_that_might_throw_an_exception()