python - 如何使用 Python pytest 测试导入函数的异常?
问题描述
如何使用 pytest 测试导入函数的异常?例如,在 main file.py 我有:
def function():
if 3 != 3:
raise Exception("Error")
在 testfile.py 我有:
import sys
import os
sys.path.insert(0, '..//main/')
import file
def test_exception():
file.function()
# need to test exception here
解决方案
你可以pytest.raises
这样使用:
def test_exception():
with pytest.raises(SomeExceptionClass) as e:
file.function()
assert "Some informative error message" in str(e.value)
SomeExceptionClass
您期望发生的具体错误在哪里。如果函数没有引发错误(或者如果它引发不同的错误类型),这将引发断言错误。
推荐阅读
- javascript - 如何将网站链接到(Excel)数据库并基于该范围构建下拉菜单?
- postgresql - PostgreSQL 10.5 中的 EF core 2 迁移脚本错误
- angular6 - 当用户单击 Angular 6 中的提交时,我必须发送多个文件。我正在使用表单数据将数据发送到 API
- node.js - 带有多个参数的 React + Node 获取请求将不起作用
- python - TypeError: playerMovement() 接受 1 个位置参数,但给出了 2 个
- reporting-services - Reporting Services 文本输出和预览结果不一致
- python-3.x - Mypy + flake8:有什么方法可以抑制`F821 undefined name`的警告
- c# - 即使调用了 beforesendrequest 方法,也强制使用 mustunderstand = 1 的 SOAP 标头
- python-3.x - Pytorch - 批次不更新
- javascript - JQuery:限制拖放元素的范围