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

How do you show an error message when a test does not throw an expected exception?

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

1
2
3
4
5
6
import mymod
import unittest

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc, compulsory_argument)

现在,如果不抛出异常,我还想显示一条消息。我该怎么做?python文档没有清楚地提到它。我在"强制争论"之后添加了这个消息,但失败了。

编辑:我修改了第一个答案,但得到了一个例外。我在这里犯了什么错误?

1
2
3
4
5
6
7
8
9
10
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)

错误:

1
2
3
4
5
Error
Traceback (most recent call last):
  File"C:\tests\tester.py", line 9, in test1
    with self.assertRaises(Exception,"My insightful message"):
AttributeError: __exit__


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

1
2
3
4
5
6
7
8
9
10
11
12
13
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()

结果在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)


Now, I also want to display a message if the exception is not thrown. How do I do that ?

UnitTest的一般原理是,测试成功时保持沉默,只有失败时才会变得冗长。因此,API为不成功的案例提供了一个"msg"关键字参数,但不提供成功案例的替代方案。

也就是说,哲学的另一部分对你有利。通常,当测试用例失败时,测试用例内部会引发异常。这意味着,如果要在成功时显示消息,只需在测试后添加另一条语句:

1
2
3
with self.assertRaises(TypeError, msg='Oh no, I did not get a TypeError')
     somecode()
logging.info('Yippee, we got a TypeError!')  # Runs after a successful test