首页 > 解决方案 > 如何使用 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

标签: pythonpython-3.x

解决方案


你可以pytest.raises这样使用:

def test_exception():
    with pytest.raises(SomeExceptionClass) as e:
        file.function()
    assert "Some informative error message" in str(e.value)

SomeExceptionClass您期望发生的具体错误在哪里。如果函数没有引发错误(或者如果它引发不同的错误类型),这将引发断言错误。


推荐阅读