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.

相关推荐
white-persist1 小时前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
Java 码农1 小时前
Centos7 maven 安装
java·python·centos·maven
倔强青铜三2 小时前
苦练Python第63天:零基础玩转TOML配置读写,tomllib模块实战
人工智能·python·面试
浔川python社2 小时前
《网络爬虫技术规范与应用指南系列》(xc—3):合规实操与场景落地
python
B站计算机毕业设计之家2 小时前
智慧交通项目:Python+YOLOv8 实时交通标志系统 深度学习实战(TT100K+PySide6 源码+文档)✅
人工智能·python·深度学习·yolo·计算机视觉·智慧交通·交通标志
IT森林里的程序猿3 小时前
基于机器学习方法的网球比赛胜负趋势预测
python·机器学习·django
正牌强哥3 小时前
Futures_ML——机器学习在期货量化交易中的应用与实践
人工智能·python·机器学习·ai·交易·akshare
倔强青铜三3 小时前
苦练Python第62天:零基础玩转CSV文件读写,csv模块实战
人工智能·python·面试
郝学胜-神的一滴3 小时前
Effective Python 第43条:自定义容器类型为什么应该从 `collections.abc` 继承?
开发语言·python
银行数字化转型导师坚鹏4 小时前
如何设计优秀的企业微信私域运营实战培训方案
大数据·python·企业微信