繁体   English   中英

Python unittest下的时间戳测试

[英]Timestamping tests under Python unittest

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

单元测试 output 包括

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

如何在测试名称前获取时间戳? 即我想看看

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

显而易见的方法(setUp()、run...() 等)要么将时间戳放在测试名称之后,要么将它们放在一起。

(这是在 python 2.5 上)

解决了:

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

更新:这只是部分解决方案。 它仅输出每个 TestCase 中第一个测试的时间戳。 (示例中的 test_A。)

您是否考虑过使用装饰器进行测试?

你可以自己修饰方法或继承方法。

这样的东西。

我知道这是一篇旧文章,但对于那些试图在 Python3 中执行此操作的人,您需要执行以下操作:

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)

现在,在创建TextTestRunner实例时使用这个resultclass作为结果类,如下所示:

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

其中, f是 stream object(默认为sys.stderr )。

每当测试用例开始执行时,就会调用startTest方法。 此时将时间戳写入 stream 可确保记录每个执行的测试用例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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