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.

相关推荐
明月_清风2 小时前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风2 小时前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly16 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling21 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook1 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风1 天前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风1 天前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei2 天前
python 抽象基类
python
用户8356290780512 天前
Python 实现 PPT 转 HTML
后端·python
zone77392 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试