unittest 跳過測試和預(yù)期故障

2022-08-02 14:59 更新

3.1 版中的新功能。

Unittest支持跳過單個測試方法甚至整個測試類。此外,它還支持將測試標(biāo)記為“預(yù)期失敗”,即已中斷并將失敗的測試,但不應(yīng)計為 TestResult 上的失敗。

跳過測試只需使用 skip() 裝飾器或其條件變體之一,在 setUp() 或測試方法中調(diào)用 TestCase.skipTest(), 或直接引發(fā) SkipTest。

基本跳過如下所示:

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

    def test_maybe_skipped(self):
        if not external_resource_available():
            self.skipTest("external resource not available")
        # test code that depends on the external resource
        pass

這是在詳細(xì)模式下運(yùn)行上述示例的輸出:

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

----------------------------------------------------------------------
Ran 4 tests in 0.005s

OK (skipped=4)

可以像方法一樣跳過類:

@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
    def test_not_run(self):
        pass

TestCase.setUp() 也可以跳過測試。當(dāng)需要設(shè)置的資源不可用時,這很有用。

預(yù)期的故障使用預(yù)期的Failure()裝飾器。

class ExpectedFailureTestCase(unittest.TestCase):
    @unittest.expectedFailure
    def test_fail(self):
        self.assertEqual(1, 0, "broken")

通過制作一個在測試中調(diào)用 skip() 的裝飾器,當(dāng)它希望它被跳過時,很容易滾動你自己的跳過裝飾器。除非傳遞的對象具有特定屬性,否則此裝飾器會跳過測試:

def skipUnlessHasattr(obj, attr):
    if hasattr(obj, attr):
        return lambda func: func
    return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))

以下修飾器和異常實現(xiàn)測試跳過和預(yù)期故障:

?@unittest.skip(reason)?

無條件跳過裝飾測試。reason應(yīng)描述跳過測試的原因。

?@unittest.skipIf(conditionreason)?

如果條件為真,則跳過修飾測試。

?@unittest.skipUnless(condition, reason)?

跳過裝飾測試,除非條件為真。

?@unittest.expectedFailure?

將測試標(biāo)記為預(yù)期的失敗或錯誤。如果測試失敗或測試函數(shù)本身(而不是其中一個測試夾具方法)中的錯誤,則將被視為成功。如果測試通過,則將被視為失敗。

      exception ?unittest.SkipTest(reason)?

引發(fā)此異常是為了跳過測試。

通常,您可以使用 TestCase.skipTest() 或其中一個跳過的裝飾器,而不是直接引發(fā)它。

跳過的測試不會有 setUp() 或 tearDown() 圍繞它們運(yùn)行。跳過的類將不會運(yùn)行 setUpClass() 或 tearDownClass()。跳過的模塊將不會有?setUpModule()?或?tearDownModule()?運(yùn)行。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號