fixture是pytest特有的功能,用以在測試執行前和執行后進行必要的準備和清理工作。使用pytest.fixture標識,定義在函數前面。在你編寫測試函數的時候,你可以將此函數名稱做為傳入參數,pytest將會以依賴注入方式,將該函數的返回值作為測試函數的傳入參數。
主要的目的是為了提供一種可靠和可重復性的手段去運行那些最基本的測試內容。
從功能上看來,與setup、teardown相似,但是優勢明顯:調用方法有2種:
1、在測試用例/測試類上面加上:@pytest.mark.usefixture("fixture的函數名字")
2、將fixture函數名,作為測試用例函數的參數。可以不加@pytest.mark.usefixture("fixture的函數名字")
import pytest@pytest.fixture()
def init2():print("用例執行之前,執行的代碼") # 只有模塊執行之前的前置準備代碼@pytest.mark.usefixtures('init2')
def test_1():print('test_2')@pytest.mark.usefixtures('init2')
def test_2():print('test_2')if __name__ == "__main__":pytest.main(['-v', '-s','test3.py']) #
?
import pytest@pytest.fixture
def init():print("用例執行之前,執行的代碼") # 前置代碼yield 'hello'print("用例執行之后,執行的代碼") # 后置代碼@pytest.fixture()
def init2():print("用例執行之前,執行的代碼") # 只有模塊執行之前的前置準備代碼def test_1(init):print('test_2',init)@pytest.mark.usefixtures('init2')
def test_2():print('test_2')if __name__ == "__main__":pytest.main(['-v', '-s','test3.py']) #
import pytest@pytest.fixture
def init():print("用例執行之前,執行的代碼") # 前置代碼yield 'hello'print("用例執行之后,執行的代碼") # 后置代碼@pytest.fixture()
def init2():print("用例執行之前,執行的代碼") # 只有模塊執行之前的前置準備代碼def test_1(init):print('test_2',init)@pytest.mark.usefixtures('init2')
def test_2():print('test_2')@pytest.fixture()
def data():return "hello"def test_data(data):print("============",data)if __name__ == "__main__":pytest.main(['-v', '-s','test3.py']) #
?feature 嵌套
import pytest@pytest.fixture
def init():print("用例執行之前,執行的代碼") # 前置代碼yield 'hello'print("用例執行之后,執行的代碼") # 后置代碼@pytest.fixture
def init3(init):print("用例執行2之前,執行的代碼") # 前置代碼yield initprint("用例執行2之后,執行的代碼") # 后置代碼def test_3(init3):assert init3 == 'hello'if __name__ == "__main__":pytest.main(['-v', '-s','test3.py']) #