繁体   English   中英

如何使用 Python pytest 测试导入函数的异常?

[英]How to test exception from imported function using 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将是您期望发生的特定错误。 如果函数没有引发错误(或者如果它引发不同的错误类型),这将引发断言错误。

你可以这样做:

import sys
import os

def function():
  raise Exception("Error")




def test_exception():
  try:
    function()
  except Exception as e:
    print(e)

test_exception()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM