How to assert expected exceptions in pytest

To assert expected exceptions in pytest, you can use the pytest.raises context manager. Here's an example:

python 复制代码
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 exc_info:
        divide(10, 0)
    assert str(exc_info.value) == "Cannot divide by zero"

In this example, we have a function divide that performs division. If the divisor b is zero, it raises a ZeroDivisionError with a custom error message.

In the test_divide_by_zero test function, we use the pytest.raises context manager to assert that a specific exception is raised. Inside the context manager, we call the divide function with arguments that would result in a division by zero. If the expected exception is raised, the context manager captures the exception information. We can then access the exception using exc_info.value and assert its properties, such as the error message.

Note that the pytest.raises context manager will pass the test if the expected exception is raised. If the exception is not raised or a different exception is raised, the test will fail.

Make sure to replace ZeroDivisionError with the actual exception you expect to be raised, and adjust the assertion as needed for your specific case.

See https://docs.pytest.org/en/7.1.x/how-to/assert.html#assertions-about-expected-exceptions for more details.

相关推荐
呆萌很4 分钟前
python 项目迁移
python
清水白石00810 分钟前
《requests vs httpx:Python 网络请求库的全面对比与实战指南》
网络·python·httpx
MediaTea27 分钟前
大学 Python 编程基础(合集)
开发语言·python
Nautiluss31 分钟前
一起玩XVF3800麦克风阵列(十)
linux·人工智能·python·音频·语音识别·实时音视频·dsp开发
BoBoZz1934 分钟前
MultiBlockDataSet 复合感知与非复合感知
python·vtk·图形渲染·图形处理
兔子小灰灰1 小时前
jetson安装pytorch
人工智能·pytorch·python
Swizard2 小时前
拒绝“裸奔”上线:FastAPI + Pytest 自动化测试实战指南
python
Ven%3 小时前
从单轮问答到连贯对话:RAG多轮对话技术详解
人工智能·python·深度学习·神经网络·算法
谈笑也风生3 小时前
经典算法题型之复数乘法(二)
开发语言·python·算法
先知后行。4 小时前
python的类
开发语言·python