簡體   English   中英

在運行python unittest時顯示進度?

[英]Show progress while running python unittest?

我有一個很大的TestSuite,我從python unittest框架與TextTestRunner運行。 不幸的是,我不知道測試運行時已經完成了多少測試。

基本上,我想轉換此輸出:

test_choice (__main__.TestSequenceFunctions) ... ok
test_sample (__main__.TestSequenceFunctions) ... ok
test_shuffle (__main__.TestSequenceFunctions) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.110s

OK

[1/3] test_choice (__main__.TestSequenceFunctions) ... ok
[2/3] test_sample (__main__.TestSequenceFunctions) ... ok
[3/3] test_shuffle (__main__.TestSequenceFunctions) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.110s

OK

我是否必須TextTestRunner才能實現此目的,如果可以,怎么辦?

注意:我知道鼻子和可用的插件,但是它不太適合我的應用程序,我想避免依賴。

編輯為什么我想避免鼻子

我的應用程序基本上是測試的另一個框架。 它選擇正確的測試用例,為它們提供庫函數,並多次執行測試以進行長期測試。 (測試在外部計算機上運行)

因此,這就是我現在運行測試的方式:

# do all sort of preperations
[...]
test_suite = TestSuite()

repeatitions = 100
tests = get_tests()
for i in range(0, repeatitions):
    test_suite.addTests(tests)
TextTestRunner(verbosity=2).run(test_suite)

我鼻子的問題是,它的設計目的是從文件系統中發現測試,而我找不到清晰的文檔,了解如何直接從python在特定的TestSuite上運行它。

晚會晚了,但是希望這會幫助像我一樣來這里尋求其他解決方案的其他人:

這是子類化TextTestRunnerTextTestResult以獲得所需結果的一種方法:

import unittest
import unittest.runner
import itertools
import collections

class CustomTextTestResult(unittest.runner.TextTestResult):
    """Extension of TextTestResult to support numbering test cases"""

    def __init__(self, stream, descriptions, verbosity):
        """Initializes the test number generator, then calls super impl"""

        self.test_numbers = itertools.count(1)

        return super(CustomTextTestResult, self).__init__(stream, descriptions, verbosity)

    def startTest(self, test):
        """Writes the test number to the stream if showAll is set, then calls super impl"""

        if self.showAll:
            progress = '[{0}/{1}] '.format(next(self.test_numbers), self.test_case_count)
            self.stream.write(progress)

            # Also store the progress in the test itself, so that if it errors,
            # it can be written to the exception information by our overridden
            # _exec_info_to_string method:
            test.progress_index = progress

        return super(CustomTextTestResult, self).startTest(test)

    def _exc_info_to_string(self, err, test):
        """Gets an exception info string from super, and prepends 'Test Number' line"""

        info = super(CustomTextTestResult, self)._exc_info_to_string(err, test)

        if self.showAll:
            info = 'Test number: {index}\n{info}'.format(
                index=test.progress_index,
                info=info
            )

        return info


class CustomTextTestRunner(unittest.runner.TextTestRunner):
    """Extension of TextTestRunner to support numbering test cases"""

    resultclass = CustomTextTestResult

    def run(self, test):
        """Stores the total count of test cases, then calls super impl"""

        self.test_case_count = test.countTestCases()
        return super(CustomTextTestRunner, self).run(test)

    def _makeResult(self):
        """Creates and returns a result instance that knows the count of test cases"""

        result = super(CustomTextTestRunner, self)._makeResult()
        result.test_case_count = self.test_case_count
        return result


class TestSequenceFunctions(unittest.TestCase):
    """Dummy test case to illustrate usage"""

    fail_1 = 0
    fail_2 = 0

    def test_choice(self):
        pass

    def test_sample(self):
        self.fail_1 += 1
        if self.fail_1 == 2:
            raise Exception()

    def test_shuffle(self):
        self.fail_2 += 1
        if self.fail_2 == 3:
            raise Exception()


def get_tests():
    test_funcs = ['test_choice', 'test_sample', 'test_shuffle']
    return [TestSequenceFunctions(func) for func in test_funcs]


if __name__ == '__main__':
    test_suite = unittest.TestSuite()

    repetitions = 3
    tests = get_tests()
    for __ in xrange(0, repetitions):
        test_suite.addTests(tests)

    CustomTextTestRunner(verbosity=2).run(test_suite)

運行上面的代碼將產生以下輸出:

>>> ================================ RESTART ================================
>>> 
[1/9] test_choice (__main__.TestSequenceFunctions) ... ok
[2/9] test_sample (__main__.TestSequenceFunctions) ... ok
[3/9] test_shuffle (__main__.TestSequenceFunctions) ... ok
[4/9] test_choice (__main__.TestSequenceFunctions) ... ok
[5/9] test_sample (__main__.TestSequenceFunctions) ... ERROR
[6/9] test_shuffle (__main__.TestSequenceFunctions) ... ok
[7/9] test_choice (__main__.TestSequenceFunctions) ... ok
[8/9] test_sample (__main__.TestSequenceFunctions) ... ok
[9/9] test_shuffle (__main__.TestSequenceFunctions) ... ERROR

======================================================================
ERROR: test_sample (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Test number: [5/9] 
Traceback (most recent call last):
  File "stackoverflow.py", line 75, in test_sample
    raise Exception()
Exception

======================================================================
ERROR: test_shuffle (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Test number: [9/9] 
Traceback (most recent call last):
  File "stackoverflow.py", line 80, in test_shuffle
    raise Exception()
Exception

----------------------------------------------------------------------
Ran 9 tests in 0.042s

FAILED (errors=2)
>>> 

您將必須繼承TextTestRunner,但是我不知道如何。 我強烈建議您重新檢查對使用鼻子的厭惡。 這是一個非常強大的工具,可以輕松解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM