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

Dip*_*iya 3 python python-3.x python-unittest

请检查以下代码:

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()
Run Code Online (Sandbox Code Playgroud)

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

我缺少什么?我已经检查过:assertRaises(exception, *, msg=None)

Dip*_*iya 8

我会回答我自己的问题。


我误解了 的用法msg。来自Python的官方文档

所有的断言方法都接受一个 msg 参数,如果指定的话,将用作失败时的错误消息。

它用于调试目的。

例如

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()
Run Code Online (Sandbox Code Playgroud)

在输出中我们将得到:

AssertionError:未引发 KeyError:错误消息

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()
Run Code Online (Sandbox Code Playgroud)