pytest参数化测试中捕获到不是预期的异常

125 阅读1分钟

如果在 pytest 参数化测试中捕获到不是预期的异常,可以使用 pytest.fail() 函数来使测试失败,并提供详细的错误信息。以下是几种实现方式:

1. 使用 pytest.fail()

在异常处理块中调用 pytest.fail(),并提供详细的信息:

import pytest

def divide(a, b):
    return a / b

@pytest.mark.parametrize("input1, input2", [
    (10, 2),
    (5, 0),  # 这里会引发异常
    (5, "a")  # 这里会引发 TypeError
])
def test_divide(input1, input2):
    try:
        result = divide(input1, input2)
        assert result == input1 / input2
    except ZeroDivisionError:
        assert input2 == 0  # 预期异常
    except Exception as e:
        pytest.fail(f"Unexpected exception {e} raised for input: {input1}, {input2}")

2. 通过 pytest.raises 检查异常类型

如果你只想捕获特定的异常并让其他异常失败,可以使用 pytest.raises

@pytest.mark.parametrize("input1, input2", [
    (10, 2),
    (5, 0),  # 这里会引发异常
    (5, "a")  # 这里会引发 TypeError
])
def test_divide(input1, input2):
    if input2 == 0:
        with pytest.raises(ZeroDivisionError):
            divide(input1, input2)
    else:
        try:
            result = divide(input1, input2)
            assert result == input1 / input2
        except Exception as e:
            pytest.fail(f"Unexpected exception {e} raised for input: {input1}, {input2}")

3. 自定义异常处理

在自定义异常处理逻辑中,使用 pytest.fail() 提供上下文信息:

@pytest.mark.parametrize("input1, input2", [
    (10, 2),
    (5, 0),
    (5, "a")
])
def test_divide(input1, input2):
    try:
        result = divide(input1, input2)
        assert result == input1 / input2
    except ZeroDivisionError:
        assert input2 == 0  # 预期异常
    except TypeError as e:
        pytest.fail(f"TypeError: {e} for inputs: {input1}, {input2}")
    except Exception as e:
        pytest.fail(f"Unexpected exception {e} for inputs: {input1}, {input2}")

总结

通过这些方法,你可以确保在测试中捕获到非预期的异常时,测试会失败并输出详细的错误信息。这有助于快速定位问题并提高测试的可靠性。