python unittest2 - exposing test method name to setup method

803 Views Asked by At

I need to find the name of the test method about to be run from within the SetUp() method that unittest runs before each test. How can I do this without running every test method seperately?

Example:

class Testing(unittest2.TestCase):
    def setUp():
        # wish i could write:
        string = getNextTestMethodName()

    def test_example(self):
        self.assertNotEqual(0,1)
2

There are 2 best solutions below

0
On BEST ANSWER

not even self.id() is needed:

def setUp( self ):
    logger.info( '# setUp for %s' % ( self, ))

typical output:

# setUp for test_mainframe_has_been_constructed (__main__.BasicFunctionality_FT)

... where "test_mainframe_has_been_constructed" is the method.

So repr( self ), presumably, if you just want the string - then slice and dice, observing that the method name ends with the opening bracket (or first white space).

2
On

You can use self.shortDescription() that will give you the name of the test (or the docstring associated with the test), and this, even in the setUp/tearDown methods.

EDIT: maybe self.id() is enough, it provide only the test name (thanks to @Blair).