欢迎访问宙启技术站
智能推送

pytest中对异常处理的 实践

发布时间:2024-01-05 17:50:46

在pytest中对异常处理的 实践是使用pytest的内置装饰器pytest.raises来捕获并验证发生的异常。以下是一个使用例子:

import pytest

def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return a / b

def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError) as e:
        divide(10, 0)
    assert str(e.value) == "Cannot divide by zero"

def test_divide_valid():
    result = divide(10, 2)
    assert result == 5

在上面的例子中,我们定义了一个divide函数来执行两个数字的除法运算。如果除数b为0,则会抛出一个ZeroDivisionError异常。

test_divide_by_zero函数中,我们使用pytest.raises装饰器来捕获ZeroDivisionError异常,并使用as关键字将其赋给变量e。我们可以使用e.value来访问捕获的异常实例,这允许我们进行进一步的验证。在此示例中,我们将异常的字符串表示与预期进行了比较。

test_divide_valid函数中,我们测试了一个有效的除法操作,即10除以2等于5。我们可以直接断言结果是否等于预期值。

使用pytest.raises装饰器可以捕获多种不同类型的异常。以下是一个稍微复杂的例子:

class MyCustomException(Exception):
    pass

def complex_operation(a, b):
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    if b == 1:
        raise MyCustomException("Custom exception")
    return a / b

def test_complex_operation():
    with pytest.raises(Exception) as e:
        complex_operation(10, 0)
    assert str(e.value) == "Cannot divide by zero"

    with pytest.raises(MyCustomException) as e:
        complex_operation(10, 1)
    assert str(e.value) == "Custom exception"

    result = complex_operation(10, 2)
    assert result == 5

在上面的例子中,我们定义了一个complex_operation函数,它会根据不同的情况抛出不同类型的异常。在test_complex_operation函数中,我们使用pytest.raises来捕获ExceptionMyCustomException两种异常,并验证它们的字符串表示。

总结一下,pytest中对异常处理的 实践是使用pytest.raises装饰器来捕获并验证预期的异常。这种做法可以帮助我们编写更可靠和稳定的测试代码。