如何實作 xunit 風格的設定¶
本節描述了一種經典且流行的方法,說明如何基於每個模組/類別/函數實作 fixtures (設定和拆卸測試狀態)。
注意
雖然這些設定/拆卸方法對於來自 unittest
或 nose
背景的人來說簡單且熟悉,但您也可以考慮使用 pytest 更強大的 fixture 機制,它利用了依賴注入的概念,為管理測試狀態提供了更模組化和更具擴展性的方法,特別是對於較大的專案和功能測試。您可以在同一個檔案中混合使用這兩種 fixture 機制,但 unittest.TestCase
子類別的測試方法無法接收 fixture 參數。
模組層級設定/拆卸¶
如果您在單一模組中有多個測試函數和測試類別,您可以選擇實作以下 fixture 方法,這些方法通常會為所有函數調用一次
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
參數是可選的。
如果您寧願直接在模組層級定義測試函數,您也可以使用以下函數來實作 fixtures
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 風格的函數不遵守 fixtures 的 scope 規則,因此,例如,有可能在 session-scoped autouse fixture 之前調用
setup_method
。現在 xunit 風格的函數已與 fixture 機制整合,並遵守調用中涉及的 fixtures 的正確 scope 規則。