3
votes
    class ATestCase(unittest.TestCase):
        def test_A ...
        def test_B ...
        def test_C ...

The unittest output includes

    test_A ...
    test_B ...
    test_C ...

How can I get timestamps in front of the test names? I.e I'd like to see

    12:15:32 test_A ...
    12:15:33 test_B ...
    12:16:45 test_C ...

The obvious methods (setUp(), run...(), etc.) either place the timestamp after the test name, or lump them all together.

(This is on python 2.5)

Solved:

class MyTextTestRunner(unittest.TextTestRunner):
    def _makeResult(self):
        print >>stderr, _now(), ' ',
        return super(MyTextTestRunner,self)._makeResult()

Update: This is only a partial solution. It only outputs the time stamp for the first test in each TestCase. (test_A in the example.)

2
You could subclass TestRunner - Ramchandra Apte
It's actually TextTestRunner. Overriding _makeResult works. - Underhill
Could you post your solution as an answer and accept it? Otherwise, the question will continue to appear in the "Unanswered" tab. - Lenna

2 Answers

0
votes

Have you considered using decorators for your test methods?

Your could decorate the methods themselves or inherited ones.

Something like this.

0
votes

I know this is an old post, but for those who are trying to do this in Python3, you need to do something like this:

class myTextTestResult(unittest.TextTestResult):
    def startTest(self, test: unittest.case.TestCase) -> None:
        import datetime
        self.stream.write("\n")
        self.stream.write(str(datetime.datetime.now()) + ": ")
        return super(myTextTestResult, self).startTest(test)

And now, use this class as the resultclass while creating your TextTestRunner instance, like this:

runner = unittest.TextTestRunner(f, resultclass=myTextTestResult)

where, f is the stream object (sys.stderr by default).

The startTest method is called whenever a testcase begins execution. Writing the timestamp to the stream at this point ensures that this gets logged for every testcase executed.