2

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)
Blair
  • 15,356
  • 7
  • 46
  • 56
yuvalshu
  • 73
  • 4

2 Answers2

1

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

Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
  • 1
    Or [self.id()](http://docs.python.org/library/unittest.html#unittest.TestCase.id), which returns the name of the test case, which is usually the name of the test method. – Blair Dec 13 '11 at 08:24
  • thanks cedric&blair, after reviewing unittest.py i realized that the testcase holds the name of the testmethod currently running in self._testMethodName. this fills my needs as id() isn't good cause i have several testmethods within my testcase class – yuvalshu Dec 13 '11 at 09:15
0

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

mike rodent
  • 14,126
  • 11
  • 103
  • 157