Pytest進階 -- fixture自動應用
阿新 • • 發佈:2022-05-14
Fixture 在自動化中的應用 - 自動應用
場景:
不想原測試⽅法有任何改動,或全部都⾃動實現⾃動應⽤,
沒特例,也都不需要返回值時可以選擇⾃動應⽤
解決:
使⽤ fixture 中引數 autouse=True 實現
步驟:
在⽅法上⾯加 @pytest.fixture(autouse=True)
案例
conftest.py
import pytest @pytest.fixture(scope="function",autouse=True) #加入後所有case會自動加上這個方法 def login(): print("\nlogin.....\n") token = 123 yield token #返回token值 print(f"\nlogout.....\n")
test_demo.py
def test_search(): print("search") def test_order(): #沒有加入login,但還是會執行login,因為fixture設定了autouse print("ordering") def test_cart(): print("shopping cart..") class TestDemo: def test_case_1(self): print("test case 1") def test_case_2(self): print("test case 2")
輸出
login..... PASSED [ 20%]search logout..... test_demo.py::test_order login..... PASSED [ 40%]ordering logout..... test_demo.py::test_cart login..... PASSED [ 60%]shopping cart.. logout.....