Wrap each pytest test function into try-except

落爺英雄遲暮 提交于 2019-12-11 05:59:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!