python - 将每个 pytest 测试函数包装成 try-except

标签 python testing pytest

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

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

我正在努力实现的示例:

def test_1():
    some_method_that_might_throw_an_exception()

我有多个测试,如果测试抛出异常,所有测试都应该运行函数 run_only_if_exception_was_thrown()。 我想在不在测试中使用 try/catch block 的情况下实现这一目标。

我目前的方法是在 fixture 中使用 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()

最佳答案

这个怎么样:

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

然后在你的测试套件中:

...
@test_dec
def test_one(fix):
    # test code

关于python - 将每个 pytest 测试函数包装成 try-except,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43937748/

相关文章:

iphone - 我的应用程序在 iOS 5 中遇到了严重的性能问题,有人可以帮我理解这个来自仪器的速度测试日志吗?

python - 如何使用 pytest 将 fixture 中的对象共享到所有测试?

python - 无法改变派生类的默认参数列表

python - Web3py send_raw_transaction ValueError : {'message' : 'invalid remainder' , 'code' : -32000}

ruby - Minitest 警告 : DEPRECATED global use of must_match. 使用 `_(obj)`

testing - 测试所需的证书和配置文件

在 Pytest 上找不到 Python 包

python - 如何为 py.test 创建一个扩展的 xfail 标记?

python - 如何使用urllib2打开 'infinite' jpg?

python - 在不同数组的一定范围内的元素中从一个数组中查找元素