我想将我的每个测试函数包装到一个 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/