如何實作 xunit 風格設定

本節說明一個經典且廣受歡迎的方式,說明您如何針對每個模組/類別/函式實作固定裝置(設定和終止測試狀態)。

注意

雖然這些設定/終止方法對來自 unittestnose 背景的人來說很簡單且熟悉,但您也可以考慮使用 pytest 更強大的 固定裝置機制,它利用依賴注入的概念,允許採用更具模組化且更具擴充性的方法來管理測試狀態,特別是對於較大的專案和功能測試。您可以在同一個檔案中混合使用這兩種固定裝置機制,但 unittest.TestCase 子類別的測試方法無法接收固定裝置引數。

模組層級設定/終止

如果您在單一模組中有多個測試函式和測試類別,您可以選擇實作下列固定裝置方法,這些方法通常會針對所有函式呼叫一次

def setup_module(module):
    """setup any state specific to the execution of the given module."""


def teardown_module(module):
    """teardown any state that was previously setup with a setup_module
    method.
    """

從 pytest-3.0 開始,module 參數是選用的。

類別層級設定/終止

類似地,下列方法會在呼叫類別的所有測試方法之前和之後在類別層級呼叫

@classmethod
def setup_class(cls):
    """setup any state specific to the execution of the given class (which
    usually contains tests).
    """


@classmethod
def teardown_class(cls):
    """teardown any state that was previously setup with a call to
    setup_class.
    """

方法和函式層級設定/終止

類似地,下列方法會在每次方法呼叫周圍呼叫

def setup_method(self, method):
    """setup any state tied to the execution of the given method in a
    class.  setup_method is invoked for every test method of a class.
    """


def teardown_method(self, method):
    """teardown any state that was previously setup with a setup_method
    call.
    """

從 pytest-3.0 開始,method 參數是選用的。

如果您比較喜歡在模組層級直接定義測試函式,您也可以使用下列函式來實作固定裝置

def setup_function(function):
    """setup any state tied to the execution of the given function.
    Invoked for every test function in the module.
    """


def teardown_function(function):
    """teardown any state that was previously setup with a setup_function
    call.
    """

從 pytest-3.0 開始,function 參數是選用的。

備註

  • 在每個測試過程中,設定/清除配對可能會被呼叫多次。

  • 如果對應的設定函式存在且失敗/被跳過,則不會呼叫清除函式。

  • 在 pytest-4.2 之前,xunit 風格函式並未遵守固定裝置的範圍規則,因此有可能會在會話範圍的自動使用固定裝置之前呼叫 setup_method

    現在,xunit 風格函式已與固定裝置機制整合,並遵守呼叫中所涉及固定裝置的適當範圍規則。