【问题标题】:How do you show an error message when a test does not throw an expected exception?当测试没有抛出预期的异常时,如何显示错误消息?
【发布时间】:2017-02-16 00:31:16
【问题描述】:

我是 python 新手。我想测试我的代码是否引发异常。我从这里得到代码:How do you test that a Python function throws an exception?

import mymod
import unittest

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

现在,如果没有抛出异常,我还想显示一条消息。我怎么做 ? 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)

错误:

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

【问题讨论】:

  • raise 将通过异常,print 将打印一条消息。结合这两者以获得您想要的行为。

标签: python unit-testing exception


【解决方案1】:

从 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()

结果

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)

【讨论】:

  • 我尝试了您的代码,但出现错误。请查看我将在问题正文中添加的编辑内容。
  • @tdelany- 谢谢。现在可以了。你能告诉我为什么在你传递这样的消息后它开始工作msg="My insightful message" 吗?是什么促使您朝这个方向思考?
  • 文档中提到了一个“msg 参数”,但我没有仔细阅读它以意识到它是一个关键字参数,而不是一个位置参数。另一位用户 unutbu 指出了我的错误,这让它发挥了作用。
  • 在测试过程中引发另一个异常时,这不起作用。知道即使引发不同的异常,如何仍然发布“有见地”的消息?
【解决方案2】:

现在,如果没有抛出异常,我还想显示一条消息。我该怎么做?

unittest 的一般理念是让测试在成功时保持沉默,只有在失败时才变得冗长。因此,API 为不成功的情况提供了“msg”关键字参数,但不为成功的情况提供替代方案。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 2018-09-11
    • 2012-04-05
    相关资源
    最近更新 更多