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.

相关推荐
VidDown2 小时前
24fps 转 25fps 不只是改个数字:帧率转换、PAL/NTSC 与音频补偿
python·网络协议·音视频·视频编解码·视频
死磕音视频4 小时前
让小模型做选择题:限定候选项并读取 logits 概率的入门实践(附 Python 代码)
开发语言·python·大模型·文本分类·transformers
凤山老林5 小时前
Spring Boot 接入国密 SM2/SM3/SM4 的一些实践记录
spring boot·后端·python
pride.li6 小时前
第03章 Python 教程-基础语法:注释与变量
服务器·前端·后端·python·算法·计算机视觉
databook6 小时前
用 Pydantic AI 从零搭建一个能干活的 AI Agent
人工智能·python
康小旺7 小时前
把 markitdown 做成 Windows 桌面版:拖进文档就出 Markdown,附 233MB→64MB 打包裁剪全过程
python
启观川7 小时前
数据结构与算法-第 3 章 常用算法-贪心算法
数据结构·笔记·python·算法·贪心算法
南笙北梦8 小时前
本地开源大模型多轮对话显存泄漏排查与修复实录
python
小羊没烦恼!8 小时前
如何在IIS6,7中部署ASP.NET网站?
数据库·后端·python·web安全·asp.net
钱栈up8 小时前
扫完 3.5 万文件后,我发现了 521 组散落的同名文件
爬虫·python·数据分析