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

标签 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()

如评论中所述,我预计此测试会失败,因为我正在检查的消息 (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()

关于python - self.assertRaises 作为上下文管理器,msg 参数未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58687475/

相关文章:

python - 如何: setting a testsuite in python

python - 总结二维数组以找到灰度强度

Python 在 Excel 中打开写入 CSV

python - unittest,在本地工作,但不在远程服务器上,没有名为 x.__main__ 的模块; 'x'是一个包,不能直接执行

python - snapshot.wait_until_completed 不显示进度也不显示完成时间

python-3.x - 我想使用命令提示符安装 cv2

python - 如何为所有unittest.TestCase类执行tearDown和setUp方法

python - Mincemeat.py - 文件的数据源划分

python - 使用用户在 Python 中插入的文件运行 Linux shell 脚本

python - matplotlib 使用列表更改线段上的线宽