簡體   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