简体   繁体   中英

Timestamping tests under Python unittest

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

Have you considered using decorators for your test methods?

Your could decorate the methods themselves or inherited ones.

Something like this .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM