请检查以下代码:
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
) 不正确,但测试通过。
我缺少什么?我检查过:断言Raises(异常,*,msg=无) https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises.
我会回答我自己的问题。
我误解了它的用法msg
. From Python 的官方文档 https://docs.python.org/3/library/unittest.html#unittest.TestCase.debug:
所有断言方法都接受 msg 参数,如果指定,则将其用作失败时的错误消息。
它用于调试目的。
e.g.
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:错误消息
msg
当未引发断言错误时使用。
实际的解决方案是使用断言引发正则表达式 https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaisesRegex如果我们想检查异常消息。
e.g.
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)