Python unittest,如何显示更好的组/测试名称?

Cyr*_* N. 0 python python-unittest

使用 Python Unittest,这是一个测试套件的示例:

import unittest

# Here's our "unit".
def IsOdd(n):
    return n % 2 == 1

# Here's our "unit tests".
class IsOddTests(unittest.TestCase):

    def testOne(self):
        self.failUnless(IsOdd(1))

    def testTwo(self):
        self.failIf(IsOdd(2))

def main():
    unittest.main(verbosity=2)

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

结果:

testOne (__main__.IsOddTests) ... ok
testTwo (__main__.IsOddTests) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
Run Code Online (Sandbox Code Playgroud)

是否可以增强测试的显示,例如:

Testing ODD method
Testing with value is 1 (__main__.IsOddTests) ... ok
Testing with value is 2 (__main__.IsOddTests) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
Run Code Online (Sandbox Code Playgroud)

我想要做的是,在有很多测试的情况下,为每个测试用例显示一个组名(包含多个测试),以及每个测试的名称(应该比函数名称更明确)。

Tim*_*ter 7

为此,只需为您的测试设置一个文档字符串:

def testOne(self):
    """Test IsOdd(1)"""
    self.failUnless(IsOdd(1))

def testTwo(self):
    """Test IsOdd(2)"""
    self.failIf(IsOdd(2))
Run Code Online (Sandbox Code Playgroud)

为您的测试选择文档字符串是一门艺术,以后会有意义。不要害怕回去重构你的东西。