python - 使用 python unittest,我如何断言报告的错误给出了特定消息?

标签 python python-unittest

假设我有一个如下所示的方法:

def my_function(arg1, arg2):
    if arg1:
        raise RuntimeError('error message A')
    else:
        raise RuntimeError('error message B')

使用 python 的内置 unittets 库,有什么方法可以判断引发了哪个 RuntimeError?我一直在做:

import unittest
from myfile import my_function


class MyTestCase(unittest.TestCase):
    def test_my_function(self):
        self.assertRaises(RuntimeError, my_function, arg1, arg2)

但这只是断言遇到了 RuntimeError。我想知道遇到了哪个 RuntimeError。检查实际的错误消息是我认为可以完成的唯一方法,但我似乎找不到任何也尝试断言错误消息的断言方法

最佳答案

单元测试用户:

在这种情况下,最好使用assertRaisesRegex .

Like assertRaises() but also tests that regex matches on the string representation of the raised exception. regex may be a regular expression object or a string containing a regular expression suitable for use by re.search().

所以,你可以使用:

self.assertRaisesRegex(RuntimeError, "^error message A$", my_function, arg1, arg2)

pytest 用户:

安装我的插件 pytest-raisin .然后你可以使用匹配的异常实例断言:

with pytest.raises(RuntimeError("error message A")):
    my_function(arg1, arg2)

关于python - 使用 python unittest,我如何断言报告的错误给出了特定消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58085998/

相关文章:

Python - 如何断言未使用特定参数调用模拟对象?

Python:如何从unittest模块访问测试结果变量

python-3.x - 为什么模拟 'open' 并返回 FileNotFoundError 引发 AttributeError : __exit__?

Python:使用列表和数据框进行精确单词匹配

python - 如何使用 Python 将特定的选定行拆分为多行

python - 如何剪切部分文本并用 Python 和 RegEx 替换每一行

python - 使用 Pandas 计算重叠时间范围的持续时间

python - Writelines (python) 清除它应该写入的文本文件,并且不写入任何内容

python - 在方法中模拟一个对象,该对象不是Python中的参数

python - 模拟补丁以错误的顺序出现?