pytest 其他測試系統(tǒng)-如何實現(xiàn)xunit風格的設(shè)置

2022-03-22 09:55 更新

本節(jié)描述了如何在每個模塊/類/函數(shù)的基礎(chǔ)上實現(xiàn)?fixture(setup和teardown測試狀態(tài))的經(jīng)典和流行的方法。

雖然這些設(shè)置/拆卸方法對于那些使用過?unittest?或?nose?的人來說很簡單,也很熟悉,但你也可以考慮使用pytest更強大的?fixture?機制,它利用了依賴注入的概念,允許使用更模塊化和更可伸縮的方法來管理測試狀態(tài),特別是對于大型項目和功能測試。您可以在同一個文件中混合使用這兩種?fixture?機制,但是可以使用?unittest?的測試方法。?TestCase?子類不能接收?fixture?參數(shù)。

模塊級setup/teardown

如果你在一個模塊中有多個測試函數(shù)和測試類,你可以選擇實現(xiàn)以下?fixture?方法,這些方法通常會被所有的函數(shù)調(diào)用一次:

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?參數(shù)是可選的。

類級別setup/teardown

同樣,下面的方法在類級別之前和之后的所有測試方法類被稱為:

@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.
    """

方法和功能級別的setup/teardown

類似地,以下方法在每個方法調(diào)用:

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?參數(shù)是可選的。

如果你更愿意直接在模塊級定義測試函數(shù),你也可以使用以下函數(shù)來實現(xiàn)?fixture?:

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?參數(shù)是可選的。

備注:

每個測試過程可以多次調(diào)用?setup/teardown?對。

如果對應的?setup?函數(shù)存在并且失敗或者被跳過,則不會調(diào)用?Teardown?函數(shù)。

在pytest-4.2之前,?xunit?風格的函數(shù)不遵守?fixture?的作用域規(guī)則,因此,例如,可以在會話作用域的自動使用?fixture?之前調(diào)用?setup_method?。

現(xiàn)在,?xunit?風格的函數(shù)與?fixture?機制集成在一起,并遵守調(diào)用中涉及的?fixture?的適當范圍規(guī)則。


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號