问题
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()
回答1:
How about this:
def test_dec(test_func):
def test_wrapper(fix):
try:
test_func(fix)
except:
run_only_if_exception_was_thrown(fix)
# re-raise exception to make the test fail
raise
return test_wrapper
Then in your test suite:
...
@test_dec
def test_one(fix):
# test code
来源:https://stackoverflow.com/questions/43937748/wrap-each-pytest-test-function-into-try-except