将每个 pytest 测试函数包装成 try-except [英] Wrap each pytest test function into try-except
问题描述
我想将我的每个测试函数都包装到一个 try-except 块中,以执行 except 块中的代码.仅当测试失败时才应执行此代码.
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()
我有多个测试,如果测试抛出异常,所有测试都应该运行一个函数run_only_if_exception_was_thrown()
.我想在不使用测试中的 try/catch 块的情况下实现这一点.
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.
我目前的方法是在夹具内使用 sys.last_value
来检查是否抛出异常:
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()
推荐答案
这个怎么样:
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
这篇关于将每个 pytest 测试函数包装成 try-except的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!