一、前言
平常寫自動化會寫一些前置fixture操作,用例需要用到直接傳該函數的參數名稱就行了。當用例很多的時候,每次都傳這個參數,會比較麻煩。
fixture里面有個參數autouse,默認是Fasle沒開啟的,可以設置為True開啟自動使用fixture功能,這樣用例就不用每次都去傳參了。
調用fixture三種方法:
(1)函數或類里面方法直接傳fixture的函數參數名稱
(2)使用裝飾器@pytest.mark.usefixtures()修飾
(3)autouse = True自動使用
二、用例傳fixture參數
方法一:先定義start功能,用例全部傳start參數,調用該功能
import time import pytest @pytest.fixture(scope="function") def start(request): print('\n----------開始執行function-----------') def test_a(start): print("-----------用例a執行----------") class Test_aaa(): def test_01(self,start): print('-----------用例01-----------') def test_02(self,start): print('-----------用例02-----------') if __name__=="__main__": pytest.main(["-s","test_06.py"])
運行結果:
三、裝飾器usefixtures
方法二:使用裝飾器@pytest.mark.usefixtures()修飾需要運行的用例
import time import pytest @pytest.fixture(scope="function") def start(request): print('\n----------開始執行function----------') @pytest.mark.usefixtures("start") def test_a(): print("----------用例a執行------------") @pytest.mark.usefixtures("start") class Test_aa(): def test_01(self): print('-----------用例01-------------') def test_02(self): print('------------用例02------------') if __name__=="__main__": pytest.main(["-s","test_07.py"])
運行結果:
四、設置autouse=True
方法三、autouse設置為Ture,自動調用fixture功能
(1)start設置scope為module級別,在當前.py用例模塊只執行一次,autouse=Ture自動使用;
(2)open_home設置scope為function級別,每個用例前都調用一次,自動調用
import time import pytest @pytest.fixture(scope="module",autouse=True) def start(request): print('\n------------開始執行module----------') print('module :%s'%request.module.__name__) print('----------啟動瀏覽器------------') yield print("----------結束測試 end!-----------") @pytest.fixture(scope="function",autouse=True) def open_home(request): print("function:%s \n----------回到首頁------------"%request.function.__name__) def test_01(): print('-----------用例01------------') def test_02(): print('-----------用例2-------------') if __name__=="__main__": pytest.main(["-s","test_08.py"])
運行結果:
上面是函數去實現用例,寫進class里面也是一樣可以的。
import time import pytest @pytest.fixture(scope="module",autouse=True) def start(request): print('\n------------開始執行module----------') print('module :%s'%request.module.__name__) print('----------啟動瀏覽器------------') yield print("----------結束測試 end!-----------") class Test_aaa(): @pytest.fixture(scope="function",autouse=True) def open_home(request): print("function:%s \n----------回到首頁------------"%request.function.__name__) def test_01(): print('-----------用例01------------') def test_02(): print('-----------用例2-------------') if __name__=="__main__": pytest.main(["-s","test_08.py"])