如何使用Python`unittest``assertRaises`方法来打印`msg`参数?

时间:2017-06-10 20:10:53

标签: python-unittest

在下面,测试应该失败并打印msg参数。但事实并非如此。

with self.assertRaises(ZeroDivisionError, msg="Unexpected denominator"):
    1/1

此参数(msg)适用于所有其他assert*方法。在unittest中,似乎不太可能破坏那么基本的东西,那么这笔交易是什么?

这是一个展示问题的完整程序:

#!/usr/bin/env python2

import unittest

class TestAssertRaisesMsgParam(unittest.TestCase):

    def test_assert_raises_msg(self):
        """
        Test unittest `assertRaises` msg param is printed
        """
        with self.assertRaises(ZeroDivisionError, msg="Unexpected denominator"):
            1/1

if __name__ == '__main__':
    unittest.main()

这是我与它的互动:

$ ls -l assertRaises.py
-rwxr-xr-x 1 tom users 440 Jun 10 14:04 assertRaises.py
$ python -m unittest assertRaises
F
======================================================================
FAIL: test_assert_raises_msg (assertRaises.TestAssertRaisesMsgParam)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "assertRaises.py", line 14, in test_assert_raises_msg
    1/1
AssertionError: ZeroDivisionError not raised

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

以及一些系统信息:

$ /usr/bin/env python2
Python 2.7.13 (default, Mar 22 2017, 12:31:17) [GCC] on linux2

$ uname -a
Linux ... 4.4.62-18.6-default #1 SMP Fri Apr 21 16:14:48 UTC 2017 (84f9824) x86_64 x86_64 x86_64 GNU/Linux

1 个答案:

答案 0 :(得分:1)

您的代码在我的包装盒上运行:

$ python -m unittest tester
F
======================================================================
FAIL: test_assert_raises_msg (test.TestAssertRaisesMsgParam)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\danth\src\test.py", line 12, in test_assert_raises_msg
    1/1
AssertionError: ZeroDivisionError not raised : Unexpected denominator

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

FAILED (failures=1)

确保按照以下方式运行测试:

python -m unittest name_of_test_file