如何检查特定于我的案例的pytest中引发的自定义异常



我正在尝试一个简单的函数,测试用例是检查提升条件是否工作。在引发自定义异常时,会给出消息。文件名为converter.py.

我正在使用Pytest框架并对其进行测试。我想检查是否出现错误并通过测试。

def convert_file(list_files):
if type(list_files) is list:
do some operations
else:
raise Exception("The file type is not a list")
return True`

测试函数为此编写:

def test_convert_file_difference():
result = converter.convert_file('1.xlxs')

assert pytest.raises("The file type is not a list") == result

但是我得到以下错误

=========================== short test summary info ============================
ERROR test_converter.py - Exception: The file type is not a list
=============================== 1 error in 0.07s ===============================
Assertion failed

我尝试了以下方法,但测试用例仍然失败。

def test_convert_file_difference():
with pytest.raises(Exception) as exc:
converter.convert_file('1.xlxs')
assert "The file type is not a list" in str(exc.value)

我是Pytest的新手。有人能给出正确的具体代码吗。我想在测试条件中检查是否发生了自定义错误,我想通过测试。怎么做?

使用下面的代码片段来传递这个场景,这样我们就可以检查捕获的异常

class TestFunction(unittest.TestCase):
def test_convert_file(self):
with pytest.raises(Exception) as e:
result = convert_file({})
self.assertEqual(str(e.value), "The file type is not a list")

在这里,我刚刚向函数传递了一个字典,以确保它进入异常。希望这对你有帮助。

最新更新