将每个 pytest 测试函数包装到 try- except 中

use*_*030 1 python testing pytest

我想将每个测试函数包装到 try- except 块中以执行 except 块中的代码。仅当测试失败时才应执行此代码。

我想在不改变测试功能的情况下实现这一点,而是使用某种装饰器/夹具。不幸的是我找不到任何例子。

我想要实现的目标的示例:

def test_1():
    some_method_that_might_throw_an_exception()
Run Code Online (Sandbox Code Playgroud)

run_only_if_exception_was_thrown()我有多个测试,如果测试抛出异常,所有测试都应该运行一个函数。我想在测试中不使用 try/catch 块来实现这一点。

我当前的方法是在固定装置内部使用来sys.last_value检查是否引发异常:

@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()
Run Code Online (Sandbox Code Playgroud)

the*_*rge 5

这个怎么样:

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
Run Code Online (Sandbox Code Playgroud)

然后在你的测试套件中:

...
@test_dec
def test_one(fix):
    # test code
Run Code Online (Sandbox Code Playgroud)