Python Unittest shortDescription 打印出来 None

Python Unittest shortDescription printing out None

我发现了 shortDescription 功能,很想尝试一下。

shortDescription() Returns a description of the test, or None if no description has been provided. The default implementation of this method returns the first line of the test method’s docstring, if available, or None.

奇怪的是,我无法让它工作。 有人能发现我做错了什么吗?

我的 class 确实继承自 unittest.TestCase 甚至它有一个文档字符串

def test_smth(self):
    """
    TEST
    """
    self.description = 'TEST!'
    print(self.shortDescription())

在 Python 3.6

中打印出 None

doc-string第一行为空:

"""   <--- this is the first line
TEST
"""

通过删除第一个空行,您将看到您想要的内容:

"""TEST
"""

➜  /tmp cat t.py
import unittest

class UT(unittest.TestCase):
    def test_smth(self):
        """TEST"""
        print('shortDescription():', self.shortDescription())


unittest.main()
➜  /tmp python3.6 t.py
shortDescription(): TEST
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

如果您 运行 使用 -v 命令行选项进行测试,您可以看到打印的描述而不是测试方法名称:

➜  /tmp python3.6 t.py -v
test_smth (__main__.UT)
TEST ... shortDescription(): TEST
ok

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

OK

您只是在函数参数中缺少 self。 其余的事情都很好。 试试吧。