self.assertRaises 作为上下文管理器,msg 参数未按预期工作

self.assertRaises as a context manager with msg argument not working as expected

请检查以下代码:

import unittest


CORRECT_MESSAGE = 'Correct message'
WRONG_MESSAGE = 'Wrong message'


def fn():
    raise KeyError(CORRECT_MESSAGE)


class Test(unittest.TestCase):
    def test(self):
        # I am expecting this test to fail as the msg I am
        # checking is WRONG_MESSAGE, and not CORRECT_MESSAGE.
        with self.assertRaises(KeyError, msg=WRONG_MESSAGE):
            fn()


unittest.main()

如评论中所述,我预计此测试会失败,因为我正在检查的消息 (WRONG_MESSAGE) 不正确,但测试通过了。

我错过了什么?我检查过:assertRaises(exception, *, msg=None).

我会回答我自己的问题。


我误解了msg的用法。来自 Python's official documentation:

All the assert methods accept a msg argument that, if specified, is used as the error message on failure.

调试用

例如

import unittest


CORRECT_MESSAGE = 'Correct message'
WRONG_MESSAGE = 'Wrong message'


def fn():
    return
    # Don't raise an exception.
    # raise KeyError(CORRECT_MESSAGE)


class Test(unittest.TestCase):
    def test(self):
        with self.assertRaises(KeyError, msg=WRONG_MESSAGE):
            fn()


unittest.main()

在输出中我们将得到:

AssertionError: KeyError not raised : Wrong message

msg在未引发断言错误时使用


如果我们想检查异常消息,实际的解决方案是使用assertRaisesRegex

例如

import unittest


CORRECT_MESSAGE = 'Correct message'
WRONG_MESSAGE = 'Wrong message'


def fn():
    raise KeyError(CORRECT_MESSAGE)


class Test(unittest.TestCase):
    def test_will_pass(self):
        # This will check if the error message is CORRECT_MESSAGE.
        with self.assertRaisesRegex(KeyError, CORRECT_MESSAGE):
            fn()

    def test_will_fail(self):
        # This will check if the error message is WRONG_MESSAGE.
        with self.assertRaisesRegex(KeyError, WRONG_MESSAGE):
            fn()

unittest.main()