gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:11:54 39 4
gpt4 key购买 nike

请检查以下代码:

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/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com