1、xunit-style setup
相比unittest只有setUp()和tearDown(),pytest則擁有module級別、class級別、method和function級別的setup()和teardown(),能夠更好地控制用例的執行。
1.1 setup_module()和teardown_module
如果在一個.py文件中有多個測試函數和測試類,并且只想執行執行一次setup和teardown,則可選擇在該文件中使用setup_module和teardown_module。
ps:pytest3.0中,“_module”可省略
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.
"""
1.2 setup_class和teardown_class
同樣地,如果一個測試類中有多個測試方法,并且只想執行一次setup和teardown,則可選擇在該類中使用setup_class和teardown_class。
@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
setu
1.3 setup_method和teardown_method
同理,如果希望類中每個方法執行前后都執行setup和teardown,則在類中使用setup_method和teardown_method。
ps:pytest3.0后,“_method”可省略
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.
"""
1.4 setup_funciton和teardown_function
如果你直接在.py文件中定義測試函數,那么使用setup_funciton和teardown_function會在每個函數執行前后都執行一次setup和teardown。
ps:pytest3.0后,“_function”可省略
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.
"""
2、marker與參數化
通過使用pytest.mark.xxx,我們可以給測試方法添加各種標志,并且在執行的時候可以有選擇的只執行某個/某幾個標志的測試。下面是pytest內置的一些marker:
# 每次都跳過不執行
@pytest.mark.skip
# 滿足條件則跳過不執行
@pytest.mark.skipif
# 將該函數執行結果置為失敗,但是不會被統計到失敗的用例數里,而是統計到expected failures中
@pytest.mark.xfail
# 用例失敗重試,需要先安裝pytest-rerunfailures插件
@pytest.mark.flaky(reruns=2)
import pytest
values_list = [(1,2,3),(2,3,4),(3,4,5)]
@pytest.mark.parametrize('n1,n2,n3',values_list)
def test_params(n1,n2,n3):
'''將逐個判斷values_list中的元素與(1,2,3)是否相等'''
assert (n1,n2,n3) == (1,2,3)
3、pytest.fixture
3.1 pytest.fixture參數
3.1.1 scope參數
scope值可指定為session、module、class、function,對應著相應的作用域。
3.1.2 autouse參數
autouse=True表示所有測試方法執行前會默認執行該fixture
3.2 pytest.fixture實現setup和teardown
在以下的測試代碼中,在執行test_func1前,會先執行fix_func1中yield前面的代碼,相當于setup。執行完test_func1后,再執行yield后的代碼,相當于teardown。
@pytest.fixture
def fix_func1():
print('setup')
result = 1
yield result
print('teardown')
def test_func1(fix_func1):
assert 1 == fix_func1
3.3 使用fixture提供測試數據
fixture可以返回任意類型的數據,因此適合用來提供測試數據
未完待續……