我有一个测试,我使用
pytest_check
进行一些软断言。即使断言失败,测试也会继续运行,并最终失败并抛出断言错误。
现在在魅力报告中,我观察到当存在
KeyError
/TypeError
时,测试显示为损坏。当 AssertionError
发生时,测试显示为失败。
我想处理这些软断言并提出
KeyError
,而不是在魅力报告中将它们显示为已损坏。我怎样才能实现它?
这样做的原因是, 我想将损坏的测试分类为仍然完成步骤流程但数学计算中存在小问题的测试。 而失败的测试是无法继续进行下一步的测试,例如,因为可以进行计算的服务不可用。
这是对的吗?有更好的方法吗?
我可以使用 try except 块来处理
AssertionError
并引发 KeyError
,但它仍然在报告中显示为断言错误。由于软断言需要位于不同的位置,所以我不能使用 try except,因为当我这样做时,测试会在第一个 except 块处停止。
import pytest
from pytest_check import check
def test_custom_assertions():
x = 25
y = 21
a = check.equal(x, 23, "x is not equal to 23") # False
b = check.greater(y, 20, "y is not greater than 20") # True
c = check.is_in(30, [10, 20, 25], "30 is not in the list") # False
if False in [a,b,c]:
raise KeyError("Test is broken")
这就是我的代码的报告的样子 错误报告
您可能需要使用软断言:我使用的一个很好的库是assertpy。使用这种方法,您不需要根据不同的错误类型来处理错误。此外,我们可以让测试知道我们希望使用 soft_assertions() 块完成所有断言验证之前的执行。这是来自 Github 存储库的示例:
from assertpy import assert_that, soft_assertions
with soft_assertions():
assert_that('foo').is_length(4)
assert_that('foo').is_empty()
assert_that('foo').is_false()
assert_that('foo').is_digit()
assert_that('123').is_alpha()
assert_that('foo').is_upper()
assert_that('FOO').is_lower()
assert_that('foo').is_equal_to('bar')
assert_that('foo').is_not_equal_to('foo')
assert_that('foo').is_equal_to_ignoring_case('BAR')