在Python中进行单元测试时,如果断言失败,如何将自定义消息与默认消息一起显示?

时间:2016-02-01 21:13:26

标签: python unit-testing

考虑以下示例:

import unittest

class MessageExampleTest(unittest.TestCase):
    def test_with_default_message(self):
        self.assertEqual('apples', 'oranges')

    def test_with_custom_message(self):
        self.assertEqual('apples', 'oranges', 'You should not compare apples and oranges.')

输出:

======================================================================
FAIL: test_with_default_message (assert_message.MessageExampleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  ...
    self.assertEqual('apples', 'oranges')
AssertionError: 'apples' != 'oranges'

======================================================================
FAIL: test_with_custom_message (assert_message.MessageExampleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  ...
    self.assertEqual('apples', 'oranges', 'You should not compare apples and oranges.')
AssertionError: You should not compare apples and oranges.


----------------------------------------------------------------------

在第二种情况下,我希望看到的是:

AssertionError: 'apples' != 'oranges'; You should not compare apples and oranges.

1 个答案:

答案 0 :(得分:1)

从Python 2.7开始,unittest现在提供了longMessage属性来执行此操作。

在Python 2.7中:

import unittest

class MessageExampleTest(unittest.TestCase):
    def setUp(self):
        self.longMessage = True

    def test_with_custom_message(self):
        self.assertEqual('apples', 'oranges', 'You should not compare apples and oranges.')

输出:

======================================================================
FAIL: test_with_custom_message (assert_message.MessageExampleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  ...
    self.assertEqual('apples', 'oranges', 'You should not compare apples and oranges.')
AssertionError: 'apples' != 'oranges' : You should not compare apples and oranges.

======================================================================