pythonpython-2.6unittest2

python unittest2 - exposing test method name to setup method


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)

Solution

  • 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).