Cyril N.
Cyril N.

Reputation: 39879

Python unittest, how to display a better group/test name?

Using Python Unittest, here's an example of a test suite :

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

And the result :

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

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

OK

Is it possible to enhance the display of the tests, something like :

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

What I'm trying to do, is in case of a lot of tests, displaying a Group name for each TestCase (that contains multiple tests), and a name for each tests (that should be more explicit than just the function name).

Upvotes: 1

Views: 4875

Answers (1)

Tim Potter
Tim Potter

Reputation: 2457

To do this simply set a docstring for your tests:

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

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

There's a bit of an art to picking docstrings for your tests that will make sense later. Don't be afraid to go back and refactor your things.

Upvotes: 8

Related Questions