当测试没有抛出预期的异常时,如何显示错误消息?

Bor*_*yev 0 python unit-testing exception

我是python的新手。我想测试我的代码是否抛出异常。我从这里得到了代码:你如何测试 Python 函数抛出异常?

import mymod
import unittest

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc, compulsory_argument)
Run Code Online (Sandbox Code Playgroud)

现在,如果没有抛出异常,我还想显示一条消息。我怎么做 ?python 文档没有明确提到它。我在“compulsory_argument”之后添加了消息,但失败了。

编辑:我尝试了第一个修改后的答案并得到了一个例外。我的错误是什么?

import unittest

def sayHelloTo(name):
    print("Hello " + name)

class MyTestCase(unittest.TestCase):
    def test1(self):
        person = "John"
        with self.assertRaises(Exception, "My insightful message"):
            sayHelloTo(person)
Run Code Online (Sandbox Code Playgroud)

错误:

Error
Traceback (most recent call last):
  File "C:\tests\tester.py", line 9, in test1
    with self.assertRaises(Exception, "My insightful message"):
AttributeError: __exit__
Run Code Online (Sandbox Code Playgroud)

tde*_*ney 5

从 python 3.3 开始,assertRaises可以用作带有消息的上下文管理器:

import unittest

def sayHelloTo(name):
    print("Hello " + name)

class MyTestCase(unittest.TestCase):
    def test1(self):
        person = "John"
        with self.assertRaises(Exception, msg="My insightful message"):
            sayHelloTo(person)

if __name__ == "__main__":
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

结果是

Hello John
F
======================================================================
FAIL: test1 (__main__.MyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "r.py", line 10, in test1
    sayHelloTo(person)
AssertionError: Exception not raised : My insightful message

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)
Run Code Online (Sandbox Code Playgroud)