目錄:
- 安裝及入門(mén)
- 使用和調(diào)用方法
- 原有TestSuite使用方法
- 斷言的編寫(xiě)和報(bào)告
- Pytest fixtures:清晰 模塊化 易擴(kuò)展
- 使用Marks標(biāo)記測(cè)試用例
- Monkeypatching/對(duì)模塊和環(huán)境進(jìn)行Mock
- 使用tmp目錄和文件
- 捕獲stdout及stderr輸出
- 捕獲警告信息
- 模塊及測(cè)試文件中集成doctest測(cè)試
- skip及xfail: 處理不能成功的測(cè)試用例
- Fixture方法及測(cè)試用例的參數(shù)化
- 緩存: 使用跨執(zhí)行狀態(tài)
- unittest.TestCase支持
- 運(yùn)行Nose用例
- 經(jīng)典xUnit風(fēng)格的setup/teardown
- 安裝和使用插件
- 插件編寫(xiě)
- 編寫(xiě)鉤子(hook)方法
- 運(yùn)行日志
- API參考
- 優(yōu)質(zhì)集成實(shí)踐
- 片狀測(cè)試
- Pytest導(dǎo)入機(jī)制及sys.path/PYTHONPATH
- 配置選項(xiàng)
- 示例及自定義技巧
- Bash自動(dòng)補(bǔ)全設(shè)置
經(jīng)典xUnit風(fēng)格的setup/teardown
本節(jié)介紹了如何在每個(gè)模塊/類(lèi)/功能的基礎(chǔ)上實(shí)現(xiàn)Fixture(setup和teardown測(cè)試狀態(tài))的經(jīng)典而流行的方法。
注意
雖然這些setup/teardown方法對(duì)于來(lái)自a unittest
或nose的人來(lái)說(shuō)簡(jiǎn)單且熟悉,但background
你也可以考慮使用pytest更強(qiáng)大的Fixture機(jī)制,該機(jī)制利用依賴(lài)注入的概念,允許更模塊化和更可擴(kuò)展的方法來(lái)管理測(cè)試狀態(tài),特別是對(duì)于大型項(xiàng)目和功能測(cè)試。你可以在同一文件中混合兩種Fixture機(jī)制,但unittest.TestCase
子類(lèi)的測(cè)試方法不能接收Fixture參數(shù)。
模塊級(jí)別setup/teardown
如果在單個(gè)模塊中有多個(gè)測(cè)試函數(shù)和測(cè)試類(lèi),則可以選擇實(shí)現(xiàn)以下fixture方法,這些方法通常會(huì)針對(duì)所有函數(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開(kāi)始,module
參數(shù)是可選的。
班級(jí)setup/拆解
類(lèi)似地,在調(diào)用類(lèi)的所有測(cè)試方法之前和之后,在類(lèi)級(jí)別調(diào)用以下方法:
@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.
"""
方法和功能級(jí)別setup/teardown
同樣,圍繞每個(gè)方法調(diào)用調(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開(kāi)始,method
參數(shù)是可選的。
如果你希望直接在模塊級(jí)別定義測(cè)試函數(shù),還可以使用以下函數(shù)來(lái)實(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開(kāi)始,function
參數(shù)是可選的。
備注:
每個(gè)測(cè)試過(guò)程可以多次調(diào)用setup / teardown對(duì)。
如果存在相應(yīng)的setup功能并且跳過(guò)了失敗/,則不會(huì)調(diào)用teardown功能。
-
在pytest-4.2之前,xunit樣式的函數(shù)不遵守fixture的范圍規(guī)則,因此例如
setup_method
可以在會(huì)話范圍的autouse fixture之前調(diào)用a。現(xiàn)在,xunit風(fēng)格的功能與Fixture機(jī)制集成在一起,并遵守調(diào)用中涉及的燈具的適當(dāng)范圍規(guī)則。