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

Using python unittest, how can I assert an error reported gave a certain message?

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

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。然后你可以使用匹配异常断言 instances:

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

您可以使用 assertRaises 作为上下文管理器并断言异常对象的字符串值符合预期:

def my_function():
    raise RuntimeError('hello')

class MyTestCase(unittest.TestCase):
    def test_my_function(self):
        with self.assertRaises(RuntimeError) as cm:
            my_function()
        self.assertEqual(str(cm.exception), 'hello')

演示:http://ideone.com/7J0HOR