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.

相关推荐
2401_871492855 分钟前
如何在 React Router v6 中正确配置多路由组件显示
jvm·数据库·python
神仙别闹1 小时前
基于Python(Django)+MySQL 实现(Web)SQL智能检测系统的设计与实现
python·mysql·django
甄心爱学习1 小时前
【项目实训】法律文书智能摘要系统4
python·github·个人开发
huzhongqiang1 小时前
Playwright理解与封装
python
zhangchaoxies2 小时前
MySQL触发器能否监控特定用户操作_结合审计功能实现分析
jvm·数据库·python
qq_413502022 小时前
如何解决ORA-12518监听程序无法分配进程_内存耗尽与PGA溢出
jvm·数据库·python
zhangrelay2 小时前
三分钟云课实践速通--大学物理--python 版
linux·开发语言·python·学习·ubuntu·lubuntu
djjdjdjdjjdj2 小时前
如何用参数解构在函数入口处直接提取对象属性
jvm·数据库·python
forEverPlume3 小时前
mysql如何批量增加表的字段_脚本化DDL操作实践
jvm·数据库·python
asdzx673 小时前
使用 Python 读取 PDF: 提取文本和图片
开发语言·python·pdf