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.

相关推荐
Desire.9842 分钟前
Python 数学建模——灰色关联度分析
python·数学建模·灰色关联度
小鹿( ﹡ˆoˆ﹡ )20 分钟前
Python中的树与图:构建复杂数据结构的艺术
开发语言·python
阡之尘埃25 分钟前
Python数据分析案例59——基于图神经网络的反欺诈交易检测(GCN,GAT,GIN)
python·神经网络·数据挖掘·数据分析·图神经网络·反欺诈·风控大数据
xiaojiesec30 分钟前
第157天: 安全开发-Python 自动化挖掘项目&SRC 目标&FOFA 资产&Web 爬虫解析库
python·安全
27划流星雨_34 分钟前
from tqdm.auto import tqdm用法详细介绍
python
爱里承欢。39 分钟前
【Python语言初识(二)】
python
hzw05101 小时前
Jupyter的使用
ide·python·jupyter
憨憨小白2 小时前
函数的高级应用
开发语言·python·青少年编程·少儿编程
CV-King2 小时前
计算机视觉硬件知识点整理(三):镜头
图像处理·人工智能·python·opencv·计算机视觉
惟长堤一痕2 小时前
医学数据分析实训 项目三 关联规则分析作业--在线购物车分析--痹症方剂用药规律分析
python·数据分析