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 小时前
AI安全--AI大模型的毒性偏见与安全对齐实践
人工智能·python·深度学习
视觉小萌新5 小时前
AI Class 3 · Chapter 2-3:函数、异常、文件读写+JSON / JSONL 读写(小白版)
人工智能·python·json
小小张说故事6 小时前
Python 的 obj.x 到底按什么顺序找?拆开数据描述符、实例字典和 __getattr__ 那条优先级链
python
用户11481867894847 小时前
水印的实现方式逻辑
前端·python
贾公子7 小时前
从单条内容到账号维度——AIGC 风险评分的工程实现
后端·python
木头左9 小时前
【Python】不点浏览器发博客:逆向 CSDN 创作中心接口做 md-publish 技能
python·自动化·api
测试界的小码农9 小时前
【让 AI 生成的测试用例变成 pytest API 自动化脚本】
人工智能·测试用例·pytest
Tt有了t9 小时前
设计模式速查
java·python·设计模式
deepseek2310 小时前
Python日志拖慢请求?QueueHandler排队、丢失与退出实测
python·性能优化·logging·后端开发·queuehandler
用户912940468484210 小时前
Codex 从零到能交付(05):第一次改代码:生成一个文件清单脚本
python