unittest模塊學習(六)

25.3.6 跳過測試和預期的失敗


unittest支持跳過單獨的測試方法甚至整個測試類。此外,它還支持將測試標記爲‘預期失敗’,這是一項測試失敗並將失敗,但不應該被視爲TestResult失敗。

可以很簡單的使用skip()裝飾器或者使用其條件變體來跳過一個測試。
基本上跳過測試的行爲類似這樣:
class MyTestCase(unittest.TestCase):

    @unittest.skip("demonstrating skipping")
    def test_nothing(self):
        self.fail("shouldn't happen")

    @unittest.skipIf(mylib.__version__ < (1, 3),
                     "not supported in this library version")
    def test_format(self):
        # Tests that work for only a certain version of the library.
        pass

    @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_windows_support(self):
        # windows specific testing code
        pass

這是以詳細模式運行上述示例的輸出: 

test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'

----------------------------------------------------------------------
Ran 3 tests in 0.005s

OK (skipped=3)

類可以像方法一樣跳過:

@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
    def test_not_run(self):
        pass
TestCase.setUp()也可以跳過測試。當需要建立的資源不可用時,這非常有用。
預期失敗使用expectedFailure()裝飾器。
class ExpectedFailureTestCase(unittest.TestCase):
    @unittest.expectedFailure
    def test_fail(self):
        self.assertEqual(1, 0, "broken")
通過在測試中可以很容易調用skip()的裝飾器來跳過自己的跳過裝飾器。除非傳遞的對象具有特定的屬性,否則此裝飾器將跳過測試:
def skipUnlessHasattr(obj, attr):
    if hasattr(obj, attr):
        return lambda func: func
    return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
以下裝飾器實現測試跳過和預期失敗:
-unittest.skip(reason)

無條件地跳過裝飾測試。理由應該描述爲什麼測試被跳過。

-unittest.skipIf(condition, reason)

跳過測試,如果條件爲True

-unittest.skipUnless(condition, reason)

跳過測試,除非條件爲True

-unittest.expectedFailure()

將測試標記爲預期的失敗。如果運行時測試失敗,測試不算做失敗。

-exception unittest.SkipTest(reason)

這個exception升起則跳過該測試

通常你可以使用TestCase.skipTest()或者其中一個跳過的裝飾器,而不是直接引用它。
被跳過的測試沒有setUp()和testDown()方法運行。跳過類也沒有setUpClass()和tearDownClass()方法運行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章